text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _key_index_iter(self) -> Iterator[Tuple[str, Any]]: """ Allows for iteration over the ``KeyIndex`` values. This function is intended to be assigned to a newly created KeyIndex class. It enables iteration over the ``KeyIndex`` names and values. We don't use a mixin to avoid issues with YAML. Note: ...
[ "def", "_key_index_iter", "(", "self", ")", "->", "Iterator", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ":", "for", "k", ",", "v", "in", "vars", "(", "self", ")", ".", "items", "(", ")", ":", "yield", "k", ",", "v" ]
45.166667
29.416667
def _validate(cls, engine, *version_cols): """ Validates the archive table. Validates the following criteria: - all version columns exist in the archive table - the python types of the user table and archive table columns are the same - a user_id column exist...
[ "def", "_validate", "(", "cls", ",", "engine", ",", "*", "version_cols", ")", ":", "cls", ".", "_version_col_names", "=", "set", "(", ")", "for", "version_column_ut", "in", "version_cols", ":", "# Make sure all version columns exist on this table", "version_col_name",...
52.139535
25.116279
def to_pandas_dataframe(self): """ Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame. Each record in the RDD becomes and column, and the DataFrame is indexed with a DatetimeIndex generated from this RDD's index. """ pd_index = self...
[ "def", "to_pandas_dataframe", "(", "self", ")", ":", "pd_index", "=", "self", ".", "index", "(", ")", ".", "to_pandas_index", "(", ")", "return", "pd", ".", "DataFrame", ".", "from_items", "(", "self", ".", "collect", "(", ")", ")", ".", "set_index", "...
45.888889
21.666667
def _get_populate_values(self, instance) -> Tuple[str, str]: """Gets all values (for each language) from the specified's instance's `populate_from` field. Arguments: instance: The instance to get the values from. Returns: A list of (lang_code, va...
[ "def", "_get_populate_values", "(", "self", ",", "instance", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "return", "[", "(", "lang_code", ",", "self", ".", "_get_populate_from_value", "(", "instance", ",", "self", ".", "populate_from", ",", "lang...
27.043478
18.347826
def module_names(self): """get all the modules in the controller_prefix :returns: set, a set of string module names """ controller_prefix = self.controller_prefix _module_name_cache = self._module_name_cache if controller_prefix in _module_name_cache: return ...
[ "def", "module_names", "(", "self", ")", ":", "controller_prefix", "=", "self", ".", "controller_prefix", "_module_name_cache", "=", "self", ".", "_module_name_cache", "if", "controller_prefix", "in", "_module_name_cache", ":", "return", "_module_name_cache", "[", "co...
33.458333
19.375
def ad_hoc_magic_from_file(filename, **kwargs): """Ad-hoc emulation of magic.from_file from python-magic.""" with open(filename, 'rb') as stream: head = stream.read(16) if head[:4] == b'\x7fELF': return b'application/x-executable' elif head[:2] == b'MZ': return b'...
[ "def", "ad_hoc_magic_from_file", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "stream", ":", "head", "=", "stream", ".", "read", "(", "16", ")", "if", "head", "[", ":", "4", "]", "==",...
38.7
6.9
def getLabelByName(self, name): """Gets a label widget by it component name :param name: name of the AbstractStimulusComponent which this label is named after :type name: str :returns: :class:`DragLabel<sparkle.gui.drag_label.DragLabel>` """ name = name.lower() i...
[ "def", "getLabelByName", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "in", "self", ".", "stimLabels", ":", "return", "self", ".", "stimLabels", "[", "name", "]", "else", ":", "return", "None" ]
34.5
17.333333
def add_item(self, *args, **kwargs): """Pass through to provider methods.""" try: self._get_provider_session('assessment_basic_authoring_session').add_item(*args, **kwargs) except InvalidArgument: self._get_sub_package_provider_session( 'assessment_authori...
[ "def", "add_item", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "_get_provider_session", "(", "'assessment_basic_authoring_session'", ")", ".", "add_item", "(", "*", "args", ",", "*", "*", "kwargs", ")", "exc...
54.714286
25.428571
def delete_index(self,*fields): """Delete the index on the specified fields""" for f in fields: if not f in self.indices: raise ValueError,"No index on field %s" %f for f in fields: del self.indices[f] self.commit()
[ "def", "delete_index", "(", "self", ",", "*", "fields", ")", ":", "for", "f", "in", "fields", ":", "if", "not", "f", "in", "self", ".", "indices", ":", "raise", "ValueError", ",", "\"No index on field %s\"", "%", "f", "for", "f", "in", "fields", ":", ...
35.875
10.75
def vnormg(v, ndim): """ Compute the magnitude of a double precision vector of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vnormg_c.html :param v: Vector whose magnitude is to be found. :type v: Array of floats :param ndim: Dimension of v :type ndim: int ...
[ "def", "vnormg", "(", "v", ",", "ndim", ")", ":", "v", "=", "stypes", ".", "toDoubleVector", "(", "v", ")", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "return", "libspice", ".", "vnormg_c", "(", "v", ",", "ndim", ")" ]
31.125
18.5
def getThings(self): """ Get the things registered in your account :return: dict with things registered in the logged in account and API call status """ login_return = self._is_logged_in() # raise NameError("Please login first using the login function, with username...
[ "def", "getThings", "(", "self", ")", ":", "login_return", "=", "self", ".", "_is_logged_in", "(", ")", "# raise NameError(\"Please login first using the login function, with username and password\")", "data", "=", "{", "\"path\"", ":", "\"/thing\"", ",", "\"host\"", ":",...
38.066667
18.933333
def reset_position_scales(self): """ Reset x and y scales """ if not self.facet.shrink: return with suppress(AttributeError): self.panel_scales_x.reset() with suppress(AttributeError): self.panel_scales_y.reset()
[ "def", "reset_position_scales", "(", "self", ")", ":", "if", "not", "self", ".", "facet", ".", "shrink", ":", "return", "with", "suppress", "(", "AttributeError", ")", ":", "self", ".", "panel_scales_x", ".", "reset", "(", ")", "with", "suppress", "(", "...
23.916667
11.25
def find_additional_rels(self, all_models): """Attempts to scan for additional relationship fields for this model based on all of the other models' structures and relationships. """ for model_name, model in iteritems(all_models): if model_name != self.name: fo...
[ "def", "find_additional_rels", "(", "self", ",", "all_models", ")", ":", "for", "model_name", ",", "model", "in", "iteritems", "(", "all_models", ")", ":", "if", "model_name", "!=", "self", ".", "name", ":", "for", "field_name", "in", "model", ".", "field_...
56.958333
18.541667
def _sample_aAt(self,n): """Sampling frequencies, angles, and times part of sampling, for stream with gap""" # Use streamdf's _sample_aAt to generate unperturbed frequencies, # angles Om,angle,dt= super(streamgapdf,self)._sample_aAt(n) # Now rewind angles by timpact, apply the ki...
[ "def", "_sample_aAt", "(", "self", ",", "n", ")", ":", "# Use streamdf's _sample_aAt to generate unperturbed frequencies,", "# angles", "Om", ",", "angle", ",", "dt", "=", "super", "(", "streamgapdf", ",", "self", ")", ".", "_sample_aAt", "(", "n", ")", "# Now r...
51.84
23.08
def graph_from_cov_df(df, threshold=.5, gain=2., n=None, class_dict=CLASSES): """Compose pair of lists of dicts (nodes, edges) for the graph described by a DataFrame""" n = n or len(df) nodes = [{'group': class_dict.get(name, 0), "name": name} for name in df.index.values][:n] edges = [] for i, (row_...
[ "def", "graph_from_cov_df", "(", "df", ",", "threshold", "=", ".5", ",", "gain", "=", "2.", ",", "n", "=", "None", ",", "class_dict", "=", "CLASSES", ")", ":", "n", "=", "n", "or", "len", "(", "df", ")", "nodes", "=", "[", "{", "'group'", ":", ...
56.9
24.1
def prepend_http(url): """ Ensure there's a scheme specified at the beginning of a url, defaulting to http:// >>> prepend_http('duckduckgo.com') 'http://duckduckgo.com' """ url = url.lstrip() if not urlparse(url).scheme: return 'http://' + url return url
[ "def", "prepend_http", "(", "url", ")", ":", "url", "=", "url", ".", "lstrip", "(", ")", "if", "not", "urlparse", "(", "url", ")", ".", "scheme", ":", "return", "'http://'", "+", "url", "return", "url" ]
28.2
13.5
def group(self, p_todos): """ Groups the todos according to the given group string. """ # preorder todos for the group sort p_todos = _apply_sort_functions(p_todos, self.pregroupfunctions) # initialize result with a single group result = OrderedDict([((), p_todos...
[ "def", "group", "(", "self", ",", "p_todos", ")", ":", "# preorder todos for the group sort", "p_todos", "=", "_apply_sort_functions", "(", "p_todos", ",", "self", ".", "pregroupfunctions", ")", "# initialize result with a single group", "result", "=", "OrderedDict", "(...
34.058824
17.117647
def properties(lines): """Parse properties block Returns: dict: {property_type: (atom_index, value)} """ results = {} for i, line in enumerate(lines): type_ = line[3:6] if type_ not in ["CHG", "RAD", "ISO"]: continue # Other properties are not supported yet ...
[ "def", "properties", "(", "lines", ")", ":", "results", "=", "{", "}", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "type_", "=", "line", "[", "3", ":", "6", "]", "if", "type_", "not", "in", "[", "\"CHG\"", ",", "\"RAD\"", ...
30.944444
13.833333
def sendintr(self): '''This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. ''' n, byte = self.ptyproc.sendintr() self._log_control(byte)
[ "def", "sendintr", "(", "self", ")", ":", "n", ",", "byte", "=", "self", ".", "ptyproc", ".", "sendintr", "(", ")", "self", ".", "_log_control", "(", "byte", ")" ]
35.666667
19
def build_metamodel(self, id_generator=None): ''' Build and return a *xtuml.MetaModel* containing previously loaded input. ''' m = xtuml.MetaModel(id_generator) self.populate(m) return m
[ "def", "build_metamodel", "(", "self", ",", "id_generator", "=", "None", ")", ":", "m", "=", "xtuml", ".", "MetaModel", "(", "id_generator", ")", "self", ".", "populate", "(", "m", ")", "return", "m" ]
27.111111
23.111111
def delete_row(self, index): """"Deletes the row from the worksheet at the specified index. :param index: Index of a row for deletion. :type index: int """ body = { "requests": [{ "deleteDimension": { "range": { ...
[ "def", "delete_row", "(", "self", ",", "index", ")", ":", "body", "=", "{", "\"requests\"", ":", "[", "{", "\"deleteDimension\"", ":", "{", "\"range\"", ":", "{", "\"sheetId\"", ":", "self", ".", "id", ",", "\"dimension\"", ":", "\"ROWS\"", ",", "\"start...
28.5
14.45
def get_node(self, key): """ return the node with the key or None if it does not exist """ self._check_if_open() try: if not key.startswith('/'): key = '/' + key return self._handle.get_node(self.root, key) except _table_mod.exceptions.NoSuchNodeEr...
[ "def", "get_node", "(", "self", ",", "key", ")", ":", "self", ".", "_check_if_open", "(", ")", "try", ":", "if", "not", "key", ".", "startswith", "(", "'/'", ")", ":", "key", "=", "'/'", "+", "key", "return", "self", ".", "_handle", ".", "get_node"...
37.777778
12.333333
def exec_request(self, URL): """Sends the actual request; returns response.""" ## Throttle request, if need be interval = time.time() - self.__ts_last_req if (interval < self.__min_req_interval): time.sleep( self.__min_req_interval - interval ) ## Construct ...
[ "def", "exec_request", "(", "self", ",", "URL", ")", ":", "## Throttle request, if need be", "interval", "=", "time", ".", "time", "(", ")", "-", "self", ".", "__ts_last_req", "if", "(", "interval", "<", "self", ".", "__min_req_interval", ")", ":", "time", ...
41.62069
19.103448
def _writeSedimentTable(self, session, fileObject, mapTable, replaceParamFile): """ Write Sediment Mapping Table Method This method writes the sediments special mapping table case. """ # Write the sediment mapping table header fileObject.write('%s\n' % (mapTable.name)) ...
[ "def", "_writeSedimentTable", "(", "self", ",", "session", ",", "fileObject", ",", "mapTable", ",", "replaceParamFile", ")", ":", "# Write the sediment mapping table header", "fileObject", ".", "write", "(", "'%s\\n'", "%", "(", "mapTable", ".", "name", ")", ")", ...
36.372093
22.930233
def run_type(self): """ Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs. TODO: Fix for other functional types like PW91, other vdW types, etc. """ METAGGA_TYPES = {"TPSS", "RTPSS", "M06L", "MBJL", "SCAN", "MS0", "MS1", "MS2"} if self.parameters.g...
[ "def", "run_type", "(", "self", ")", ":", "METAGGA_TYPES", "=", "{", "\"TPSS\"", ",", "\"RTPSS\"", ",", "\"M06L\"", ",", "\"MBJL\"", ",", "\"SCAN\"", ",", "\"MS0\"", ",", "\"MS1\"", ",", "\"MS2\"", "}", "if", "self", ".", "parameters", ".", "get", "(", ...
37.28
21.92
def updateAndFlush(self, login, tableName, cells): """ Parameters: - login - tableName - cells """ self.send_updateAndFlush(login, tableName, cells) self.recv_updateAndFlush()
[ "def", "updateAndFlush", "(", "self", ",", "login", ",", "tableName", ",", "cells", ")", ":", "self", ".", "send_updateAndFlush", "(", "login", ",", "tableName", ",", "cells", ")", "self", ".", "recv_updateAndFlush", "(", ")" ]
22.444444
15.333333
def modify(self, fields=None, **fields_kwargs): """update the fields of this instance with the values in dict fields this should rarely be messed with, if you would like to manipulate the fields you should override _modify() :param fields: dict, the fields in a dict :param **fi...
[ "def", "modify", "(", "self", ",", "fields", "=", "None", ",", "*", "*", "fields_kwargs", ")", ":", "modified_fields", "=", "set", "(", ")", "fields", "=", "self", ".", "make_dict", "(", "fields", ",", "fields_kwargs", ")", "fields", "=", "self", ".", ...
43.047619
17.666667
def levels(self): """ Return a sequence of |CategoryLevel| objects representing the hierarchy of this category collection. The sequence is empty when the category collection is not hierarchical, that is, contains only leaf-level categories. The levels are ordered from the leaf le...
[ "def", "levels", "(", "self", ")", ":", "cat", "=", "self", ".", "_xChart", ".", "cat", "if", "cat", "is", "None", ":", "return", "[", "]", "return", "[", "CategoryLevel", "(", "lvl", ")", "for", "lvl", "in", "cat", ".", "lvls", "]" ]
44
19.692308
def edit(self, description='', files={}): """Edit this gist. :param str description: (optional), description of the gist :param dict files: (optional), files that make up this gist; the key(s) should be the file name(s) and the values should be another (optional) diction...
[ "def", "edit", "(", "self", ",", "description", "=", "''", ",", "files", "=", "{", "}", ")", ":", "data", "=", "{", "}", "json", "=", "None", "if", "description", ":", "data", "[", "'description'", "]", "=", "description", "if", "files", ":", "data...
36.583333
20.458333
def _get(self, url, params={}): """Wrapper around request.get() to use the API prefix. Returns a JSON response.""" req = self._session.get(self._api_prefix + url, params=params) return self._action(req)
[ "def", "_get", "(", "self", ",", "url", ",", "params", "=", "{", "}", ")", ":", "req", "=", "self", ".", "_session", ".", "get", "(", "self", ".", "_api_prefix", "+", "url", ",", "params", "=", "params", ")", "return", "self", ".", "_action", "("...
55.75
11.75
def filedown(environ, filename, cache=True, cache_timeout=None, action=None, real_filename=None, x_sendfile=False, x_header_name=None, x_filename=None, fileobj=None, default_mimetype='application/octet-stream'): """ @param filename: is used for display in download @param real_filename: if used f...
[ "def", "filedown", "(", "environ", ",", "filename", ",", "cache", "=", "True", ",", "cache_timeout", "=", "None", ",", "action", "=", "None", ",", "real_filename", "=", "None", ",", "x_sendfile", "=", "False", ",", "x_header_name", "=", "None", ",", "x_f...
40.982906
21.478632
def list_availability_zones(call=None): ''' List all availability zones in the current region ''' ret = {} params = {'Action': 'DescribeZones', 'RegionId': get_location()} items = query(params) for zone in items['Zones']['Zone']: ret[zone['ZoneId']] = {} for i...
[ "def", "list_availability_zones", "(", "call", "=", "None", ")", ":", "ret", "=", "{", "}", "params", "=", "{", "'Action'", ":", "'DescribeZones'", ",", "'RegionId'", ":", "get_location", "(", ")", "}", "items", "=", "query", "(", "params", ")", "for", ...
24.9375
19.9375
def _trigger(self): """ Add stats to json and dump to disk. Note that this method is idempotent. """ if len(self._stat_now): self._stat_now['epoch_num'] = self.epoch_num self._stat_now['global_step'] = self.global_step self._stats.append(self....
[ "def", "_trigger", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_stat_now", ")", ":", "self", ".", "_stat_now", "[", "'epoch_num'", "]", "=", "self", ".", "epoch_num", "self", ".", "_stat_now", "[", "'global_step'", "]", "=", "self", ".", "...
31.833333
11.5
def release(self): """Create a release 1. Perform Sanity checks on work file. 2. Copy work file to releasefile location. 3. Perform cleanup actions on releasefile. :returns: True if successfull, False if not. :rtype: bool :raises: None """ log.in...
[ "def", "release", "(", "self", ")", ":", "log", ".", "info", "(", "\"Releasing: %s\"", ",", "self", ".", "_workfile", ".", "get_fullpath", "(", ")", ")", "ac", "=", "self", ".", "build_actions", "(", ")", "ac", ".", "execute", "(", "self", ")", "s", ...
30.25
13.95
def info(gandi, resource, id): """ Display information about a vhost. Resource must be the vhost fqdn. """ output_keys = ['name', 'state', 'date_creation', 'paas_name', 'ssl'] if id: # When we will have more than paas vhost, we will append rproxy_id output_keys.append('paas_id') ...
[ "def", "info", "(", "gandi", ",", "resource", ",", "id", ")", ":", "output_keys", "=", "[", "'name'", ",", "'state'", ",", "'date_creation'", ",", "'paas_name'", ",", "'ssl'", "]", "if", "id", ":", "# When we will have more than paas vhost, we will append rproxy_i...
29.785714
19.75
def toggle_axes(self, parameters = None): '''Toggle axes [x,y,z] on and off for the current representation Parameters: dictionary of parameters to control axes: position/p: origin of axes length/l: length of axis offset/o: offset to place axis labels ...
[ "def", "toggle_axes", "(", "self", ",", "parameters", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_axes_reps", ")", ">", "0", ":", "for", "rep_id", "in", "self", ".", "_axes_reps", ":", "self", ".", "remove_representation", "(", "rep_id", ")...
54.634921
26.253968
def _backup(path, filename): """ Backup a file. """ target = os.path.join(path, filename) if os.path.isfile(target): dt = datetime.now() new_filename = ".{0}.{1}.{2}".format( filename, dt.isoformat(), "backup" ) destination = os.path.join(path, new_filenam...
[ "def", "_backup", "(", "path", ",", "filename", ")", ":", "target", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "target", ")", ":", "dt", "=", "datetime", ".", "now", "(", ...
28.117647
11.764706
def CreateMenuBar(self): """Create our menu-bar for triggering operations""" menubar = wx.MenuBar() menu = wx.Menu() menu.Append(ID_OPEN, _('&Open Profile'), _('Open a cProfile file')) menu.Append(ID_OPEN_MEMORY, _('Open &Memory'), _('Open a Meliae memory-dump file')) men...
[ "def", "CreateMenuBar", "(", "self", ")", ":", "menubar", "=", "wx", ".", "MenuBar", "(", ")", "menu", "=", "wx", ".", "Menu", "(", ")", "menu", ".", "Append", "(", "ID_OPEN", ",", "_", "(", "'&Open Profile'", ")", ",", "_", "(", "'Open a cProfile fi...
43.344262
20.04918
def loadUiType(uifile, from_imports=False, resource_suffix='_rc', import_from='.'): """loadUiType(uifile, from_imports=False, resource_suffix='_rc', import_from='.') -> (form class, base class) Load a Qt Designer .ui file and return the generated form class and the Qt base class. uifile is a file name...
[ "def", "loadUiType", "(", "uifile", ",", "from_imports", "=", "False", ",", "resource_suffix", "=", "'_rc'", ",", "import_from", "=", "'.'", ")", ":", "import", "sys", "from", "PyQt5", "import", "QtWidgets", "if", "sys", ".", "hexversion", ">=", "0x03000000"...
41.823529
28.117647
def doframe(self, v): """This method will set the measure specified as part of a frame. If conversion from one type to another is necessary (with the measure function), the following frames should be set if one of the reference types involved in the conversion is as in the following lis...
[ "def", "doframe", "(", "self", ",", "v", ")", ":", "if", "not", "is_measure", "(", "v", ")", ":", "raise", "TypeError", "(", "'Argument is not a measure'", ")", "if", "(", "v", "[", "\"type\"", "]", "==", "\"frequency\"", "and", "v", "[", "\"refer\"", ...
22.428571
21.714286
def extract_package_dir(self): # type: () -> Optional[str] """ Get the package_dir dictionary from source :return: """ # package_dir={'': 'lib'}, source = self.setup_py_source() if not source: # this happens when the setup.py file is missing ...
[ "def", "extract_package_dir", "(", "self", ")", ":", "# type: () -> Optional[str]", "# package_dir={'': 'lib'},", "source", "=", "self", ".", "setup_py_source", "(", ")", "if", "not", "source", ":", "# this happens when the setup.py file is missing", "return", "None", "# ...
32.962264
14.849057
def default_logger(name): """Return a toplevel logger. This should be used only in the toplevel file. Files deeper in the hierarchy should use ``logger = logging.getLogger(__name__)``, in order to considered as children of the toplevel logger. Beware that without a setLevel() somewhere, th...
[ "def", "default_logger", "(", "name", ")", ":", "# https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "# this is a basic handler, with output to stderr", "logger_handler", "=", "logging", ".", ...
36.185185
21.111111
def _set_vrrp_rbridge_global(self, v, load=False): """ Setter method for vrrp_rbridge_global, mapped from YANG variable /vrrp_rbridge_global (container) If this variable is read-only (config: false) in the source YANG file, then _set_vrrp_rbridge_global is considered as a private method. Backends lo...
[ "def", "_set_vrrp_rbridge_global", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",...
81.227273
37.590909
def _apply_outputter(self, func, mod): ''' Apply the __outputter__ variable to the functions ''' if hasattr(mod, '__outputter__'): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__]
[ "def", "_apply_outputter", "(", "self", ",", "func", ",", "mod", ")", ":", "if", "hasattr", "(", "mod", ",", "'__outputter__'", ")", ":", "outp", "=", "mod", ".", "__outputter__", "if", "func", ".", "__name__", "in", "outp", ":", "func", ".", "__output...
35.875
12.625
def build_stack_changes(stack_name, new_stack, old_stack, new_params, old_params): """Builds a list of strings to represent the the parameters (if changed) and stack diff""" from_file = "old_%s" % (stack_name,) to_file = "new_%s" % (stack_name,) lines = difflib.context_diff(...
[ "def", "build_stack_changes", "(", "stack_name", ",", "new_stack", ",", "old_stack", ",", "new_params", ",", "old_params", ")", ":", "from_file", "=", "\"old_%s\"", "%", "(", "stack_name", ",", ")", "to_file", "=", "\"new_%s\"", "%", "(", "stack_name", ",", ...
39.52381
14
def output(self, kind, line): "*line* should be bytes" self.destination.write(b''.join([ self._cyan, b't=%07d' % (time.time() - self._t0), self._reset, self._kind_prefixes[kind], self.markers[kind], line, self._reset, ...
[ "def", "output", "(", "self", ",", "kind", ",", "line", ")", ":", "self", ".", "destination", ".", "write", "(", "b''", ".", "join", "(", "[", "self", ".", "_cyan", ",", "b't=%07d'", "%", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_...
29.25
12.416667
def diff_charsToLines(self, diffs, lineArray): """Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings. """ for i in range(len(diffs)): text = [] for char in diffs[i][1]: ...
[ "def", "diff_charsToLines", "(", "self", ",", "diffs", ",", "lineArray", ")", ":", "for", "i", "in", "range", "(", "len", "(", "diffs", ")", ")", ":", "text", "=", "[", "]", "for", "char", "in", "diffs", "[", "i", "]", "[", "1", "]", ":", "text...
29.923077
12.461538
def temporal_latent_to_dist(name, x, hparams, output_channels=None): """Network that maps a time-indexed list of 3-D latents to a gaussian. Args: name: variable scope. x: List of 4-D Tensors indexed by time, (NHWC) hparams: tf.contrib.training.Hparams. output_channels: int, Number of channels of th...
[ "def", "temporal_latent_to_dist", "(", "name", ",", "x", ",", "hparams", ",", "output_channels", "=", "None", ")", ":", "_", ",", "_", ",", "width", ",", "_", ",", "res_channels", "=", "common_layers", ".", "shape_list", "(", "x", ")", "if", "output_chan...
44.35
19.875
def get_lines(file_path=BOOK_PATH): r""" Retrieve text lines from the manuscript Chapter*.asc and Appendix*.asc files Args: file_path (str): Path to directory containing manuscript asciidoc files i.e.: /Users/cole-home/repos/nlpinaction/manuscript/ or nlpia.constants.BOOK_PATH Returns: ...
[ "def", "get_lines", "(", "file_path", "=", "BOOK_PATH", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "file_path", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "file_path", ",", "'*.asc'", ")", "files", "=", "glob", ".", ...
35.212121
18.969697
def AddWarning(self, warning): """Adds a warnings. Args: warning (ExtractionWarning): warning. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed. """ self._RaiseIfNotWritable() warning = self._PrepareAttributeContainer(warning) ...
[ "def", "AddWarning", "(", "self", ",", "warning", ")", ":", "self", ".", "_RaiseIfNotWritable", "(", ")", "warning", "=", "self", ".", "_PrepareAttributeContainer", "(", "warning", ")", "self", ".", "_warnings", ".", "append", "(", "warning", ")", "self", ...
23.1875
18.0625
def onSelect_specimen(self, event): """ update figures and text when a new specimen is selected """ self.selected_meas = [] self.select_specimen(str(self.specimens_box.GetValue())) if self.ie_open: self.ie.change_selected(self.current_fit) self.update_...
[ "def", "onSelect_specimen", "(", "self", ",", "event", ")", ":", "self", ".", "selected_meas", "=", "[", "]", "self", ".", "select_specimen", "(", "str", "(", "self", ".", "specimens_box", ".", "GetValue", "(", ")", ")", ")", "if", "self", ".", "ie_ope...
35.888889
11
def _parse_row(rowvalues, rowtypes): """ Scan a single row from an Excel file, and return the list of ranges corresponding to each consecutive span of non-empty cells in this row. If all cells are empty, return an empty list. Each "range" in the list is a tuple of the form `(startcol, endcol)`. ...
[ "def", "_parse_row", "(", "rowvalues", ",", "rowtypes", ")", ":", "n", "=", "len", "(", "rowvalues", ")", "assert", "n", "==", "len", "(", "rowtypes", ")", "if", "not", "n", ":", "return", "[", "]", "range_start", "=", "None", "ranges", "=", "[", "...
36.52381
20.333333
def create_app(**config): """Application Factory You can create a new He-Man application with:: from heman.config import create_app app = create_app() # app can be uses as WSGI application app.run() # Or you can run as a simple web server """ app = Flask( __name__, sta...
[ "def", "create_app", "(", "*", "*", "config", ")", ":", "app", "=", "Flask", "(", "__name__", ",", "static_folder", "=", "None", ")", "if", "'MONGO_URI'", "in", "os", ".", "environ", ":", "app", ".", "config", "[", "'MONGO_URI'", "]", "=", "os", ".",...
24.888889
21.518519
def leave_group(self, group_id, timeout=None): """Call leave group API. https://devdocs.line.me/en/#leave Leave a group. :param str group_id: Group ID :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, ...
[ "def", "leave_group", "(", "self", ",", "group_id", ",", "timeout", "=", "None", ")", ":", "self", ".", "_post", "(", "'/v2/bot/group/{group_id}/leave'", ".", "format", "(", "group_id", "=", "group_id", ")", ",", "timeout", "=", "timeout", ")" ]
32.944444
17.888889
def flags_from_dict(kw): """ This turns a dict with keys that are flags (e.g. for CLOSECIRCUIT, CLOSESTREAM) only if the values are true. """ if len(kw) == 0: return '' flags = '' for (k, v) in kw.items(): if v: flags += ' ' + str(k) # note that we want the ...
[ "def", "flags_from_dict", "(", "kw", ")", ":", "if", "len", "(", "kw", ")", "==", "0", ":", "return", "''", "flags", "=", "''", "for", "(", "k", ",", "v", ")", "in", "kw", ".", "items", "(", ")", ":", "if", "v", ":", "flags", "+=", "' '", "...
23.1875
20.1875
def re_filter(text, regexps): """Filter text using regular expressions.""" if not regexps: return text matched_text = [] compiled_regexps = [re.compile(x) for x in regexps] for line in text: if line in matched_text: continue for regexp in compiled_regexps: ...
[ "def", "re_filter", "(", "text", ",", "regexps", ")", ":", "if", "not", "regexps", ":", "return", "text", "matched_text", "=", "[", "]", "compiled_regexps", "=", "[", "re", ".", "compile", "(", "x", ")", "for", "x", "in", "regexps", "]", "for", "line...
26.647059
15.705882
def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really ...
[ "def", "get_hash", "(", "path", ",", "form", "=", "'sha256'", ",", "chunk_size", "=", "65536", ")", ":", "hash_type", "=", "hasattr", "(", "hashlib", ",", "form", ")", "and", "getattr", "(", "hashlib", ",", "form", ")", "or", "None", "if", "hash_type",...
43.2
22.4
def build_table(table, meta_data): """ This returns a table object with all rows and cells correctly populated. """ # Create a blank table element. table_el = etree.Element('table') w_namespace = get_namespace(table, 'w') # Get the rowspan values for cells that have a rowspan. row_span...
[ "def", "build_table", "(", "table", ",", "meta_data", ")", ":", "# Create a blank table element.", "table_el", "=", "etree", ".", "Element", "(", "'table'", ")", "w_namespace", "=", "get_namespace", "(", "table", ",", "'w'", ")", "# Get the rowspan values for cells ...
28.958333
13.375
def collect_vocab(qp_pairs): ''' Build the vocab from corpus. ''' vocab = set() for qp_pair in qp_pairs: for word in qp_pair['question_tokens']: vocab.add(word['word']) for word in qp_pair['passage_tokens']: vocab.add(word['word']) return vocab
[ "def", "collect_vocab", "(", "qp_pairs", ")", ":", "vocab", "=", "set", "(", ")", "for", "qp_pair", "in", "qp_pairs", ":", "for", "word", "in", "qp_pair", "[", "'question_tokens'", "]", ":", "vocab", ".", "add", "(", "word", "[", "'word'", "]", ")", ...
27.090909
15.272727
def ec2_elasticip_elasticip_ipaddress(self, lookup, default=None): """ Args: lookup: the CloudFormation resource name of the Elastic IP address to look up default: the optional value to return if lookup failed; returns None if not set Returns: The IP address of the first Elastic IP found w...
[ "def", "ec2_elasticip_elasticip_ipaddress", "(", "self", ",", "lookup", ",", "default", "=", "None", ")", ":", "# Extract environment from resource ID to build stack name", "m", "=", "re", ".", "search", "(", "'ElasticIp([A-Z]?[a-z]+[0-9]?)\\w+'", ",", "lookup", ")", "#...
42.290323
23.193548
def return_obj(cols, df, return_cols=False): """Construct a DataFrameHolder and then return either that or the DataFrame.""" df_holder = DataFrameHolder(cols=cols, df=df) return df_holder.return_self(return_cols=return_cols)
[ "def", "return_obj", "(", "cols", ",", "df", ",", "return_cols", "=", "False", ")", ":", "df_holder", "=", "DataFrameHolder", "(", "cols", "=", "cols", ",", "df", "=", "df", ")", "return", "df_holder", ".", "return_self", "(", "return_cols", "=", "return...
61.25
9.5
def node_mkdir(self, path=''): 'Does not raise any errors if dir already exists.' return self(path, data=dict(kind='directory'), encode='json', method='put')
[ "def", "node_mkdir", "(", "self", ",", "path", "=", "''", ")", ":", "return", "self", "(", "path", ",", "data", "=", "dict", "(", "kind", "=", "'directory'", ")", ",", "encode", "=", "'json'", ",", "method", "=", "'put'", ")" ]
53
19.666667
def Watson(T, Hvap_ref, T_Ref, Tc, exponent=0.38): ''' Adjusts enthalpy of vaporization of enthalpy for another temperature, for one temperature. ''' Tr = T/Tc Trefr = T_Ref/Tc H2 = Hvap_ref*((1-Tr)/(1-Trefr))**exponent return H2
[ "def", "Watson", "(", "T", ",", "Hvap_ref", ",", "T_Ref", ",", "Tc", ",", "exponent", "=", "0.38", ")", ":", "Tr", "=", "T", "/", "Tc", "Trefr", "=", "T_Ref", "/", "Tc", "H2", "=", "Hvap_ref", "*", "(", "(", "1", "-", "Tr", ")", "/", "(", "...
31.25
26.25
def send_activation_email(self, user): """ Send the activation email. The activation key is the username, signed using TimestampSigner. """ activation_key = self.get_activation_key(user) context = self.get_email_context(activation_key) context.update({ ...
[ "def", "send_activation_email", "(", "self", ",", "user", ")", ":", "activation_key", "=", "self", ".", "get_activation_key", "(", "user", ")", "context", "=", "self", ".", "get_email_context", "(", "activation_key", ")", "context", ".", "update", "(", "{", ...
39.315789
16.052632
def connect_with_key(self, ssh, username, key, address, port, sock, timeout=20): """ Create an ssh session to a remote host with a username and rsa key :type username: str :param username: username used for ssh authentication :type key: :py:class:`parami...
[ "def", "connect_with_key", "(", "self", ",", "ssh", ",", "username", ",", "key", ",", "address", ",", "port", ",", "sock", ",", "timeout", "=", "20", ")", ":", "ssh", ".", "connect", "(", "hostname", "=", "address", ",", "port", "=", "port", ",", "...
36.75
12.45
def post(self, request, *args, **kwargs): """ Validates subscription data before creating Outbound message """ schedule_disable.delay(kwargs["subscription_id"]) return Response({"accepted": True}, status=201)
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "schedule_disable", ".", "delay", "(", "kwargs", "[", "\"subscription_id\"", "]", ")", "return", "Response", "(", "{", "\"accepted\"", ":", "True", "}", ",...
47.2
6.6
def idle_print_status(self): '''print out statistics every 10 seconds from idle loop''' now = time.time() if (now - self.last_idle_status_printed_time) >= 10: print (self.status()) self.last_idle_status_printed_time = now self.prev_download = self.download
[ "def", "idle_print_status", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "(", "now", "-", "self", ".", "last_idle_status_printed_time", ")", ">=", "10", ":", "print", "(", "self", ".", "status", "(", ")", ")", "self", ".", ...
44.285714
14
def get_bytes(self, addr, size, **kwargs): '''Reading bytes of any arbitrary size Parameters ----------. addr : int The register address. size : int Byte length of the value. Returns ------- data : iterable ...
[ "def", "get_bytes", "(", "self", ",", "addr", ",", "size", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_intf", ".", "read", "(", "self", ".", "_conf", "[", "'base_addr'", "]", "+", "addr", ",", "size", ")" ]
25.0625
19.6875
def set_off(self): """Turn the bulb off.""" try: request = requests.post( '{}/{}/{}/'.format(self.resource, URI, self._mac), data={'action': 'off'}, timeout=self.timeout) if request.status_code == 200: pass except requests.e...
[ "def", "set_off", "(", "self", ")", ":", "try", ":", "request", "=", "requests", ".", "post", "(", "'{}/{}/{}/'", ".", "format", "(", "self", ".", "resource", ",", "URI", ",", "self", ".", "_mac", ")", ",", "data", "=", "{", "'action'", ":", "'off'...
39.1
14.7
def _set_status_self(self, key=JobDetails.topkey, status=JobStatus.unknown): """Set the status of this job, both in self.jobs and in the `JobArchive` if it is present. """ fullkey = JobDetails.make_fullkey(self.full_linkname, key) if fullkey in self.jobs: self.jobs[fullkey].s...
[ "def", "_set_status_self", "(", "self", ",", "key", "=", "JobDetails", ".", "topkey", ",", "status", "=", "JobStatus", ".", "unknown", ")", ":", "fullkey", "=", "JobDetails", ".", "make_fullkey", "(", "self", ".", "full_linkname", ",", "key", ")", "if", ...
49.8
15.3
def downsample_grid(a, b, samples, ret_idx=False): """Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ndarrays ...
[ "def", "downsample_grid", "(", "a", ",", "b", ",", "samples", ",", "ret_idx", "=", "False", ")", ":", "# fixed random state for this method", "rs", "=", "np", ".", "random", ".", "RandomState", "(", "seed", "=", "47", ")", ".", "get_state", "(", ")", "sa...
33.96875
16.5
def deptree(self, field, oids, date=None, level=None, table=None): ''' Dependency tree builder. Recursively fetchs objects that are children of the initial set of parent object ids provided. :param field: Field that contains the 'parent of' data :param oids: Object oids to build...
[ "def", "deptree", "(", "self", ",", "field", ",", "oids", ",", "date", "=", "None", ",", "level", "=", "None", ",", "table", "=", "None", ")", ":", "table", "=", "self", ".", "get_table", "(", "table", ")", "fringe", "=", "str2list", "(", "oids", ...
42.592593
18.148148
def get_subscribers(self, order="created_at desc", offset=None, count=None): """Returns a list of subscribers. List is sorted by most-recent-to-subsribe, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items (in sort...
[ "def", "get_subscribers", "(", "self", ",", "order", "=", "\"created_at desc\"", ",", "offset", "=", "None", ",", "count", "=", "None", ")", ":", "req_data", "=", "[", "None", ",", "order", ",", "fmt_paging", "(", "offset", ",", "count", ")", "]", "ret...
48.666667
31.333333
def post_collect(self, obj): """ We want to manage the side-effect of not collecting other items of the same type as root model. If for example, you run the collect on a specific user that is linked to a model "A" linked (ForeignKey) to ANOTHER user. Then the collect won't collec...
[ "def", "post_collect", "(", "self", ",", "obj", ")", ":", "if", "not", "self", ".", "ALLOWS_SAME_TYPE_AS_ROOT_COLLECT", ":", "for", "field", "in", "self", ".", "get_local_fields", "(", "obj", ")", ":", "if", "isinstance", "(", "field", ",", "ForeignKey", "...
53.111111
28.518519
def cfmakeraw(tflags): """Given a list returned by :py:func:`termios.tcgetattr`, return a list modified in a manner similar to the `cfmakeraw()` C library function, but additionally disabling local echo.""" # BSD: https://github.com/freebsd/freebsd/blob/master/lib/libc/gen/termios.c#L162 # Linux: ht...
[ "def", "cfmakeraw", "(", "tflags", ")", ":", "# BSD: https://github.com/freebsd/freebsd/blob/master/lib/libc/gen/termios.c#L162", "# Linux: https://github.com/lattera/glibc/blob/master/termios/cfmakeraw.c#L20", "iflag", ",", "oflag", ",", "cflag", ",", "lflag", ",", "ispeed", ",", ...
57.785714
21.5
def get_recipes_in_cookbook(name): """Gets the name of all recipes present in a cookbook Returns a list of dictionaries """ recipes = {} path = None cookbook_exists = False metadata_exists = False for cookbook_path in cookbook_paths: path = os.path.join(cookbook_path, name) ...
[ "def", "get_recipes_in_cookbook", "(", "name", ")", ":", "recipes", "=", "{", "}", "path", "=", "None", "cookbook_exists", "=", "False", "metadata_exists", "=", "False", "for", "cookbook_path", "in", "cookbook_paths", ":", "path", "=", "os", ".", "path", "."...
38.807692
16.064103
def kind(self): """The type of value to watch, based on :attr:`block`. One of ``variable``, ``list``, or ``block``. ``block`` watchers watch the value of a reporter block. """ if self.block.type.has_command('readVariable'): return 'variable' elif self.block...
[ "def", "kind", "(", "self", ")", ":", "if", "self", ".", "block", ".", "type", ".", "has_command", "(", "'readVariable'", ")", ":", "return", "'variable'", "elif", "self", ".", "block", ".", "type", ".", "has_command", "(", "'contentsOfList:'", ")", ":",...
29.357143
20.142857
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): """ Updates references to the old logical id of a resource to the new (generated) logical id. Example: {"Ref": "MyLayer"} => {"Ref": "MyLayerABC123"} :param dict input_dict: Dictionary representing ...
[ "def", "resolve_resource_id_refs", "(", "self", ",", "input_dict", ",", "supported_resource_id_refs", ")", ":", "if", "not", "self", ".", "can_handle", "(", "input_dict", ")", ":", "return", "input_dict", "ref_value", "=", "input_dict", "[", "self", ".", "intrin...
35.571429
27.071429
def search(self): """Search srt in project for cells matching list of terms.""" matches = [] for pattern in Config.patterns: matches += self.termfinder(pattern) return sorted(set(matches), key=int)
[ "def", "search", "(", "self", ")", ":", "matches", "=", "[", "]", "for", "pattern", "in", "Config", ".", "patterns", ":", "matches", "+=", "self", ".", "termfinder", "(", "pattern", ")", "return", "sorted", "(", "set", "(", "matches", ")", ",", "key"...
29.5
16.875
def a_not_committed(ctx): """Provide the message that current software is not committed and reload is not possible.""" ctx.ctrl.sendline('n') ctx.msg = "Some active software packages are not yet committed. Reload may cause software rollback." ctx.device.chain.connection.emit_message(ctx.msg, log_level=l...
[ "def", "a_not_committed", "(", "ctx", ")", ":", "ctx", ".", "ctrl", ".", "sendline", "(", "'n'", ")", "ctx", ".", "msg", "=", "\"Some active software packages are not yet committed. Reload may cause software rollback.\"", "ctx", ".", "device", ".", "chain", ".", "co...
52.285714
24.857143
def make_syllables(self, sentences_words): """Divide the word tokens into a list of syllables. Note that a syllable in this instance is defined as a vocalic group (i.e., a vowel or a diphthong). This means that all syllables which are not the last syllable in the word will end with a vow...
[ "def", "make_syllables", "(", "self", ",", "sentences_words", ")", ":", "all_syllables", "=", "[", "]", "for", "sentence", "in", "sentences_words", ":", "syll_per_sent", "=", "[", "]", "for", "word", "in", "sentence", ":", "syll_start", "=", "0", "# Begins s...
50.555556
17.015873
def gradient_rgb( self, text=None, fore=None, back=None, style=None, start=None, stop=None, step=1, linemode=True, movefactor=0): """ Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, ...
[ "def", "gradient_rgb", "(", "self", ",", "text", "=", "None", ",", "fore", "=", "None", ",", "back", "=", "None", ",", "style", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "1", ",", "linemode", "=", "True",...
33.892857
17.428571
def declare_queue(self, queue_name): """Declare a queue. Has no effect if a queue with the given name already exists. Parameters: queue_name(str): The name of the new queue. Raises: ConnectionClosed: If the underlying channel or connection has been clos...
[ "def", "declare_queue", "(", "self", ",", "queue_name", ")", ":", "attempts", "=", "1", "while", "True", ":", "try", ":", "if", "queue_name", "not", "in", "self", ".", "queues", ":", "self", ".", "emit_before", "(", "\"declare_queue\"", ",", "queue_name", ...
38.214286
19.714286
def ternary_operation(x): """Ternary operation use threshold computed with weights.""" g = tf.get_default_graph() with g.gradient_override_map({"Sign": "Identity"}): threshold = _compute_threshold(x) x = tf.sign(tf.add(tf.sign(tf.add(x, threshold)), tf.sign(tf.add(x, -threshold)))) r...
[ "def", "ternary_operation", "(", "x", ")", ":", "g", "=", "tf", ".", "get_default_graph", "(", ")", "with", "g", ".", "gradient_override_map", "(", "{", "\"Sign\"", ":", "\"Identity\"", "}", ")", ":", "threshold", "=", "_compute_threshold", "(", "x", ")", ...
45.857143
16.428571
def analyze(self, s, method='chebyshev', order=30): r"""Convenience alias to :meth:`filter`.""" if s.ndim == 3 and s.shape[-1] != 1: raise ValueError('Last dimension (#features) should be ' '1, got {}.'.format(s.shape)) return self.filter(s, method, order...
[ "def", "analyze", "(", "self", ",", "s", ",", "method", "=", "'chebyshev'", ",", "order", "=", "30", ")", ":", "if", "s", ".", "ndim", "==", "3", "and", "s", ".", "shape", "[", "-", "1", "]", "!=", "1", ":", "raise", "ValueError", "(", "'Last d...
52.666667
10.833333
def rc2lar(k): """Convert reflection coefficients to log area ratios. :param k: reflection coefficients :return: inverse sine parameters The log area ratio is defined by G = log((1+k)/(1-k)) , where the K parameter is the reflection coefficient. .. seealso:: :func:`lar2rc`, :func:`rc2poly`, :...
[ "def", "rc2lar", "(", "k", ")", ":", "assert", "numpy", ".", "isrealobj", "(", "k", ")", ",", "'Log area ratios not defined for complex reflection coefficients.'", "if", "max", "(", "numpy", ".", "abs", "(", "k", ")", ")", ">=", "1", ":", "raise", "ValueErro...
37.904762
27.857143
def get_next_record(in_uid, kind='1'): ''' Get next record by time_create. ''' current_rec = MPost.get_by_uid(in_uid) recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.time_create < current_rec.time_create) ).order_by(TabPost.time_cr...
[ "def", "get_next_record", "(", "in_uid", ",", "kind", "=", "'1'", ")", ":", "current_rec", "=", "MPost", ".", "get_by_uid", "(", "in_uid", ")", "recs", "=", "TabPost", ".", "select", "(", ")", ".", "where", "(", "(", "TabPost", ".", "kind", "==", "ki...
33
12.166667
def list_repos(config_path=_DEFAULT_CONFIG_PATH, with_packages=False): ''' List all of the local package repositories. :param str config_path: The path to the configuration file for the aptly instance. :param bool with_packages: Return a list of packages in the repo. :return: A dictionary of the r...
[ "def", "list_repos", "(", "config_path", "=", "_DEFAULT_CONFIG_PATH", ",", "with_packages", "=", "False", ")", ":", "_validate_config", "(", "config_path", ")", "ret", "=", "dict", "(", ")", "cmd", "=", "[", "'repo'", ",", "'list'", ",", "'-config={}'", ".",...
27.9
26.9
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): """Redirect the call to FakeFileOpen. See FakeFileOpen.call() for description. """ if opener is not None and sys.version_info < (3, 3): raise TypeEr...
[ "def", "open", "(", "self", ",", "file", ",", "mode", "=", "'r'", ",", "buffering", "=", "-", "1", ",", "encoding", "=", "None", ",", "errors", "=", "None", ",", "newline", "=", "None", ",", "closefd", "=", "True", ",", "opener", "=", "None", ")"...
51.272727
15.636364
def feed_backend(url, clean, fetch_archive, backend_name, backend_params, es_index=None, es_index_enrich=None, project=None, arthur=False, es_aliases=None, projects_json_repo=None): """ Feed Ocean with backend data """ backend = None repo = {'backend_name': backend_name, '...
[ "def", "feed_backend", "(", "url", ",", "clean", ",", "fetch_archive", ",", "backend_name", ",", "backend_params", ",", "es_index", "=", "None", ",", "es_index_enrich", "=", "None", ",", "project", "=", "None", ",", "arthur", "=", "False", ",", "es_aliases",...
37.550847
23.29661
def functions(self): """ Returns all documented module level functions in the module sorted alphabetically as a list of `pydoc.Function`. """ p = lambda o: isinstance(o, Function) and self._docfilter(o) return sorted(filter(p, self.doc.values()))
[ "def", "functions", "(", "self", ")", ":", "p", "=", "lambda", "o", ":", "isinstance", "(", "o", ",", "Function", ")", "and", "self", ".", "_docfilter", "(", "o", ")", "return", "sorted", "(", "filter", "(", "p", ",", "self", ".", "doc", ".", "va...
41.142857
15.142857
def generate_signing_key(date, region, secret_key): """ Generate signing key. :param date: Date is input from :meth:`datetime.datetime` :param region: Region should be set to bucket region. :param secret_key: Secret access key. """ formatted_date = date.strftime("%Y%m%d") key1_string =...
[ "def", "generate_signing_key", "(", "date", ",", "region", ",", "secret_key", ")", ":", "formatted_date", "=", "date", ".", "strftime", "(", "\"%Y%m%d\"", ")", "key1_string", "=", "'AWS4'", "+", "secret_key", "key1", "=", "key1_string", ".", "encode", "(", "...
37.684211
15.894737
def find_ui_tree_entity(entity_id=None, entity_value=None, entity_ca=None): """ find the Ariane UI tree menu entity depending on its id (priority), value or context address :param entity_id: the Ariane UI tree menu ID to search :param entity_value: the Ariane UI tree menu Value to search...
[ "def", "find_ui_tree_entity", "(", "entity_id", "=", "None", ",", "entity_value", "=", "None", ",", "entity_ca", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "\"InjectorUITreeService.find_ui_tree_entity\"", ")", "operation", "=", "None", "search_criteria", ...
46.97561
21.512195
def label_contiguous_1d(X): """ WARNING: API for this function is not liable to change!!! By example: X = [F T T F F T F F F T T T] result = [0 1 1 0 0 2 0 0 0 3 3 3] Or: X = [0 3 3 0 0 5 5 5 1 1 0 2] result = [0 1 1 0 0 2 2 2 3 3 0 4] T...
[ "def", "label_contiguous_1d", "(", "X", ")", ":", "if", "X", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"this is for 1d masks only.\"", ")", "is_start", "=", "np", ".", "empty", "(", "len", "(", "X", ")", ",", "dtype", "=", "bool", ")",...
29.131579
22.684211
def convert_response(allocate_quota_response, project_id): """Computes a http status code and message `AllocateQuotaResponse` The return value a tuple (code, message) where code: is the http status code message: is the message to return Args: allocate_quota_response (:class:`endpoints_mana...
[ "def", "convert_response", "(", "allocate_quota_response", ",", "project_id", ")", ":", "if", "not", "allocate_quota_response", "or", "not", "allocate_quota_response", ".", "allocateErrors", ":", "return", "_IS_OK", "# only allocate_quota the first error for now, as per ESP", ...
37.692308
25.269231
def filter_gradient_threshold(self, analyte, win, threshold, recalc=True): """ Apply gradient threshold filter. Generates threshold filters for the given analytes above and below the specified threshold. Two filters are created with prefixes '_above' and '_below'. '...
[ "def", "filter_gradient_threshold", "(", "self", ",", "analyte", ",", "win", ",", "threshold", ",", "recalc", "=", "True", ")", ":", "params", "=", "locals", "(", ")", "del", "(", "params", "[", "'self'", "]", ")", "# calculate absolute gradient", "if", "r...
33.58
20.42
def Import(context, request): """ Read Dimensional-CSV analysis results """ form = request.form # TODO form['file'] sometimes returns a list infile = form['instrument_results_file'][0] if \ isinstance(form['instrument_results_file'], list) else \ form['instrument_results_file'] a...
[ "def", "Import", "(", "context", ",", "request", ")", ":", "form", "=", "request", ".", "form", "# TODO form['file'] sometimes returns a list", "infile", "=", "form", "[", "'instrument_results_file'", "]", "[", "0", "]", "if", "isinstance", "(", "form", "[", "...
34.302326
16.860465
def account_history(self, account, count): """ Reports send/receive information for a **account** :param account: Account to get send/receive information for :type account: str :param count: number of blocks to return :type count: int :raises: :py:exc:`nano.rpc...
[ "def", "account_history", "(", "self", ",", "account", ",", "count", ")", ":", "account", "=", "self", ".", "_process_value", "(", "account", ",", "'account'", ")", "count", "=", "self", ".", "_process_value", "(", "count", ",", "'int'", ")", "payload", ...
29.846154
23.897436
def novo(args): """ %prog novo reads.fastq Reference-free tGBS pipeline v1. """ from jcvi.assembly.kmer import jellyfish, histogram from jcvi.assembly.preprocess import diginorm from jcvi.formats.fasta import filter as fasta_filter, format from jcvi.apps.cdhit import filter as cdhit_fil...
[ "def", "novo", "(", "args", ")", ":", "from", "jcvi", ".", "assembly", ".", "kmer", "import", "jellyfish", ",", "histogram", "from", "jcvi", ".", "assembly", ".", "preprocess", "import", "diginorm", "from", "jcvi", ".", "formats", ".", "fasta", "import", ...
36.915493
16.943662
def UTCFromGps(gpsWeek, SOW, leapSecs=14): """converts gps week and seconds to UTC see comments of inverse function! SOW = seconds of week gpsWeek is the full number (not modulo 1024) """ secFract = SOW % 1 epochTuple = gpsEpoch + (-1, -1, 0) t0 = time.mktime(epochTuple) - time.timezo...
[ "def", "UTCFromGps", "(", "gpsWeek", ",", "SOW", ",", "leapSecs", "=", "14", ")", ":", "secFract", "=", "SOW", "%", "1", "epochTuple", "=", "gpsEpoch", "+", "(", "-", "1", ",", "-", "1", ",", "0", ")", "t0", "=", "time", ".", "mktime", "(", "ep...
40.625
19.75