text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _run(self): # type: (Downloader) -> None """Execute Downloader :param Downloader self: this """ # mark start self._start_time = blobxfer.util.datetime_now() logger.info('blobxfer start time: {0}'.format(self._start_time)) # ensure destination path ...
[ "def", "_run", "(", "self", ")", ":", "# type: (Downloader) -> None", "# mark start", "self", ".", "_start_time", "=", "blobxfer", ".", "util", ".", "datetime_now", "(", ")", "logger", ".", "info", "(", "'blobxfer start time: {0}'", ".", "format", "(", "self", ...
47.426752
15.210191
def lock(self): """Close the charger door.""" if not self.__lock_state: data = self._controller.command(self._id, 'charge_port_door_close', wake_if_asleep=True) if data['response']['result']: self.__lock_state = True ...
[ "def", "lock", "(", "self", ")", ":", "if", "not", "self", ".", "__lock_state", ":", "data", "=", "self", ".", "_controller", ".", "command", "(", "self", ".", "_id", ",", "'charge_port_door_close'", ",", "wake_if_asleep", "=", "True", ")", "if", "data",...
45.125
13.5
def _speak_header_always_inherit(self, element): """ The cells headers will be spoken for every data cell for element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ self._speak_header_once_inheri...
[ "def", "_speak_header_always_inherit", "(", "self", ",", "element", ")", ":", "self", ".", "_speak_header_once_inherit", "(", "element", ")", "cell_elements", "=", "self", ".", "html_parser", ".", "find", "(", "element", ")", ".", "find_descendants", "(", "'td[h...
34.25
19.05
def pop (self, key): """Remove key from dict and return value.""" if key in self._keys: self._keys.remove(key) super(ListDict, self).pop(key)
[ "def", "pop", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "_keys", ":", "self", ".", "_keys", ".", "remove", "(", "key", ")", "super", "(", "ListDict", ",", "self", ")", ".", "pop", "(", "key", ")" ]
34.6
7.8
def save(self, filename=None): """ Save the smart object to a file. :param filename: File name to export. If None, use the embedded name. """ if filename is None: filename = self.filename with open(filename, 'wb') as f: f.write(self.data)
[ "def", "save", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "filename", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ...
30.2
11.4
def order_queryset(self, queryset): """ Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter. """ order = self.derive_ordering() # if we get our order from the request # make sure it is a valid field in ...
[ "def", "order_queryset", "(", "self", ",", "queryset", ")", ":", "order", "=", "self", ".", "derive_ordering", "(", ")", "# if we get our order from the request", "# make sure it is a valid field in the list", "if", "'_order'", "in", "self", ".", "request", ".", "GET"...
32.285714
18.952381
def setup_module_dev(destdir): """ Sets up a development environment suitable for working on anchore modules (queries, etc) in the specified directory. Creates a copied environment in the destination containing the module scripts, unpacked image(s) and helper scripts such that a module script that works...
[ "def", "setup_module_dev", "(", "destdir", ")", ":", "if", "not", "nav", ":", "sys", ".", "exit", "(", "1", ")", "ecode", "=", "0", "try", ":", "anchore_print", "(", "\"Anchore Module Development Environment\\n\"", ")", "helpstr", "=", "\"This tool has set up an...
53.184466
34.699029
def set_attribute(self, attribute, value, callback=None): """ Set a new value for an attribute of the Queue. :type attribute: String :param attribute: The name of the attribute you want to set. The only valid value at this time is: VisibilityTimeout ...
[ "def", "set_attribute", "(", "self", ",", "attribute", ",", "value", ",", "callback", "=", "None", ")", ":", "return", "self", ".", "connection", ".", "set_queue_attribute", "(", "self", ",", "attribute", ",", "value", ",", "callback", "=", "callback", ")"...
43.4375
21.6875
def check_if_release_is_current(log): """Warns the user if their release is behind the latest PyPi __version__.""" if __version__ == '0.0.0': return client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') latest_pypi_version = client.package_releases('hca') latest_version_nums = [int...
[ "def", "check_if_release_is_current", "(", "log", ")", ":", "if", "__version__", "==", "'0.0.0'", ":", "return", "client", "=", "xmlrpclib", ".", "ServerProxy", "(", "'https://pypi.python.org/pypi'", ")", "latest_pypi_version", "=", "client", ".", "package_releases", ...
53.857143
27.571429
def collection_list(self, resource_id, resource_type="collection"): """ Fetches a list of slug representing descriptions within the specified parent description. :param resource_id str: The slug of the description to fetch children from. :param resource_type str: no-op; not required or ...
[ "def", "collection_list", "(", "self", ",", "resource_id", ",", "resource_type", "=", "\"collection\"", ")", ":", "def", "fetch_children", "(", "children", ")", ":", "results", "=", "[", "]", "for", "child", "in", "children", ":", "results", ".", "append", ...
35.222222
26.407407
def debug_print(*message): """Output debug messages to stdout""" warnings.warn("debug_print is deprecated; use the logging module instead.") if get_debug_level(): ss = STDOUT if PY3: # This is needed after restarting and using debug_print for m in message: ...
[ "def", "debug_print", "(", "*", "message", ")", ":", "warnings", ".", "warn", "(", "\"debug_print is deprecated; use the logging module instead.\"", ")", "if", "get_debug_level", "(", ")", ":", "ss", "=", "STDOUT", "if", "PY3", ":", "# This is needed after restarting ...
37.166667
17
def check_type(lineno, type_list, arg): """ Check arg's type is one in type_list, otherwise, raises an error. """ if not isinstance(type_list, list): type_list = [type_list] if arg.type_ in type_list: return True if len(type_list) == 1: syntax_error(lineno, "Wrong expre...
[ "def", "check_type", "(", "lineno", ",", "type_list", ",", "arg", ")", ":", "if", "not", "isinstance", "(", "type_list", ",", "list", ")", ":", "type_list", "=", "[", "type_list", "]", "if", "arg", ".", "type_", "in", "type_list", ":", "return", "True"...
30.333333
19.055556
def get_statement(self, statement_id): """ Returns the statement object for the supplied identifier @type statement_id: string @param statement_id: statement identifier """ if statement_id in self.idx: return Cstatement(self.idx[statement_id], self.type) ...
[ "def", "get_statement", "(", "self", ",", "statement_id", ")", ":", "if", "statement_id", "in", "self", ".", "idx", ":", "return", "Cstatement", "(", "self", ".", "idx", "[", "statement_id", "]", ",", "self", ".", "type", ")", "else", ":", "return", "N...
34.3
11.3
def get_template_options(self, instance=None, test_message=None, **kwargs): """Returns a dictionary of message template options. Extend using `extra_template_options`. """ protocol_name = django_apps.get_app_config("edc_protocol").protocol_name test_message = test_message or sel...
[ "def", "get_template_options", "(", "self", ",", "instance", "=", "None", ",", "test_message", "=", "None", ",", "*", "*", "kwargs", ")", ":", "protocol_name", "=", "django_apps", ".", "get_app_config", "(", "\"edc_protocol\"", ")", ".", "protocol_name", "test...
41.741935
17.258065
def check_function( state, name, index=0, missing_msg=None, params_not_matched_msg=None, expand_msg=None, signature=True, ): """Check whether a particular function is called. ``check_function()`` is typically followed by: - ``check_args()`` to check whether the arguments we...
[ "def", "check_function", "(", "state", ",", "name", ",", "index", "=", "0", ",", "missing_msg", "=", "None", ",", "params_not_matched_msg", "=", "None", ",", "expand_msg", "=", "None", ",", "signature", "=", "True", ",", ")", ":", "append_missing", "=", ...
38.369565
27.23913
def unblockqueue(self, queue): ''' Remove blocked events from the queue and all subqueues. Usually used after queue clear/unblockall to prevent leak. :returns: the cleared events ''' subqueues = set() def allSubqueues(q): subqueues.add(q) ...
[ "def", "unblockqueue", "(", "self", ",", "queue", ")", ":", "subqueues", "=", "set", "(", ")", "def", "allSubqueues", "(", "q", ")", ":", "subqueues", ".", "add", "(", "q", ")", "subqueues", ".", "add", "(", "q", ".", "defaultQueue", ")", "for", "v...
35.166667
18.166667
def SXTB(self, params): """ STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) self.check_arguments(low_registers=(Ra, Rb)) def SXTB_func(): i...
[ "def", "SXTB", "(", "self", ",", "params", ")", ":", "Ra", ",", "Rb", "=", "self", ".", "get_two_parameters", "(", "r'\\s*([^\\s,]*),\\s*([^\\s,]*)(,\\s*[^\\s,]*)*\\s*'", ",", "params", ")", "self", ".", "check_arguments", "(", "low_registers", "=", "(", "Ra", ...
30.470588
23.647059
def getResponsible(self): """Return all manager info of responsible departments """ managers = {} for department in self.getDepartments(): manager = department.getManager() if manager is None: continue manager_id = manager.getId() ...
[ "def", "getResponsible", "(", "self", ")", ":", "managers", "=", "{", "}", "for", "department", "in", "self", ".", "getDepartments", "(", ")", ":", "manager", "=", "department", ".", "getManager", "(", ")", "if", "manager", "is", "None", ":", "continue",...
43.805556
12.972222
def point(self, t): """Evaluate the cubic Bezier curve at t using Horner's rule.""" # algebraically equivalent to # P0*(1-t)**3 + 3*P1*t*(1-t)**2 + 3*P2*(1-t)*t**2 + P3*t**3 # for (P0, P1, P2, P3) = self.bpoints() return self.start + t*( 3*(self.control1 - self.start)...
[ "def", "point", "(", "self", ",", "t", ")", ":", "# algebraically equivalent to", "# P0*(1-t)**3 + 3*P1*t*(1-t)**2 + 3*P2*(1-t)*t**2 + P3*t**3", "# for (P0, P1, P2, P3) = self.bpoints()", "return", "self", ".", "start", "+", "t", "*", "(", "3", "*", "(", "self", ".", ...
48.7
16.4
def parse_all_data(self): """Parses the master df.""" self._master_df.columns = ["domain", "entity", "state", "last_changed"] # Check if state is float and store in numericals category. self._master_df["numerical"] = self._master_df["state"].apply( lambda x: functions.isfloa...
[ "def", "parse_all_data", "(", "self", ")", ":", "self", ".", "_master_df", ".", "columns", "=", "[", "\"domain\"", ",", "\"entity\"", ",", "\"state\"", ",", "\"last_changed\"", "]", "# Check if state is float and store in numericals category.", "self", ".", "_master_d...
36
24.076923
def resource_collections_update(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/resource_collections#update-a-resource-collection" api_path = "/api/v2/resource_collections.json" return self.call(api_path, method="PUT", data=data, **kwargs)
[ "def", "resource_collections_update", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/resource_collections.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"PUT\"", ",", "data", "=", "data"...
71.25
31.25
def pipe(self, methodname, first_arg, *args, **kwargs): """Call a common method on all the plugins, if it exists. The return value of each call becomes the replaces the first argument in the given argument list to pass to the next. Useful to utilize plugins as sets of filters. "...
[ "def", "pipe", "(", "self", ",", "methodname", ",", "first_arg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "plugin", "in", "self", ".", "_plugins", ":", "method", "=", "getattr", "(", "plugin", ",", "methodname", ",", "None", ")", ...
36.5
15.5625
def detect_format(program, attributes) -> str: ''' Detect format for vertex attributes. The format returned does not contain padding. Args: program (Program): The program. attributes (list): A list of attribute names. Returns: str ''' de...
[ "def", "detect_format", "(", "program", ",", "attributes", ")", "->", "str", ":", "def", "fmt", "(", "attr", ")", ":", "'''\n For internal use only.\n '''", "return", "attr", ".", "array_length", "*", "attr", ".", "dimension", ",", "attr", ".",...
23.857143
24.619048
async def emit(self, event, data, namespace, room=None, skip_sid=None, callback=None, **kwargs): """Emit a message to a single client, a room, or all the clients connected to the namespace. Note: this method is a coroutine. """ if namespace not in self.rooms o...
[ "async", "def", "emit", "(", "self", ",", "event", ",", "data", ",", "namespace", ",", "room", "=", "None", ",", "skip_sid", "=", "None", ",", "callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "namespace", "not", "in", "self", ".", ...
41.619048
16.428571
def __reorganize_chron_header(line): """ Reorganize the list of variables. If there are units given, log them. :param str line: :return dict: key: variable, val: units (optional) """ d = {} # Header variables should be tab-delimited. Use regex to split by tabs ...
[ "def", "__reorganize_chron_header", "(", "line", ")", ":", "d", "=", "{", "}", "# Header variables should be tab-delimited. Use regex to split by tabs", "m", "=", "re", ".", "split", "(", "re_tab_split", ",", "line", ")", "# If there was an output match from the line, then ...
40.68
15.08
def commuting_sets_by_zbasis(pauli_sums): """ Computes commuting sets based on terms having the same diagonal basis Following the technique outlined in the appendix of arXiv:1704.05018. :param pauli_sums: PauliSum object to group :return: dictionary where key value pair is a tuple corresponding to...
[ "def", "commuting_sets_by_zbasis", "(", "pauli_sums", ")", ":", "diagonal_sets", "=", "{", "}", "for", "term", "in", "pauli_sums", ":", "diagonal_sets", "=", "_max_key_overlap", "(", "term", ",", "diagonal_sets", ")", "return", "diagonal_sets" ]
35.266667
21.933333
def print_tree(self, filename, tree=None): """ Print referrers tree to file (in text format). keyword arguments tree -- if not None, the passed tree will be printed. """ old_stream = self.stream self.stream = open(filename, 'w') try: super(FileBrowse...
[ "def", "print_tree", "(", "self", ",", "filename", ",", "tree", "=", "None", ")", ":", "old_stream", "=", "self", ".", "stream", "self", ".", "stream", "=", "open", "(", "filename", ",", "'w'", ")", "try", ":", "super", "(", "FileBrowser", ",", "self...
30.214286
15
def check_status(self, basepath=None): """Check on the status of this particular file""" if basepath is None: fullpath = self.path else: fullpath = os.path.join(basepath, self.path) exists = os.path.exists(fullpath) if not exists: if self.flag...
[ "def", "check_status", "(", "self", ",", "basepath", "=", "None", ")", ":", "if", "basepath", "is", "None", ":", "fullpath", "=", "self", ".", "path", "else", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "basepath", ",", "self", ".", ...
39.172414
13.758621
def ensure_element(self, locator, selector, state="present", timeout=None): """This method allows us to wait till an element appears or disappears in the browser The webdriver runs in parallel with our scripts, so we must wait for it everytime it runs javascript. Selenium automatically waits ti...
[ "def", "ensure_element", "(", "self", ",", "locator", ",", "selector", ",", "state", "=", "\"present\"", ",", "timeout", "=", "None", ")", ":", "locators", "=", "{", "'id'", ":", "By", ".", "ID", ",", "'name'", ":", "By", ".", "NAME", ",", "'xpath'",...
48.474576
25.525424
def to_pointer(cls, instance): """Get a pointer to the private object. """ return OctavePtr(instance._ref, instance._name, instance._address)
[ "def", "to_pointer", "(", "cls", ",", "instance", ")", ":", "return", "OctavePtr", "(", "instance", ".", "_ref", ",", "instance", ".", "_name", ",", "instance", ".", "_address", ")" ]
40.5
11
def _datetime_to_pb_timestamp(when): """Convert a datetime object to a Timestamp protobuf. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp` :returns: A timestamp protobuf corresponding to the object. """ ms...
[ "def", "_datetime_to_pb_timestamp", "(", "when", ")", ":", "ms_value", "=", "_microseconds_from_datetime", "(", "when", ")", "seconds", ",", "micros", "=", "divmod", "(", "ms_value", ",", "10", "**", "6", ")", "nanos", "=", "micros", "*", "10", "**", "3", ...
37.846154
13.846154
def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None ): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `for...
[ "def", "fetch_distribution", "(", "self", ",", "requirement", ",", "tmpdir", ",", "force_scan", "=", "False", ",", "source", "=", "False", ",", "develop_ok", "=", "False", ",", "local_index", "=", "None", ")", ":", "# process a Requirement", "self", ".", "in...
37.588235
22.25
def do_action_for(self, context, request): """/@@API/doActionFor: Perform workflow transition on values returned by jsonapi "read" function. Required parameters: - action: The workflow transition to apply to found objects. Parameters used to locate objects are the same as ...
[ "def", "do_action_for", "(", "self", ",", "context", ",", "request", ")", ":", "savepoint", "=", "transaction", ".", "savepoint", "(", ")", "workflow", "=", "getToolByName", "(", "context", ",", "'portal_workflow'", ")", "uc", "=", "getToolByName", "(", "con...
34.071429
18.02381
def ReSpecTh_to_ChemKED(filename_xml, file_author='', file_author_orcid='', *, validate=False): """Convert ReSpecTh XML file to ChemKED-compliant dictionary. Args: filename_xml (`str`): Name of ReSpecTh XML file to be converted. file_author (`str`, optional): Name to override original file auth...
[ "def", "ReSpecTh_to_ChemKED", "(", "filename_xml", ",", "file_author", "=", "''", ",", "file_author_orcid", "=", "''", ",", "*", ",", "validate", "=", "False", ")", ":", "# get all information from XML file", "tree", "=", "etree", ".", "parse", "(", "filename_xm...
42.802817
25.225352
def get_room_member_ids(self, room_id, start=None, timeout=None): """Call get room member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as a f...
[ "def", "get_room_member_ids", "(", "self", ",", "room_id", ",", "start", "=", "None", ",", "timeout", "=", "None", ")", ":", "params", "=", "None", "if", "start", "is", "None", "else", "{", "'start'", ":", "start", "}", "response", "=", "self", ".", ...
39.142857
20.75
def multiple_subplots(rows=1, cols=1, maxplots=None, n=1, delete=True, for_maps=False, *args, **kwargs): """ Function to create subplots. This function creates so many subplots on so many figures until the specified number `n` is reached. Parameters ---------- rows: i...
[ "def", "multiple_subplots", "(", "rows", "=", "1", ",", "cols", "=", "1", ",", "maxplots", "=", "None", ",", "n", "=", "1", ",", "delete", "=", "True", ",", "for_maps", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", ...
35.192982
17.54386
def enable_buffering(self, size=5): """Enable buffering. Buffer `size` items before yielding them.""" if size <= 1: raise ValueError('buffer size too small') def generator(next): buf = [] c_size = 0 push = buf.append while 1: ...
[ "def", "enable_buffering", "(", "self", ",", "size", "=", "5", ")", ":", "if", "size", "<=", "1", ":", "raise", "ValueError", "(", "'buffer size too small'", ")", "def", "generator", "(", "next", ")", ":", "buf", "=", "[", "]", "c_size", "=", "0", "p...
29.230769
13.923077
def awsReadMetadataKey(): """Print key from a running instance's metadata""" parser = argparse.ArgumentParser() parser.add_argument("--key", dest="keyname", help="Which metadata key to read") cli = parser.parse_args() print getMetadataKey(name=cli.keyname)
[ "def", "awsReadMetadataKey", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--key\"", ",", "dest", "=", "\"keyname\"", ",", "help", "=", "\"Which metadata key to read\"", ")", "cli", "=", "pars...
27.545455
16.454545
def auto_kwargs(function): """Modifies the provided function to support kwargs by only passing along kwargs for parameters it accepts""" supported = introspect.arguments(function) @wraps(function) def call_function(*args, **kwargs): return function(*args, **{key: value for key, value in kwargs....
[ "def", "auto_kwargs", "(", "function", ")", ":", "supported", "=", "introspect", ".", "arguments", "(", "function", ")", "@", "wraps", "(", "function", ")", "def", "call_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "function"...
45.875
19.5
def read_namespaced_role_binding(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_role_binding # noqa: E501 read the specified RoleBinding # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_re...
[ "def", "read_namespaced_role_binding", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retu...
51.130435
25.478261
def __autorefresh_studies(self, cfg): """Execute autorefresh for areas of code study if configured""" if 'studies' not in self.conf[self.backend_section] or \ 'enrich_areas_of_code:git' not in self.conf[self.backend_section]['studies']: logger.debug("Not doing autorefresh fo...
[ "def", "__autorefresh_studies", "(", "self", ",", "cfg", ")", ":", "if", "'studies'", "not", "in", "self", ".", "conf", "[", "self", ".", "backend_section", "]", "or", "'enrich_areas_of_code:git'", "not", "in", "self", ".", "conf", "[", "self", ".", "backe...
46.942857
30.628571
def _create_bundle(self, data): """Return a bundle initialised by the given dict.""" kwargs = {} filters = None if isinstance(data, dict): kwargs.update( filters=data.get('filters', None), output=data.get('output', None), debug=...
[ "def", "_create_bundle", "(", "self", ",", "data", ")", ":", "kwargs", "=", "{", "}", "filters", "=", "None", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "kwargs", ".", "update", "(", "filters", "=", "data", ".", "get", "(", "'filters'", ...
42.714286
11
def create_with_dst_resource_provisioning( cls, cli, src_resource_id, dst_resource_config, max_time_out_of_sync, name=None, remote_system=None, src_spa_interface=None, src_spb_interface=None, dst_spa_interface=None, dst_spb_interface=None, dst_resource_element...
[ "def", "create_with_dst_resource_provisioning", "(", "cls", ",", "cli", ",", "src_resource_id", ",", "dst_resource_config", ",", "max_time_out_of_sync", ",", "name", "=", "None", ",", "remote_system", "=", "None", ",", "src_spa_interface", "=", "None", ",", "src_spb...
50.487179
19.512821
def authenticate(self, *args, **kwargs): """Authenticate this packet. Returns a boolean indicates whether the packet can be authenticated or not. Returns ``False`` if the Authentication Present (A) is not set in the flag of this packet. Returns ``False`` if the Authent...
[ "def", "authenticate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "flags", "&", "BFD_FLAG_AUTH_PRESENT", "or", "not", "issubclass", "(", "self", ".", "auth_cls", ".", "__class__", ",", "BFDAuth", ")", ":...
36.2
25.55
def triplifyOverallStructures(self): """Insert into RDF graph the textual and network structures. Ideally, one should be able to make bag of words related to each item (communities, users, posts, comments, tags, etc). Interaction and friendship networks should be made. Human net...
[ "def", "triplifyOverallStructures", "(", "self", ")", ":", "if", "self", ".", "compute_networks", ":", "self", ".", "computeNetworks", "(", ")", "if", "self", ".", "compute_bows", ":", "self", ".", "computeBows", "(", ")" ]
41.5
16.142857
def setValue(self, key, value): """ Some devices allow to directly set values to perform a specific task. """ LOG.debug("HMGeneric.setValue: address = '%s', key = '%s' value = '%s'" % (self._ADDRESS, key, value)) try: self._proxy.setValue(self._ADDRESS, key, value) ...
[ "def", "setValue", "(", "self", ",", "key", ",", "value", ")", ":", "LOG", ".", "debug", "(", "\"HMGeneric.setValue: address = '%s', key = '%s' value = '%s'\"", "%", "(", "self", ".", "_ADDRESS", ",", "key", ",", "value", ")", ")", "try", ":", "self", ".", ...
41.916667
19.75
def _process_intersects_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks if the directive arg and the field intersect. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...
[ "def", "_process_intersects_filter_directive", "(", "filter_operation_info", ",", "location", ",", "context", ",", "parameters", ")", ":", "filtered_field_type", "=", "filter_operation_info", ".", "field_type", "filtered_field_name", "=", "filter_operation_info", ".", "fiel...
54.2
30.742857
def get_option_value(self, opt_name): """ Return the value of a given option :param opt_name: option name :type opt_name: str :returns: the value of the option """ if not self.has_option(opt_name): raise ValueError("Unknow option name (%s)" %...
[ "def", "get_option_value", "(", "self", ",", "opt_name", ")", ":", "if", "not", "self", ".", "has_option", "(", "opt_name", ")", ":", "raise", "ValueError", "(", "\"Unknow option name (%s)\"", "%", "opt_name", ")", "return", "self", ".", "_options", "[", "op...
33.181818
10.545455
def pager_fatality_rates(): """USGS Pager fatality estimation model. Fatality rate(MMI) = cum. standard normal dist(1/BETA * ln(MMI/THETA)). Reference: Jaiswal, K. S., Wald, D. J., and Hearne, M. (2009a). Estimating casualties for large worldwide earthquakes using an empirical approach. U.S. ...
[ "def", "pager_fatality_rates", "(", ")", ":", "# Model coefficients", "theta", "=", "13.249", "beta", "=", "0.151", "mmi_range", "=", "list", "(", "range", "(", "2", ",", "11", ")", ")", "fatality_rate", "=", "{", "mmi", ":", "0", "if", "mmi", "<", "4"...
32.939394
21.212121
def get_kline_data(self, symbol, kline_type='5min', start=None, end=None): """Get kline data For each query, the system would return at most 1500 pieces of data. To obtain more data, please page the data by time. :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string ...
[ "def", "get_kline_data", "(", "self", ",", "symbol", ",", "kline_type", "=", "'5min'", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "data", "=", "{", "'symbol'", ":", "symbol", "}", "if", "kline_type", "is", "not", "None", ":", "data...
33.328358
24.044776
def split_line(line, min_line_length=30, max_line_length=100): """ This is designed to work with prettified output from Beautiful Soup which indents with a single space. :param line: The line to split :param min_line_length: The minimum desired line length :param max_line_length: The maximum desire...
[ "def", "split_line", "(", "line", ",", "min_line_length", "=", "30", ",", "max_line_length", "=", "100", ")", ":", "if", "len", "(", "line", ")", "<=", "max_line_length", ":", "# No need to split!", "return", "[", "line", "]", "# First work out the indentation o...
30.543478
20.630435
def store(self, obj): """ Store Store an object into the MongoDB storage for caching Args: obj (AtlasServiceBinding.Binding or AtlasServiceInstance.Instance): instance or binding Returns: ObjectId: MongoDB _id Raise...
[ "def", "store", "(", "self", ",", "obj", ")", ":", "# query", "if", "type", "(", "obj", ")", "is", "AtlasServiceInstance", ".", "Instance", ":", "query", "=", "{", "\"instance_id\"", ":", "obj", ".", "instance_id", ",", "\"database\"", ":", "obj", ".", ...
36.621622
25.621622
def draw_panel(self, surf): """Draw the unit selection or build queue.""" left = -12 # How far from the right border def unit_name(unit_type): return self._static_data.units.get(unit_type, "<unknown>") def write(loc, text, color=colors.yellow): surf.write_screen(self._font_large, color, ...
[ "def", "draw_panel", "(", "self", ",", "surf", ")", ":", "left", "=", "-", "12", "# How far from the right border", "def", "unit_name", "(", "unit_type", ")", ":", "return", "self", ".", "_static_data", ".", "units", ".", "get", "(", "unit_type", ",", "\"<...
38.447761
16.253731
def list_all_directories(self): """ Utility method that yields all directories on the device's file systems. """ def list_dirs_recursively(directory): if directory == self.filesystem: yield directory d_gen = itertools.chain( dir...
[ "def", "list_all_directories", "(", "self", ")", ":", "def", "list_dirs_recursively", "(", "directory", ")", ":", "if", "directory", "==", "self", ".", "filesystem", ":", "yield", "directory", "d_gen", "=", "itertools", ".", "chain", "(", "directory", ".", "...
38.285714
8.428571
def format_row(row, bounds, columns): """Formats a single row of the dataframe""" for c in columns: if c not in row: continue if "format" in columns[c]: row[c] = columns[c]["format"] % row[c] if c in bounds: b = bounds...
[ "def", "format_row", "(", "row", ",", "bounds", ",", "columns", ")", ":", "for", "c", "in", "columns", ":", "if", "c", "not", "in", "row", ":", "continue", "if", "\"format\"", "in", "columns", "[", "c", "]", ":", "row", "[", "c", "]", "=", "colum...
29.214286
19
def ram_dumper(**kwargs): """Dump data to 'memory' for later usage.""" logging.debug("trying to save stuff in memory") farms = kwargs["farms"] experiments = kwargs["experiments"] engine = kwargs["engine"] try: engine_name = engine.__name__ except AttributeError: engine_name ...
[ "def", "ram_dumper", "(", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "\"trying to save stuff in memory\"", ")", "farms", "=", "kwargs", "[", "\"farms\"", "]", "experiments", "=", "kwargs", "[", "\"experiments\"", "]", "engine", "=", "kwargs", ...
36.636364
15.454545
def recommend(self, userid, user_items, N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False): """ returns the best N recommendations for a user given its id""" if userid >= user_items.shape[0]: raise ValueError("userid is out of bounds of the us...
[ "def", "recommend", "(", "self", ",", "userid", ",", "user_items", ",", "N", "=", "10", ",", "filter_already_liked_items", "=", "True", ",", "filter_items", "=", "None", ",", "recalculate_user", "=", "False", ")", ":", "if", "userid", ">=", "user_items", "...
46.571429
27.666667
def get(self, resource, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.GetAction, oper...
[ "def", "get", "(", "self", ",", "resource", ",", "operation_timeout", "=", "None", ",", "max_envelope_size", "=", "None", ",", "locale", "=", "None", ")", ":", "if", "isinstance", "(", "resource", ",", "str", ")", ":", "resource", "=", "ResourceLocator", ...
44.9
20.5
def new_from_tokens(self, *args, **kwargs): """ Takes in a name that has been split by spaces. Names which are in [last, first] format need to be preprocessed. The nickname must be in double quotes to be recognized as such. This can take name parts in in these or...
[ "def", "new_from_tokens", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'allow_quoted_nicknames'", ")", ":", "args", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "args", "if", "not",...
34.537313
16.38806
def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type): """ Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as 'anti-scoring' of far instances outside of r...
[ "def", "SURFstar_compute_scores", "(", "inst", ",", "attr", ",", "nan_entries", ",", "num_attributes", ",", "mcmap", ",", "NN_near", ",", "NN_far", ",", "headers", ",", "class_type", ",", "X", ",", "y", ",", "labels_std", ",", "data_type", ")", ":", "score...
81.461538
38.846154
async def set_playback_settings(self, target, value) -> None: """Set playback settings such a shuffle and repeat.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["avContent"]["setPlaybackModeSettings"](params)
[ "async", "def", "set_playback_settings", "(", "self", ",", "target", ",", "value", ")", "->", "None", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "return", "await", ...
68
22.5
def emulate_network(network_constraints, roles=None, inventory_path=None, extra_vars=None): """Emulate network links. Read ``network_constraints`` and apply ``tc`` rules on all the nodes. Constraints are applied between groups of machines. Theses ...
[ "def", "emulate_network", "(", "network_constraints", ",", "roles", "=", "None", ",", "inventory_path", "=", "None", ",", "extra_vars", "=", "None", ")", ":", "# 1) Retrieve the list of ips for all nodes (Ansible)", "# 2) Build all the constraints (Python)", "# {source:src...
33.284722
18.229167
def invitelist(self, channel): """ Get the channel invitelist. Required arguments: * channel - Channel of which to get the invitelist for. """ with self.lock: self.is_in_channel(channel) self.send('MODE %s i' % channel) invites = [] ...
[ "def", "invitelist", "(", "self", ",", "channel", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "is_in_channel", "(", "channel", ")", "self", ".", "send", "(", "'MODE %s i'", "%", "channel", ")", "invites", "=", "[", "]", "while", "self", ...
32.130435
17.695652
def reset_handler(self, cmd): """Process a ResetCommand.""" self.cmd_counts[cmd.name] += 1 if cmd.ref.startswith('refs/tags/'): self.lightweight_tags += 1 else: if cmd.from_ is not None: self.reftracker.track_heads_for_ref( cmd....
[ "def", "reset_handler", "(", "self", ",", "cmd", ")", ":", "self", ".", "cmd_counts", "[", "cmd", ".", "name", "]", "+=", "1", "if", "cmd", ".", "ref", ".", "startswith", "(", "'refs/tags/'", ")", ":", "self", ".", "lightweight_tags", "+=", "1", "els...
36.333333
6.888889
def _get_theme_label(catalog, theme): """Intenta conseguir el theme por id o por label.""" try: label = catalog.get_theme(identifier=theme)['label'] except BaseException: try: label = catalog.get_theme(label=theme)['label'] except BaseException: raise ce.Theme...
[ "def", "_get_theme_label", "(", "catalog", ",", "theme", ")", ":", "try", ":", "label", "=", "catalog", ".", "get_theme", "(", "identifier", "=", "theme", ")", "[", "'label'", "]", "except", "BaseException", ":", "try", ":", "label", "=", "catalog", ".",...
33.692308
16
def main(argd=None): """ Main entry point, expects doctopt arg dict as argd. """ global DEBUG, debug # The argd parameter for main() is for testing purposes only. argd = argd or docopt( USAGESTR, version=VERSIONSTR, script=SCRIPT, # Example usage of colr_docopt colors. ...
[ "def", "main", "(", "argd", "=", "None", ")", ":", "global", "DEBUG", ",", "debug", "# The argd parameter for main() is for testing purposes only.", "argd", "=", "argd", "or", "docopt", "(", "USAGESTR", ",", "version", "=", "VERSIONSTR", ",", "script", "=", "SCR...
27.102941
17.882353
def create_default_item_node(field, state): """Create a definition list item node that describes the default value of a Field config. Parameters ---------- field : ``lsst.pex.config.Field`` A configuration field. state : ``docutils.statemachine.State`` Usually the directive's ``...
[ "def", "create_default_item_node", "(", "field", ",", "state", ")", ":", "default_item", "=", "nodes", ".", "definition_list_item", "(", ")", "default_item", ".", "append", "(", "nodes", ".", "term", "(", "text", "=", "\"Default\"", ")", ")", "default_item_con...
31.84
14.84
def define_lattice_from_file( self, filename, cell_lengths ): """ Set up the simulation lattice from a file containing site data. Uses `init_lattice.lattice_from_sites_file`, which defines the site file spec. Args: filename (Str): sites file filename. cell_...
[ "def", "define_lattice_from_file", "(", "self", ",", "filename", ",", "cell_lengths", ")", ":", "self", ".", "lattice", "=", "init_lattice", ".", "lattice_from_sites_file", "(", "filename", ",", "cell_lengths", "=", "cell_lengths", ")" ]
39.692308
27.692308
def _collect_pathways_by_feature(self, pathway_feature_tuples): """Given a tuple list [(pathway, feature)], create a dictionary mapping each feature to the pathways overrepresented in the feature. """ pathways_in_feature = {} for (pathway, feature) in pathway_feature_tuples: ...
[ "def", "_collect_pathways_by_feature", "(", "self", ",", "pathway_feature_tuples", ")", ":", "pathways_in_feature", "=", "{", "}", "for", "(", "pathway", ",", "feature", ")", "in", "pathway_feature_tuples", ":", "vertex", "=", "self", ".", "add_pathway", "(", "p...
49.454545
11.818182
def get_provider_id(self): """Gets the ``Id`` of the provider. return: (osid.id.Id) - the provider ``Id`` *compliance: mandatory -- This method must be implemented.* """ if 'providerId' not in self._my_map or not self._my_map['providerId']: raise errors.IllegalState...
[ "def", "get_provider_id", "(", "self", ")", ":", "if", "'providerId'", "not", "in", "self", ".", "_my_map", "or", "not", "self", ".", "_my_map", "[", "'providerId'", "]", ":", "raise", "errors", ".", "IllegalState", "(", "'this sourceable object has no provider ...
40.3
21.7
def _getInputNeighborhood(self, centerInput): """ Gets a neighborhood of inputs. Simply calls topology.wrappingNeighborhood or topology.neighborhood. A subclass can insert different topology behavior by overriding this method. :param centerInput (int) The center of the neighborhood. @ret...
[ "def", "_getInputNeighborhood", "(", "self", ",", "centerInput", ")", ":", "if", "self", ".", "_wrapAround", ":", "return", "topology", ".", "wrappingNeighborhood", "(", "centerInput", ",", "self", ".", "_potentialRadius", ",", "self", ".", "_inputDimensions", "...
34.681818
19.045455
def discard_all(self, filterfunc=None): """Discard all waiting messages. :param filterfunc: A filter function to only discard the messages this filter returns. :returns: the number of messages discarded. *WARNING*: All incoming messages will be ignored and not processed. ...
[ "def", "discard_all", "(", "self", ",", "filterfunc", "=", "None", ")", ":", "if", "not", "filterfunc", ":", "return", "self", ".", "backend", ".", "queue_purge", "(", "self", ".", "queue", ")", "if", "self", ".", "no_ack", "or", "self", ".", "auto_ack...
31.184211
18.631579
def _to_dict(self): ''' Returns a dictionary representation of this object ''' return dict(latitude=self.latitude, longitude=self.longitude, depth=self.depth)
[ "def", "_to_dict", "(", "self", ")", ":", "return", "dict", "(", "latitude", "=", "self", ".", "latitude", ",", "longitude", "=", "self", ".", "longitude", ",", "depth", "=", "self", ".", "depth", ")" ]
42
11.6
def get_platform_for_target(self, target): """Find the platform associated with this target. :param JvmTarget target: target to query. :return: The jvm platform object. :rtype: JvmPlatformSettings """ if not target.payload.platform and target.is_synthetic: derived_from = target.derived_fr...
[ "def", "get_platform_for_target", "(", "self", ",", "target", ")", ":", "if", "not", "target", ".", "payload", ".", "platform", "and", "target", ".", "is_synthetic", ":", "derived_from", "=", "target", ".", "derived_from", "platform", "=", "derived_from", "and...
38.230769
13.769231
def get_out_segmentlistdict(self, process_ids = None): """ Return a segmentlistdict mapping instrument to out segment list. If process_ids is a sequence of process IDs, then only rows with matching IDs are included otherwise all rows are included. Note: the result is not coalesced, each segmentlist con...
[ "def", "get_out_segmentlistdict", "(", "self", ",", "process_ids", "=", "None", ")", ":", "seglists", "=", "segments", ".", "segmentlistdict", "(", ")", "for", "row", "in", "self", ":", "ifos", "=", "row", ".", "instruments", "or", "(", "None", ",", ")",...
38.352941
17.882353
def unwrap(self, value, session=None): ''' Unwraps the elements of ``value`` using ``ListField.item_type`` and returns them in a list''' kwargs = {} if self.has_autoload: kwargs['session'] = session self.validate_unwrap(value, **kwargs) return [ self.item_...
[ "def", "unwrap", "(", "self", ",", "value", ",", "session", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "self", ".", "has_autoload", ":", "kwargs", "[", "'session'", "]", "=", "session", "self", ".", "validate_unwrap", "(", "value", ",", "*...
44.125
13.625
def match_date(self, value, strict=False): """if value is a date""" value = stringify(value) try: parse(value) except Exception: self.shout('Value %r is not a valid date', strict, value)
[ "def", "match_date", "(", "self", ",", "value", ",", "strict", "=", "False", ")", ":", "value", "=", "stringify", "(", "value", ")", "try", ":", "parse", "(", "value", ")", "except", "Exception", ":", "self", ".", "shout", "(", "'Value %r is not a valid ...
33.714286
14
def _filter_jxns_donor_acceptor(sj_outP, annotDF, extDF): """Remove junctions that do not use an annotated donor or acceptor according to external junction annotation. Add strand and gene information for junctions according to external annoation (STAR strand ignored). Parameters ---------- sj_o...
[ "def", "_filter_jxns_donor_acceptor", "(", "sj_outP", ",", "annotDF", ",", "extDF", ")", ":", "import", "re", "sjRE", "=", "re", ".", "compile", "(", "'(.*:.*-.*):(\\+|-)'", ")", "juncRE", "=", "re", ".", "compile", "(", "'(.*):(\\d*)-(\\d*):'", ")", "# Add co...
44.218447
23.38835
def _currentResponse(self, debugInfo): """ Pull the current response off the queue. """ bd = b''.join(self._bufferedData) self._bufferedData = [] return AssuanResponse(bd, debugInfo)
[ "def", "_currentResponse", "(", "self", ",", "debugInfo", ")", ":", "bd", "=", "b''", ".", "join", "(", "self", ".", "_bufferedData", ")", "self", ".", "_bufferedData", "=", "[", "]", "return", "AssuanResponse", "(", "bd", ",", "debugInfo", ")" ]
32
3.428571
def get_volume(self, token, channel, x_start, x_stop, y_start, y_stop, z_start, z_stop, resolution=1, block_size=DEFAULT_BLOCK_SIZE, neariso=False): """ Get a RAMONVolume volumetric cutout f...
[ "def", "get_volume", "(", "self", ",", "token", ",", "channel", ",", "x_start", ",", "x_stop", ",", "y_start", ",", "y_stop", ",", "z_start", ",", "z_stop", ",", "resolution", "=", "1", ",", "block_size", "=", "DEFAULT_BLOCK_SIZE", ",", "neariso", "=", "...
41.5
15.357143
def filter_headers(criterion): """Filter already loaded headers against some criterion. The criterion function must accept a single argument, which is an instance of sastool.classes2.header.Header, or one of its subclasses. The function must return True if the header is to be kept or False if it needs ...
[ "def", "filter_headers", "(", "criterion", ")", ":", "ip", "=", "get_ipython", "(", ")", "for", "headerkind", "in", "[", "'processed'", ",", "'raw'", "]", ":", "for", "h", "in", "ip", ".", "user_ns", "[", "'_headers'", "]", "[", "headerkind", "]", "[",...
50.6
21.6
def simplify(script, texture=True, faces=25000, target_perc=0.0, quality_thr=0.3, preserve_boundary=False, boundary_weight=1.0, optimal_placement=True, preserve_normal=False, planar_quadric=False, selected=False, extra_tex_coord_weight=1.0, preserve_topology=True, qua...
[ "def", "simplify", "(", "script", ",", "texture", "=", "True", ",", "faces", "=", "25000", ",", "target_perc", "=", "0.0", ",", "quality_thr", "=", "0.3", ",", "preserve_boundary", "=", "False", ",", "boundary_weight", "=", "1.0", ",", "optimal_placement", ...
47.324324
20.871622
def create_configuration(name='Base'): """Create a configuration base class It is built using :class:`ConfigurationMeta`. Subclassing such a base class will register exposed methods .. class:: Base .. attribute:: configuration Configuration dict that can be used by a Router or th...
[ "def", "create_configuration", "(", "name", "=", "'Base'", ")", ":", "@", "classmethod", "def", "register", "(", "cls", ",", "element", ",", "action", ",", "method", ")", ":", "if", "not", "action", "in", "cls", ".", "configuration", ":", "cls", ".", "...
37.7
24
def get_install_requires_odoo_addons(addons_dir, depends_override={}, external_dependencies_override={}, odoo_version_override=None): """ Get the list of requirements for a directory containing addons """ ...
[ "def", "get_install_requires_odoo_addons", "(", "addons_dir", ",", "depends_override", "=", "{", "}", ",", "external_dependencies_override", "=", "{", "}", ",", "odoo_version_override", "=", "None", ")", ":", "addon_dirs", "=", "[", "]", "addons", "=", "os", "."...
42.590909
13.045455
def placebo_session(function): """ Decorator to help do testing with placebo. Simply wrap the function you want to test and make sure to add a "session" argument so the decorator can pass the placebo session. Accepts the following environment variables to configure placebo: PLACEBO_MODE: set to ...
[ "def", "placebo_session", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "session_kwargs", "=", "{", "'region_name'", ":", "os", ".", "environ", "....
34.347826
21.826087
def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False): """ Traverses the list of query paths to find the data requested :param query_path: (list(str), str), list of query path branches or query string Default b...
[ "def", "get", "(", "self", ",", "query_path", "=", "None", ",", "return_type", "=", "list", ",", "preceding_depth", "=", "None", ",", "throw_null_return_error", "=", "False", ")", ":", "function_type_lookup", "=", "{", "str", ":", "self", ".", "_get_path_ent...
62.068966
37.758621
def split(url): """Split URL into scheme, netloc, path, query and fragment. >>> split('http://www.example.com/abc?x=1&y=2#foo') SplitResult(scheme='http', netloc='www.example.com', path='/abc', query='x=1&y=2', fragment='foo') """ scheme = netloc = path = query = fragment = '' ip6_start = url.f...
[ "def", "split", "(", "url", ")", ":", "scheme", "=", "netloc", "=", "path", "=", "query", "=", "fragment", "=", "''", "ip6_start", "=", "url", ".", "find", "(", "'['", ")", "scheme_end", "=", "url", ".", "find", "(", "':'", ")", "if", "ip6_start", ...
30.5
14.362069
def trace(self, trace_obj): """ Trace given trace_obj (usuall a Message instance) recursively. :param trace_obj: :return: a string with properly formatted tracing information """ tracer = self tracer.writeln(u'%s = ' % trace_obj.__class__.__name__) tracer....
[ "def", "trace", "(", "self", ",", "trace_obj", ")", ":", "tracer", "=", "self", "tracer", ".", "writeln", "(", "u'%s = '", "%", "trace_obj", ".", "__class__", ".", "__name__", ")", "tracer", ".", "incr", "(", "'{'", ")", "for", "attr_name", "in", "trac...
44.810811
16.378378
def report_change(project, path, old_content): """Report that the contents of file at `path` was changed The new contents of file is retrieved by reading the file. """ resource = path_to_resource(project, path) if resource is None: return for observer in list(project.observers): ...
[ "def", "report_change", "(", "project", ",", "path", ",", "old_content", ")", ":", "resource", "=", "path_to_resource", "(", "project", ",", "path", ")", "if", "resource", "is", "None", ":", "return", "for", "observer", "in", "list", "(", "project", ".", ...
37.357143
16.214286
def create_multiple_expectations(df, columns, expectation_type, *args, **kwargs): """Creates an identical expectation for each of the given columns with the specified arguments, if any. Args: df (great_expectations.dataset): A great expectations dataset object. columns (list): A list of column ...
[ "def", "create_multiple_expectations", "(", "df", ",", "columns", ",", "expectation_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "expectation", "=", "getattr", "(", "df", ",", "expectation_type", ")", "results", "=", "list", "(", ")", "for",...
33.916667
28
def _log_intermediate_failure(self, err, flaky, name): """ Report that the test has failed, but still has reruns left. Then rerun the test. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Excepti...
[ "def", "_log_intermediate_failure", "(", "self", ",", "err", ",", "flaky", ",", "name", ")", ":", "max_runs", "=", "flaky", "[", "FlakyNames", ".", "MAX_RUNS", "]", "runs_left", "=", "max_runs", "-", "flaky", "[", "FlakyNames", ".", "CURRENT_RUNS", "]", "m...
32.36
16.84
def Lines(startPoints, endPoints=None, scale=1, lw=1, c=None, alpha=1, dotted=False): """ Build the line segments between two lists of points `startPoints` and `endPoints`. `startPoints` can be also passed in the form ``[[point1, point2], ...]``. :param float scale: apply a rescaling factor to the leng...
[ "def", "Lines", "(", "startPoints", ",", "endPoints", "=", "None", ",", "scale", "=", "1", ",", "lw", "=", "1", ",", "c", "=", "None", ",", "alpha", "=", "1", ",", "dotted", "=", "False", ")", ":", "if", "endPoints", "is", "not", "None", ":", "...
31.216216
21
def with_write_hdf5(func): """Decorate an HDF5-writing function to open a filepath if needed ``func`` should be written to take the object to be written as the first argument, and then presume an `h5py.Group` as the second. This method uses keywords ``append`` and ``overwrite`` as follows if the o...
[ "def", "with_write_hdf5", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated_func", "(", "obj", ",", "fobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=missing-docstring", "if", "not", "isinstance", "(", ...
41.653846
18.576923
def convert_namespaces_str( bel_str: str, api_url: str = None, namespace_targets: Mapping[str, List[str]] = None, canonicalize: bool = False, decanonicalize: bool = False, ) -> str: """Convert namespace in string Uses a regex expression to extract all NSArgs and replace them with the up...
[ "def", "convert_namespaces_str", "(", "bel_str", ":", "str", ",", "api_url", ":", "str", "=", "None", ",", "namespace_targets", ":", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", "=", "None", ",", "canonicalize", ":", "bool", "=", "False", ...
36.928571
23.095238
def joint_probabilities_nn( neighbors, distances, perplexities, symmetrize=True, normalization="pair-wise", n_reference_samples=None, n_jobs=1, ): """Compute the conditional probability matrix P_{j|i}. This method computes an approximation to P using the nearest neighbors. Para...
[ "def", "joint_probabilities_nn", "(", "neighbors", ",", "distances", ",", "perplexities", ",", "symmetrize", "=", "True", ",", "normalization", "=", "\"pair-wise\"", ",", "n_reference_samples", "=", "None", ",", "n_jobs", "=", "1", ",", ")", ":", "assert", "no...
33.638554
23.385542
def repr_return(func): """ This is a decorator to give the return value a pretty print repr """ def repr_return_decorator(*args, **kwargs): ret = func(*args, **kwargs) if isinstance(ret, basestring): return ret if type(ret) in repr_map: return repr_map[t...
[ "def", "repr_return", "(", "func", ")", ":", "def", "repr_return_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "ret", ",", "basestring", ...
25.3
17.4
def seekFromEnd(self, numRecords): """ Seeks to ``numRecords`` from the end and returns a bookmark to the new position. :param numRecords: how far to seek from end of file. :return: bookmark to desired location. """ self._file.seek(self._getTotalLineCount() - numRecords) return self.get...
[ "def", "seekFromEnd", "(", "self", ",", "numRecords", ")", ":", "self", ".", "_file", ".", "seek", "(", "self", ".", "_getTotalLineCount", "(", ")", "-", "numRecords", ")", "return", "self", ".", "getBookmark", "(", ")" ]
32.1
15.5
def set_action(self, action, message): """Set the action to be taken for this object. Assign an special "action" to this object to be taken in consideration in Holding Pen. The widget is referred to by a string with the filename minus extension. A message is also needed to tell...
[ "def", "set_action", "(", "self", ",", "action", ",", "message", ")", ":", "self", ".", "extra_data", "[", "\"_action\"", "]", "=", "action", "self", ".", "extra_data", "[", "\"_message\"", "]", "=", "message" ]
35.555556
17.611111
def intersperse(iterable, element): """Generator yielding all elements of `iterable`, but with `element` inserted between each two consecutive elements""" iterable = iter(iterable) yield next(iterable) while True: next_from_iterable = next(iterable) yield element yield next_f...
[ "def", "intersperse", "(", "iterable", ",", "element", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "yield", "next", "(", "iterable", ")", "while", "True", ":", "next_from_iterable", "=", "next", "(", "iterable", ")", "yield", "element", "yield...
36
9.666667
def info(cabdir, header=False): """ prints out help information about a cab """ # First check if cab exists pfile = "{}/parameters.json".format(cabdir) if not os.path.exists(pfile): raise RuntimeError("Cab could not be found at : {}".format(cabdir)) # Get cab info cab_definition = cab.C...
[ "def", "info", "(", "cabdir", ",", "header", "=", "False", ")", ":", "# First check if cab exists", "pfile", "=", "\"{}/parameters.json\"", ".", "format", "(", "cabdir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "pfile", ")", ":", "raise", ...
38
15.5