text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def local_time_to_online(dt=None): """Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as understood by AGOL (time in...
[ "def", "local_time_to_online", "(", "dt", "=", "None", ")", ":", "is_dst", "=", "None", "utc_offset", "=", "None", "try", ":", "if", "dt", "is", "None", ":", "dt", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "is_dst", "=", "time", ".", ...
32.159091
23.181818
def fastq_iter(handle, header=None): """Iterate over FASTQ file and return FASTQ entries Args: handle (file): FASTQ file handle, can be any iterator so long as it it returns subsequent "lines" of a FASTQ entry header (str): Header line of next FASTQ entry, if 'handle' has been ...
[ "def", "fastq_iter", "(", "handle", ",", "header", "=", "None", ")", ":", "# Speed tricks: reduces function calls", "append", "=", "list", ".", "append", "join", "=", "str", ".", "join", "strip", "=", "str", ".", "strip", "next_line", "=", "next", "if", "h...
36.714286
22.314286
def record_delete_subfield_from(rec, tag, subfield_position, field_position_global=None, field_position_local=None): """ Delete subfield from position specified. Specify the subfield by tag, field number and subfield position. """ subf...
[ "def", "record_delete_subfield_from", "(", "rec", ",", "tag", ",", "subfield_position", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "subfields", "=", "record_get_subfields", "(", "rec", ",", "tag", ",", "field_pos...
37.171429
16.371429
def competing_interests(soup, fntype_filter): """ Find the fn tags included in the competing interest """ competing_interests_section = extract_nodes(soup, "fn-group", attr="content-type", value="competing-interest") if not competing_interests_section: return None fn = extract_nodes(fir...
[ "def", "competing_interests", "(", "soup", ",", "fntype_filter", ")", ":", "competing_interests_section", "=", "extract_nodes", "(", "soup", ",", "\"fn-group\"", ",", "attr", "=", "\"content-type\"", ",", "value", "=", "\"competing-interest\"", ")", "if", "not", "...
34.5
20.333333
def run_nose(self, params): """ :type params: Params """ thread.set_index(params.thread_index) log.debug("[%s] Starting nose iterations: %s", params.worker_index, params) assert isinstance(params.tests, list) # argv.extend(['--with-apiritif', '--nocapture', '--exe...
[ "def", "run_nose", "(", "self", ",", "params", ")", ":", "thread", ".", "set_index", "(", "params", ".", "thread_index", ")", "log", ".", "debug", "(", "\"[%s] Starting nose iterations: %s\"", ",", "params", ".", "worker_index", ",", "params", ")", "assert", ...
41.061224
23.836735
def cli(env): """List options for creating Reserved Capacity""" manager = CapacityManager(env.client) items = manager.get_create_options() items.sort(key=lambda term: int(term['capacity'])) table = formatting.Table(["KeyName", "Description", "Term", "Default Hourly Price Per Instance"], ...
[ "def", "cli", "(", "env", ")", ":", "manager", "=", "CapacityManager", "(", "env", ".", "client", ")", "items", "=", "manager", ".", "get_create_options", "(", ")", "items", ".", "sort", "(", "key", "=", "lambda", "term", ":", "int", "(", "term", "["...
42.958333
21.916667
def stop(self): """Stop the stream and terminate PyAudio""" self.prestop() if not self._graceful: self._graceful = True self.stream.stop_stream() self.audio.terminate() msg = 'Stopped' self.verbose_info(msg, log=False) # Log 'Stopped' anyway ...
[ "def", "stop", "(", "self", ")", ":", "self", ".", "prestop", "(", ")", "if", "not", "self", ".", "_graceful", ":", "self", ".", "_graceful", "=", "True", "self", ".", "stream", ".", "stop_stream", "(", ")", "self", ".", "audio", ".", "terminate", ...
34.526316
12.578947
def synchronise_device_state(self, device_state, authentication_headers): """ Synchronizing the component states with AVS Components state must be synchronised with AVS after establishing the downchannel stream in order to create a persistent connection with AVS. Note that curr...
[ "def", "synchronise_device_state", "(", "self", ",", "device_state", ",", "authentication_headers", ")", ":", "payload", "=", "{", "'context'", ":", "device_state", ",", "'event'", ":", "{", "'header'", ":", "{", "'namespace'", ":", "'System'", ",", "'name'", ...
32.333333
18.958333
def args(self) -> str: """Provides arguments for the command.""" return '{}{}{}{}{}'.format( to_ascii_hex(self._index, 2), to_ascii_hex(self._group_number, 2), to_ascii_hex(self._unit_number, 2), to_ascii_hex(int(self._enable_status), 4), to_as...
[ "def", "args", "(", "self", ")", "->", "str", ":", "return", "'{}{}{}{}{}'", ".", "format", "(", "to_ascii_hex", "(", "self", ".", "_index", ",", "2", ")", ",", "to_ascii_hex", "(", "self", ".", "_group_number", ",", "2", ")", ",", "to_ascii_hex", "(",...
43.125
7.75
def notify_telegram(title, content, token=None, chat=None, mention_user=None, **kwargs): """ Sends a telegram notification and returns *True* on success. The communication with the telegram API might have some delays and is therefore handled by a thread. """ # test import import telegram # noqa...
[ "def", "notify_telegram", "(", "title", ",", "content", ",", "token", "=", "None", ",", "chat", "=", "None", ",", "mention_user", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# test import", "import", "telegram", "# noqa: F401", "cfg", "=", "Config", ...
32.596154
23.480769
def format_property(name, value): """Format the name and value (both unicode) of a property as a string.""" result = b'' utf8_name = utf8_bytes_string(name) result = b'property ' + utf8_name if value is not None: utf8_value = utf8_bytes_string(value) result += b' ' + ('%d' % len(utf...
[ "def", "format_property", "(", "name", ",", "value", ")", ":", "result", "=", "b''", "utf8_name", "=", "utf8_bytes_string", "(", "name", ")", "result", "=", "b'property '", "+", "utf8_name", "if", "value", "is", "not", "None", ":", "utf8_value", "=", "utf8...
34
18.454545
def length(self): """Returns the route length (cost) Returns ------- int Route length (cost). """ cost = 0 depot = self._problem.depot() last = depot for i in self._nodes: a, b = last, i if a.name() > b...
[ "def", "length", "(", "self", ")", ":", "cost", "=", "0", "depot", "=", "self", ".", "_problem", ".", "depot", "(", ")", "last", "=", "depot", "for", "i", "in", "self", ".", "_nodes", ":", "a", ",", "b", "=", "last", ",", "i", "if", "a", ".",...
21.347826
20.173913
def sigangledAngle(self,dangle,assumeZeroMean=True,smallest=False, simple=False): """ NAME: sigangledAngle PURPOSE: calculate the dispersion in the perpendicular angle at a given angle INPUT: dangle - angle offset along the str...
[ "def", "sigangledAngle", "(", "self", ",", "dangle", ",", "assumeZeroMean", "=", "True", ",", "smallest", "=", "False", ",", "simple", "=", "False", ")", ":", "if", "smallest", ":", "eigIndx", "=", "0", "else", ":", "eigIndx", "=", "1", "if", "simple",...
32.895833
25.979167
def short_encode(input, errors='strict'): """Transliterate to 8 bit using as few letters as possible. For example, \u00e4 LATIN SMALL LETTER A WITH DIAERESIS ``ä`` will be replaced with ``a``. """ if not isinstance(input, text_type): input = text_type(input, sys.getdefaultencoding(), error...
[ "def", "short_encode", "(", "input", ",", "errors", "=", "'strict'", ")", ":", "if", "not", "isinstance", "(", "input", ",", "text_type", ")", ":", "input", "=", "text_type", "(", "input", ",", "sys", ".", "getdefaultencoding", "(", ")", ",", "errors", ...
36
15.166667
def attempt_dev_link_via_import(self, egg): """Create egg-link to FS location if an egg is found through importing. Sometimes an egg *is* installed, but without a proper egg-info file. So we attempt to import the egg in order to return a link anyway. TODO: currently it only works with ...
[ "def", "attempt_dev_link_via_import", "(", "self", ",", "egg", ")", ":", "try", ":", "imported", "=", "__import__", "(", "egg", ")", "except", "ImportError", ":", "self", ".", "logger", ".", "warn", "(", "\"Tried importing '%s', but that also didn't work.\"", ",",...
39.774194
20.225806
def step_impl06(context): """Prepare test for singleton property. :param context: test context. """ store = context.SingleStore context.st_1 = store() context.st_2 = store() context.st_3 = store()
[ "def", "step_impl06", "(", "context", ")", ":", "store", "=", "context", ".", "SingleStore", "context", ".", "st_1", "=", "store", "(", ")", "context", ".", "st_2", "=", "store", "(", ")", "context", ".", "st_3", "=", "store", "(", ")" ]
24.111111
12.555556
def request(self, apdu): """This function is called by transaction functions to send to the application.""" if _debug: ServerSSM._debug("request %r", apdu) # make sure it has a good source and destination apdu.pduSource = self.pdu_address apdu.pduDestination = None ...
[ "def", "request", "(", "self", ",", "apdu", ")", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\"request %r\"", ",", "apdu", ")", "# make sure it has a good source and destination", "apdu", ".", "pduSource", "=", "self", ".", "pdu_address", "apdu",...
34.181818
13.181818
def create_session(self, session_id, register=True): """Creates new session object and returns it. `request` Request that created the session. Will be used to get query string parameters and cookies `register` Should be session registered in a storage. Websoc...
[ "def", "create_session", "(", "self", ",", "session_id", ",", "register", "=", "True", ")", ":", "# TODO: Possible optimization here for settings.get", "s", "=", "self", ".", "_session_kls", "(", "self", ".", "_connection", ",", "self", ",", "session_id", ",", "...
33.095238
18.714286
def to_string(self, buf=None, na_rep='NaN', float_format=None, header=True, index=True, length=False, dtype=False, name=False, max_rows=None): """ Render a string representation of the Series. Parameters ---------- buf : StringIO-like, optiona...
[ "def", "to_string", "(", "self", ",", "buf", "=", "None", ",", "na_rep", "=", "'NaN'", ",", "float_format", "=", "None", ",", "header", "=", "True", ",", "index", "=", "True", ",", "length", "=", "False", ",", "dtype", "=", "False", ",", "name", "=...
37.303571
17.446429
def check_dependency(self, operation, dependency): """ Enhances default behavior of method by checking dependency for matching operation. """ if isinstance(dependency[1], SQLBlob): # NOTE: we follow the sort order created by `assemble_changes` so we build a fixed chain ...
[ "def", "check_dependency", "(", "self", ",", "operation", ",", "dependency", ")", ":", "if", "isinstance", "(", "dependency", "[", "1", "]", ",", "SQLBlob", ")", ":", "# NOTE: we follow the sort order created by `assemble_changes` so we build a fixed chain", "# of operati...
57
23.444444
def em_rates_from_E_DA_mix(em_rates_tot, E_values): """D and A emission rates for two populations. """ em_rates_d, em_rates_a = [], [] for em_rate_tot, E_value in zip(em_rates_tot, E_values): em_rate_di, em_rate_ai = em_rates_from_E_DA(em_rate_tot, E_value) em_rates_d.append(em_rate_di) ...
[ "def", "em_rates_from_E_DA_mix", "(", "em_rates_tot", ",", "E_values", ")", ":", "em_rates_d", ",", "em_rates_a", "=", "[", "]", ",", "[", "]", "for", "em_rate_tot", ",", "E_value", "in", "zip", "(", "em_rates_tot", ",", "E_values", ")", ":", "em_rate_di", ...
42.555556
9.111111
def resolve_possible_paths(path, relative_prefix, possible_extensions=None, leading_underscore=False): """ Attempts to resolve the given absolute or relative ``path``. If it doesn't exist as is, tries to create an absolute path using the ``relative_prefix``. If that fails, tries relative/absolute versio...
[ "def", "resolve_possible_paths", "(", "path", ",", "relative_prefix", ",", "possible_extensions", "=", "None", ",", "leading_underscore", "=", "False", ")", ":", "possible_extensions", "=", "[", "''", "]", "+", "list", "(", "possible_extensions", ")", "if", "pos...
44.25
26.75
def write_gpio(self, gpio=None): """Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written. """ if gpio is not None: self.gpio = gpio self._device.writeList(self.GPIO, self.gpio)
[ "def", "write_gpio", "(", "self", ",", "gpio", "=", "None", ")", ":", "if", "gpio", "is", "not", "None", ":", "self", ".", "gpio", "=", "gpio", "self", ".", "_device", ".", "writeList", "(", "self", ".", "GPIO", ",", "self", ".", "gpio", ")" ]
41.142857
9.285714
def _handle_list_marker(self): """Handle a list marker at the head (``#``, ``*``, ``;``, ``:``).""" markup = self._read() if markup == ";": self._context |= contexts.DL_TERM self._emit(tokens.TagOpenOpen(wiki_markup=markup)) self._emit_text(get_html_tag(markup)) ...
[ "def", "_handle_list_marker", "(", "self", ")", ":", "markup", "=", "self", ".", "_read", "(", ")", "if", "markup", "==", "\";\"", ":", "self", ".", "_context", "|=", "contexts", ".", "DL_TERM", "self", ".", "_emit", "(", "tokens", ".", "TagOpenOpen", ...
44.25
8.75
def uninstall_packages(): """ Uninstall unwanted packages """ p = server_state('packages_installed') if p: installed = set(p) else: return env.uninstalled_packages[env.host] = [] #first uninstall any that have been taken off the list packages = set(get_packages()) uninstall = ins...
[ "def", "uninstall_packages", "(", ")", ":", "p", "=", "server_state", "(", "'packages_installed'", ")", "if", "p", ":", "installed", "=", "set", "(", "p", ")", "else", ":", "return", "env", ".", "uninstalled_packages", "[", "env", ".", "host", "]", "=", ...
32.25
10.75
def generateKey(self, template, mecha=MechanismAESGENERATEKEY): """ generate a secret key :param template: template for the secret key :param mecha: mechanism to use :return: handle of the generated key :rtype: PyKCS11.LowLevel.CK_OBJECT_HANDLE """ t = se...
[ "def", "generateKey", "(", "self", ",", "template", ",", "mecha", "=", "MechanismAESGENERATEKEY", ")", ":", "t", "=", "self", ".", "_template2ckattrlist", "(", "template", ")", "ck_handle", "=", "PyKCS11", ".", "LowLevel", ".", "CK_OBJECT_HANDLE", "(", ")", ...
36
12.375
def _scalar_to_vector(self, m): """Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model) """ if not isinstance(m.y0, numbers.Number): return m else: m = copy.deepcopy(m) t0 = 0.0 if isinstanc...
[ "def", "_scalar_to_vector", "(", "self", ",", "m", ")", ":", "if", "not", "isinstance", "(", "m", ".", "y0", ",", "numbers", ".", "Number", ")", ":", "return", "m", "else", ":", "m", "=", "copy", ".", "deepcopy", "(", "m", ")", "t0", "=", "0.0", ...
40.05
12.9
def create(self, api_version=values.unset, friendly_name=values.unset, sms_application_sid=values.unset, sms_fallback_method=values.unset, sms_fallback_url=values.unset, sms_method=values.unset, sms_url=values.unset, status_callback=values.unset, status_callba...
[ "def", "create", "(", "self", ",", "api_version", "=", "values", ".", "unset", ",", "friendly_name", "=", "values", ".", "unset", ",", "sms_application_sid", "=", "values", ".", "unset", ",", "sms_fallback_method", "=", "values", ".", "unset", ",", "sms_fall...
58.2375
28.8125
def restore_scrollbar_position(self): """Restoring scrollbar position after main window is visible""" scrollbar_pos = self.get_option('scrollbar_position', None) if scrollbar_pos is not None: self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)
[ "def", "restore_scrollbar_position", "(", "self", ")", ":", "scrollbar_pos", "=", "self", ".", "get_option", "(", "'scrollbar_position'", ",", "None", ")", "if", "scrollbar_pos", "is", "not", "None", ":", "self", ".", "explorer", ".", "treewidget", ".", "set_s...
58
13.2
def upvote_num(self): """获取收到的的赞同数量. :return: 收到的的赞同数量 :rtype: int """ if self.url is None: return 0 else: number = int(self.soup.find( 'span', class_='zm-profile-header-user-agree').strong.text) return number
[ "def", "upvote_num", "(", "self", ")", ":", "if", "self", ".", "url", "is", "None", ":", "return", "0", "else", ":", "number", "=", "int", "(", "self", ".", "soup", ".", "find", "(", "'span'", ",", "class_", "=", "'zm-profile-header-user-agree'", ")", ...
24.916667
17
def check_events(self): """Call the event dispatcher. Quit the main loop when the `QUIT` event is reached. :Return: `True` if `QUIT` was reached. """ if self.event_dispatcher.flush() is QUIT: self._quit = True return True return False
[ "def", "check_events", "(", "self", ")", ":", "if", "self", ".", "event_dispatcher", ".", "flush", "(", ")", "is", "QUIT", ":", "self", ".", "_quit", "=", "True", "return", "True", "return", "False" ]
27.090909
16.363636
def system_add_column_family(self, cf_def): """ adds a column family. returns the new schema id. Parameters: - cf_def """ self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_system_add_column_family(cf_def) return d
[ "def", "system_add_column_family", "(", "self", ",", "cf_def", ")", ":", "self", ".", "_seqid", "+=", "1", "d", "=", "self", ".", "_reqs", "[", "self", ".", "_seqid", "]", "=", "defer", ".", "Deferred", "(", ")", "self", ".", "send_system_add_column_fami...
24.090909
15.545455
def load_library(lib, name=None, lib_cls=None): """Loads a library. Catches and logs exceptions. Returns: the loaded library or None arguments: * lib -- path to/name of the library to be loaded * name -- the library's identifier (for logging) Defaults to None. ...
[ "def", "load_library", "(", "lib", ",", "name", "=", "None", ",", "lib_cls", "=", "None", ")", ":", "try", ":", "if", "lib_cls", ":", "return", "lib_cls", "(", "lib", ")", "else", ":", "return", "ctypes", ".", "CDLL", "(", "lib", ")", "except", "Ex...
28.035714
17.285714
def _read_proc_file(path, opts): ''' Return a dict of JID metadata, or None ''' serial = salt.payload.Serial(opts) current_thread = threading.currentThread().name pid = os.getpid() with salt.utils.files.fopen(path, 'rb') as fp_: buf = fp_.read() fp_.close() if buf: ...
[ "def", "_read_proc_file", "(", "path", ",", "opts", ")", ":", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "opts", ")", "current_thread", "=", "threading", ".", "currentThread", "(", ")", ".", "name", "pid", "=", "os", ".", "getpid", "(",...
30.721311
17.836066
def _geu16(ins): ''' Compares & pops top 2 operands out of the stack, and checks if the 1st operand >= 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 16 bit unsigned version ''' output = _16bit_oper(ins.quad[2], ins.quad[3]) output.append('or a') output.append...
[ "def", "_geu16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ")", "output", ".", "append", "(", "'or a'", ")", "output", ".", "append", "(", "'sbc hl, de'", "...
30.214286
18.071429
def parse_config(config_file): """Parse a YAML configuration file""" try: with open(config_file, 'r') as f: return yaml.load(f) except IOError: print "Configuration file {} not found or not readable.".format(config_file) raise
[ "def", "parse_config", "(", "config_file", ")", ":", "try", ":", "with", "open", "(", "config_file", ",", "'r'", ")", "as", "f", ":", "return", "yaml", ".", "load", "(", "f", ")", "except", "IOError", ":", "print", "\"Configuration file {} not found or not r...
33.375
18
def _srm(self, data): """Expectation-Maximization algorithm for fitting the probabilistic SRM. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. Returns -...
[ "def", "_srm", "(", "self", ",", "data", ")", ":", "local_min", "=", "min", "(", "[", "d", ".", "shape", "[", "1", "]", "for", "d", "in", "data", "if", "d", "is", "not", "None", "]", ",", "default", "=", "sys", ".", "maxsize", ")", "samples", ...
42.647482
22.841727
def normalized_messages(self, no_field_name='_entity'): """Return all the error messages as a dictionary""" if isinstance(self.messages, dict): return self.messages if not self.field_names: return {no_field_name: self.messages} return dict((name, self.messages) f...
[ "def", "normalized_messages", "(", "self", ",", "no_field_name", "=", "'_entity'", ")", ":", "if", "isinstance", "(", "self", ".", "messages", ",", "dict", ")", ":", "return", "self", ".", "messages", "if", "not", "self", ".", "field_names", ":", "return",...
42.625
14.25
def cmd_print(self): """Returns the raw lines to be printed.""" if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
[ "def", "cmd_print", "(", "self", ")", ":", "if", "not", "self", ".", "_valid_lines", ":", "return", "''", "return", "'\\n'", ".", "join", "(", "[", "line", ".", "raw_line", "for", "line", "in", "self", ".", "_valid_lines", "]", ")", "+", "'\\n'" ]
40.4
16.8
def update(self, item, id_expression=None, upsert=False, update_ops={}, safe=None, **kwargs): ''' Update an item in the database. Uses the on_update keyword to each field to decide which operations to do, or. :param item: An instance of a :class:`~ommongo.document.Document` \ subclass :param id_express...
[ "def", "update", "(", "self", ",", "item", ",", "id_expression", "=", "None", ",", "upsert", "=", "False", ",", "update_ops", "=", "{", "}", ",", "safe", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "safe", "is", "None", ":", "safe", "="...
46.09375
25.40625
def update_factor_providers(self, factor_name, name, body): """Get Guardian factor providers. Returns provider configuration Args: factor_name (str): Either push-notification or sms name (str): Name of the provider body (dict): See: https://auth0...
[ "def", "update_factor_providers", "(", "self", ",", "factor_name", ",", "name", ",", "body", ")", ":", "url", "=", "self", ".", "_url", "(", "'factors/{}/providers/{}'", ".", "format", "(", "factor_name", ",", "name", ")", ")", "return", "self", ".", "clie...
37.923077
19.461538
def submit_post_searchquery(url, data, apikey): '''This submits a POST query to an LCC-Server search API endpoint. Handles streaming of the results, and returns the final JSON stream. Also handles results that time out. Parameters ---------- url : str The URL of the search API endpoin...
[ "def", "submit_post_searchquery", "(", "url", ",", "data", ",", "apikey", ")", ":", "# first, we need to convert any columns and collections items to broken out", "# params", "postdata", "=", "{", "}", "for", "key", "in", "data", ":", "if", "key", "==", "'columns'", ...
33.140625
25.015625
def _assert_valid_start(start_int, count_int, total_int): """Assert that the number of objects visible to the active subject is higher than the requested start position for the slice. This ensures that it's possible to create a valid slice. """ if total_int and start_int >= total_int: rais...
[ "def", "_assert_valid_start", "(", "start_int", ",", "count_int", ",", "total_int", ")", ":", "if", "total_int", "and", "start_int", ">=", "total_int", ":", "raise", "d1_common", ".", "types", ".", "exceptions", ".", "InvalidRequest", "(", "0", ",", "'Requeste...
37.142857
19.571429
def duplicate(self): ''' Returns a copy of the current address. @returns: Address ''' return self.__class__(street_address=self.street_address, city=self.city, zipcode=self.zipcode, state=self.state, country=self.country...
[ "def", "duplicate", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "street_address", "=", "self", ".", "street_address", ",", "city", "=", "self", ".", "city", ",", "zipcode", "=", "self", ".", "zipcode", ",", "state", "=", "self", "."...
39.25
22.5
def has_offline_historical_manager_or_raise(self): """Raises an exception if model uses a history manager and historical model history_id is not a UUIDField. Note: expected to use edc_model.HistoricalRecords instead of simple_history.HistoricalRecords. """ try: ...
[ "def", "has_offline_historical_manager_or_raise", "(", "self", ")", ":", "try", ":", "model", "=", "self", ".", "instance", ".", "__class__", ".", "history", ".", "model", "except", "AttributeError", ":", "model", "=", "self", ".", "instance", ".", "__class__"...
49.666667
19.809524
def scale(self, x, y=None, z=None): "Uniform scale, if only sx argument is specified" if y is None: y = x if z is None: z = x m = self for col in range(4): # Only the top three rows m[0,col] *= x m[1,col] *= y ...
[ "def", "scale", "(", "self", ",", "x", ",", "y", "=", "None", ",", "z", "=", "None", ")", ":", "if", "y", "is", "None", ":", "y", "=", "x", "if", "z", "is", "None", ":", "z", "=", "x", "m", "=", "self", "for", "col", "in", "range", "(", ...
27.307692
15.461538
def get_search_fields(self, exclude=None): """ Get the fields for searching for an item. """ exclude = set(exclude) if self.search_fields and len(self.search_fields) > 1: exclude = exclude.union(self.search_fields) return self.get_filter_fields(exclude=exclud...
[ "def", "get_search_fields", "(", "self", ",", "exclude", "=", "None", ")", ":", "exclude", "=", "set", "(", "exclude", ")", "if", "self", ".", "search_fields", "and", "len", "(", "self", ".", "search_fields", ")", ">", "1", ":", "exclude", "=", "exclud...
34.888889
12.444444
def item_huisnummer_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Huisnummer` to json. """ return { 'id': obj.id, 'huisnummer': obj.huisnummer, 'postadres': obj.postadres, 'status': { 'id': obj.status.id, ...
[ "def", "item_huisnummer_adapter", "(", "obj", ",", "request", ")", ":", "return", "{", "'id'", ":", "obj", ".", "id", ",", "'huisnummer'", ":", "obj", ".", "huisnummer", ",", "'postadres'", ":", "obj", ".", "postadres", ",", "'status'", ":", "{", "'id'",...
34.266667
14.533333
def invalid_type_error(method_name, arg_name, got_value, expected_type, version='0.13.0'): """Raise a CompilationException when an adapter method available to macros has changed. """ got_type = type(got_value) msg = ("As of {version}, 'adapter.{method_name}' expects argument "...
[ "def", "invalid_type_error", "(", "method_name", ",", "arg_name", ",", "got_value", ",", "expected_type", ",", "version", "=", "'0.13.0'", ")", ":", "got_type", "=", "type", "(", "got_value", ")", "msg", "=", "(", "\"As of {version}, 'adapter.{method_name}' expects ...
53.083333
18.666667
def set_precision(predictions, labels, weights_fn=common_layers.weights_nonzero): """Precision of set predictions. Args: predictions : A Tensor of scores of shape [batch, nlabels]. labels: A Tensor of int32s giving true set elements, of shape [batch, seq_length]. weights_fn: A f...
[ "def", "set_precision", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_nonzero", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"set_precision\"", ",", "values", "=", "[", "predictions", ",", "labels", "]", ")"...
37.571429
14.952381
def _w_within_shard(args: Dict[str, Any]): """Applies a W gate when the gate acts only within a shard.""" index = args['index'] half_turns = args['half_turns'] axis_half_turns = args['axis_half_turns'] state = _state_shard(args) pm_vect = _pm_vects(args)[index] num_shard_qubits = args['num_s...
[ "def", "_w_within_shard", "(", "args", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "index", "=", "args", "[", "'index'", "]", "half_turns", "=", "args", "[", "'half_turns'", "]", "axis_half_turns", "=", "args", "[", "'axis_half_turns'", "]", "sta...
38
12.909091
def windows_dir_format(host_dir, user): """Format a string for the location of the user's folder on the Windows (TJ03) fileserver.""" if user and user.grade: grade = int(user.grade) else: return host_dir if grade in range(9, 13): win_path = "/{}/".format(user.username) else:...
[ "def", "windows_dir_format", "(", "host_dir", ",", "user", ")", ":", "if", "user", "and", "user", ".", "grade", ":", "grade", "=", "int", "(", "user", ".", "grade", ")", "else", ":", "return", "host_dir", "if", "grade", "in", "range", "(", "9", ",", ...
31.5
15.416667
def search_range(self, value): """Set private ``_search_range`` and reset ``_block_matcher``.""" if value == 0 or not value % 16: self._search_range = value else: raise InvalidSearchRangeError("Search range must be a multiple of " ...
[ "def", "search_range", "(", "self", ",", "value", ")", ":", "if", "value", "==", "0", "or", "not", "value", "%", "16", ":", "self", ".", "_search_range", "=", "value", "else", ":", "raise", "InvalidSearchRangeError", "(", "\"Search range must be a multiple of ...
43.375
12.5
def mapColorRampToValues(cls, colorRamp, minValue, maxValue, alpha=1.0): """ Creates color ramp based on min and max values of all the raster pixels from all rasters. If pixel value is one of the no data values it will be excluded in the color ramp interpolation. Returns colorRamp, slope, interc...
[ "def", "mapColorRampToValues", "(", "cls", ",", "colorRamp", ",", "minValue", ",", "maxValue", ",", "alpha", "=", "1.0", ")", ":", "minRampIndex", "=", "0", "# Always zero", "maxRampIndex", "=", "float", "(", "len", "(", "colorRamp", ")", "-", "1", ")", ...
49.090909
27.818182
def operation(func=None, pipeline_facts=None): ''' Decorator that takes a simple module function and turn it into the internal operation representation that consists of a list of commands + options (sudo, (sudo|su)_user, env). ''' # If not decorating, return function with config attached if...
[ "def", "operation", "(", "func", "=", "None", ",", "pipeline_facts", "=", "None", ")", ":", "# If not decorating, return function with config attached", "if", "func", "is", "None", ":", "def", "decorator", "(", "f", ")", ":", "setattr", "(", "f", ",", "'pipeli...
33.727273
21.008264
def _is_inside(self, span1, span2, covered_spans): """Returns True if both `span1` and `span2` fall within `covered_spans`. :param span1: start and end indices of a span :type span1: 2-`tuple` of `int` :param span2: start and end indices of a span :type span2: 2-`tuple` ...
[ "def", "_is_inside", "(", "self", ",", "span1", ",", "span2", ",", "covered_spans", ")", ":", "if", "self", ".", "_is_span_inside", "(", "span1", ",", "covered_spans", "[", "0", "]", ")", "and", "self", ".", "_is_span_inside", "(", "span2", ",", "covered...
40.555556
17.888889
def get_ip_packet(data, client_port, server_port, is_loopback=False): """ if client_port is 0 any client_port is good """ header = _loopback if is_loopback else _ethernet try: header.unpack(data) except Exception as ex: raise ValueError('Bad header: %s' % ex) tcp_p = getattr(header...
[ "def", "get_ip_packet", "(", "data", ",", "client_port", ",", "server_port", ",", "is_loopback", "=", "False", ")", ":", "header", "=", "_loopback", "if", "is_loopback", "else", "_ethernet", "try", ":", "header", ".", "unpack", "(", "data", ")", "except", ...
35.173913
19.043478
def schedule(self, func, *args, **kwargs): """ Schedules a function func for execution. One special parameter is track_progress. If passed in and not None, the func will be passed in a keyword parameter called update_progress: def update_progress(progress, total_progress, stage...
[ "def", "schedule", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# if the func is already a job object, just schedule that directly.", "if", "isinstance", "(", "func", ",", "Job", ")", ":", "job", "=", "func", "# else, turn it i...
43
29.105263
def GenerateClient(args): """Driver for client code generation.""" codegen = _GetCodegenFromFlags(args) if codegen is None: logging.error('Failed to create codegen, exiting.') return 128 _WriteGeneratedFiles(args, codegen) if args.init_file != 'none': _WriteInit(codegen)
[ "def", "GenerateClient", "(", "args", ")", ":", "codegen", "=", "_GetCodegenFromFlags", "(", "args", ")", "if", "codegen", "is", "None", ":", "logging", ".", "error", "(", "'Failed to create codegen, exiting.'", ")", "return", "128", "_WriteGeneratedFiles", "(", ...
27.909091
15.909091
def PCA_reduce(X, Q): """ A helpful function for linearly reducing the dimensionality of the data X to Q. :param X: data array of size N (number of points) x D (dimensions) :param Q: Number of latent dimensions, Q < D :return: PCA projection array of size N x Q. """ assert Q <= X.shape[1...
[ "def", "PCA_reduce", "(", "X", ",", "Q", ")", ":", "assert", "Q", "<=", "X", ".", "shape", "[", "1", "]", ",", "'Cannot have more latent dimensions than observed'", "evals", ",", "evecs", "=", "np", ".", "linalg", ".", "eigh", "(", "np", ".", "cov", "(...
38.75
16.916667
def logtrick_minimizer(minimizer): r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from scipy.optimize i...
[ "def", "logtrick_minimizer", "(", "minimizer", ")", ":", "@", "wraps", "(", "minimizer", ")", "def", "new_minimizer", "(", "fun", ",", "x0", ",", "jac", "=", "True", ",", "bounds", "=", "None", ",", "*", "*", "minimizer_kwargs", ")", ":", "if", "bounds...
31.055556
21.236111
def get_real_percent(self): """get_real_percent() Returns the unmodified percentage of the score based on a 0-point scale.""" if not (self.votes and self.score): return 0 return 100 * (self.get_real_rating() / self.field.range)
[ "def", "get_real_percent", "(", "self", ")", ":", "if", "not", "(", "self", ".", "votes", "and", "self", ".", "score", ")", ":", "return", "0", "return", "100", "*", "(", "self", ".", "get_real_rating", "(", ")", "/", "self", ".", "field", ".", "ra...
39.142857
13.142857
def template_global(self, name: Optional[str]=None) -> Callable: """Add a template global. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.template_global('name') def five(): return 5 Arguments: ...
[ "def", "template_global", "(", "self", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Callable", ":", "def", "decorator", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "self", ".", "add_template_global", "(", "func", ...
29.111111
19.777778
def exportFile(self, jobStoreFileID, dstUrl): """ Exports file to destination pointed at by the destination URL. See :func:`toil.jobStores.abstractJobStore.AbstractJobStore.exportFile` for a full description """ self._assertContextManagerUsed() self._jobStore.exp...
[ "def", "exportFile", "(", "self", ",", "jobStoreFileID", ",", "dstUrl", ")", ":", "self", ".", "_assertContextManagerUsed", "(", ")", "self", ".", "_jobStore", ".", "exportFile", "(", "jobStoreFileID", ",", "dstUrl", ")" ]
38.111111
17
def get_parent_ps(self): """ Return a :class:`ParameterSet` of all Parameters in the same :class:`phoebe.frontend.bundle.Bundle` which share the same meta-tags (except qualifier, twig, uniquetwig) :return: the parent :class:`ParameterSet` """ if self._bundle is N...
[ "def", "get_parent_ps", "(", "self", ")", ":", "if", "self", ".", "_bundle", "is", "None", ":", "return", "None", "metawargs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "meta", ".", "items", "(", ")", "if", "k", "not", "...
34.857143
22
def has_error(self): """ Queries the server to check if the job has an error. Returns True or False. """ self.get_info() if 'status' not in self.info: return False if 'hasError' not in self.info['status']: return False return self...
[ "def", "has_error", "(", "self", ")", ":", "self", ".", "get_info", "(", ")", "if", "'status'", "not", "in", "self", ".", "info", ":", "return", "False", "if", "'hasError'", "not", "in", "self", ".", "info", "[", "'status'", "]", ":", "return", "Fals...
25.769231
15.153846
def can_create_gradebook_with_record_types(self, gradebook_record_types): """Tests if this user can create a single ``Gradebook`` using the desired record types. While ``GradingManager.getGradebookRecordTypes()`` can be used to examine which records are supported, this method tests which ...
[ "def", "can_create_gradebook_with_record_types", "(", "self", ",", "gradebook_record_types", ")", ":", "# Implemented from template for", "# osid.resource.BinAdminSession.can_create_bin_with_record_types", "# NOTE: It is expected that real authentication hints will be", "# handled in a service...
54.375
26.625
def RetryQuestion(question_text, output_re="", default_val=None): """Continually ask a question until the output_re is matched.""" while True: if default_val is not None: new_text = "%s [%s]: " % (question_text, default_val) else: new_text = "%s: " % question_text # pytype: disable=wrong-arg...
[ "def", "RetryQuestion", "(", "question_text", ",", "output_re", "=", "\"\"", ",", "default_val", "=", "None", ")", ":", "while", "True", ":", "if", "default_val", "is", "not", "None", ":", "new_text", "=", "\"%s [%s]: \"", "%", "(", "question_text", ",", "...
36.3125
16.3125
def rate_limit(max_interval=20, sampling=3, f=lambda x: x): '''x rises by 1 from 0 on each iteraton, back to 0 on triggering. f(x) should rise up to f(max_interval) in some way (with default "f(x)=x" probability rises lineary with 100% chance on "x=max_interval"). "sampling" affect probablility in an "c=1-(1-c0...
[ "def", "rate_limit", "(", "max_interval", "=", "20", ",", "sampling", "=", "3", ",", "f", "=", "lambda", "x", ":", "x", ")", ":", "from", "random", "import", "random", "val", "=", "0", "val_max", "=", "float", "(", "f", "(", "max_interval", ")", ")...
38.6
23.8
def render(template, saltenv='base', sls='', tmplpath=None, **kws): ''' Render the python module's components :rtype: string ''' template = tmplpath if not os.path.isfile(template): raise SaltRenderError('Template {0} is not a file!'.format(template)) tmp_data = salt.utils.template...
[ "def", "render", "(", "template", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "tmplpath", "=", "None", ",", "*", "*", "kws", ")", ":", "template", "=", "tmplpath", "if", "not", "os", ".", "path", ".", "isfile", "(", "template", ")", ...
28.387097
17.225806
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']: self.wploader.expected_count = m.count if self.wp_op is None: #self.console.error("No waypoint load started") ...
[ "def", "mavlink_packet", "(", "self", ",", "m", ")", ":", "mtype", "=", "m", ".", "get_type", "(", ")", "if", "mtype", "in", "[", "'WAYPOINT_COUNT'", ",", "'MISSION_COUNT'", "]", ":", "self", ".", "wploader", ".", "expected_count", "=", "m", ".", "coun...
47.638889
18.194444
def setsweep(self, sweep=0, channel=0): """set the sweep and channel of an ABF. Both start at 0.""" try: sweep=int(sweep) except: self.log.error("trying to set sweep to [%s]",sweep) return if sweep<0: sweep=self.sweeps-1-sweep # if negative...
[ "def", "setsweep", "(", "self", ",", "sweep", "=", "0", ",", "channel", "=", "0", ")", ":", "try", ":", "sweep", "=", "int", "(", "sweep", ")", "except", ":", "self", ".", "log", ".", "error", "(", "\"trying to set sweep to [%s]\"", ",", "sweep", ")"...
52.721311
25.52459
def getOutEdges(self, label=None): """Gets all the outgoing edges of the node. If label parameter is provided, it only returns the edges of the given label @params label: Optional parameter to filter the edges @returns A generator function with the outgoing edges""" if l...
[ "def", "getOutEdges", "(", "self", ",", "label", "=", "None", ")", ":", "if", "label", ":", "for", "edge", "in", "self", ".", "neoelement", ".", "relationships", ".", "outgoing", "(", "types", "=", "[", "label", "]", ")", ":", "yield", "Edge", "(", ...
41.384615
17.846154
def login(self, response): """ Login using email/username and password, used to get the auth token @param str account @param str password @param int duration (optional) """ self._state_params['auth'] = response['auth'] self._user_data = response['user'] ...
[ "def", "login", "(", "self", ",", "response", ")", ":", "self", ".", "_state_params", "[", "'auth'", "]", "=", "response", "[", "'auth'", "]", "self", ".", "_user_data", "=", "response", "[", "'user'", "]", "if", "not", "self", ".", "logged_in", ":", ...
31.833333
12.166667
def send_video(self, user_id, media_id, title=None, description=None, account=None): """ 发送视频消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param media_id: 发送的视频的媒体ID。 可...
[ "def", "send_video", "(", "self", ",", "user_id", ",", "media_id", ",", "title", "=", "None", ",", "description", "=", "None", ",", "account", "=", "None", ")", ":", "video_data", "=", "{", "'media_id'", ":", "media_id", ",", "}", "if", "title", ":", ...
29.111111
20.444444
def time_delay_from_earth_center(self, right_ascension, declination, t_gps): """Return the time delay from the earth center """ return self.time_delay_from_location(np.array([0, 0, 0]), right_ascension, dec...
[ "def", "time_delay_from_earth_center", "(", "self", ",", "right_ascension", ",", "declination", ",", "t_gps", ")", ":", "return", "self", ".", "time_delay_from_location", "(", "np", ".", "array", "(", "[", "0", ",", "0", ",", "0", "]", ")", ",", "right_asc...
53.571429
15.714286
def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): """ Delete all thumbnails for a source image. """ thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix) return _delete_us...
[ "def", "delete_thumbnails", "(", "relative_source_path", ",", "root", "=", "None", ",", "basedir", "=", "None", ",", "subdir", "=", "None", ",", "prefix", "=", "None", ")", ":", "thumbs", "=", "thumbnails_for_file", "(", "relative_source_path", ",", "root", ...
42
10.25
def encrypt(self, password, kdf=None, iterations=None): ''' Generate a string with the encrypted key, as in :meth:`~eth_account.account.Account.encrypt`, but without a private key argument. ''' return self._publicapi.encrypt(self.privateKey, password, kdf=kdf, iterations=iteratio...
[ "def", "encrypt", "(", "self", ",", "password", ",", "kdf", "=", "None", ",", "iterations", "=", "None", ")", ":", "return", "self", ".", "_publicapi", ".", "encrypt", "(", "self", ".", "privateKey", ",", "password", ",", "kdf", "=", "kdf", ",", "ite...
53
32.333333
def setup(app): """Setup.""" # add_html_theme is new in Sphinx 1.6+ if hasattr(app, 'add_html_theme'): theme_path = get_html_theme_path()[0] app.add_html_theme('bootstrap', os.path.join(theme_path, 'bootstrap'))
[ "def", "setup", "(", "app", ")", ":", "# add_html_theme is new in Sphinx 1.6+", "if", "hasattr", "(", "app", ",", "'add_html_theme'", ")", ":", "theme_path", "=", "get_html_theme_path", "(", ")", "[", "0", "]", "app", ".", "add_html_theme", "(", "'bootstrap'", ...
39
12
def setup_seasonal(self): """ Check if there's some seasonal holiday going on, setup appropriate Shibe picture and load holiday words. Note: if there are two or more holidays defined for a certain date, the first one takes precedence. """ # If we've specified a...
[ "def", "setup_seasonal", "(", "self", ")", ":", "# If we've specified a season, just run that one", "if", "self", ".", "ns", ".", "season", ":", "return", "self", ".", "load_season", "(", "self", ".", "ns", ".", "season", ")", "# If we've specified another doge or n...
34.53125
20.78125
def fire_failed_contact_lookup(self, msisdn): """ Fires a webhook in the event of a failed WhatsApp contact lookup. """ payload = {"address": msisdn} # We cannot user the raw_hook_event here, because we don't have a user, so we # manually filter and send the hooks for all...
[ "def", "fire_failed_contact_lookup", "(", "self", ",", "msisdn", ")", ":", "payload", "=", "{", "\"address\"", ":", "msisdn", "}", "# We cannot user the raw_hook_event here, because we don't have a user, so we", "# manually filter and send the hooks for all users", "hooks", "=", ...
45
18.833333
def disable_category(self, category: str, message_to_print: str) -> None: """ Disable an entire category of commands :param category: the category to disable :param message_to_print: what to print when anything in this category is run or help is called on it ...
[ "def", "disable_category", "(", "self", ",", "category", ":", "str", ",", "message_to_print", ":", "str", ")", "->", "None", ":", "all_commands", "=", "self", ".", "get_all_commands", "(", ")", "for", "cmd_name", "in", "all_commands", ":", "func", "=", "se...
52.235294
25.411765
def send_request(self, http_request): """ Send a request and get response """ self.request_object = http_request self.build_socket() self.build_request() try: self.sock.send(self.request) except socket.error as err: raise errors.Tes...
[ "def", "send_request", "(", "self", ",", "http_request", ")", ":", "self", ".", "request_object", "=", "http_request", "self", ".", "build_socket", "(", ")", "self", ".", "build_request", "(", ")", "try", ":", "self", ".", "sock", ".", "send", "(", "self...
31.111111
10.888889
def write_slide_list(self, logname, slides): """ Write list of slides to logfile """ # Write slides.txt with list of slides with open('%s/%s' % (self.cache, logname), 'w') as logfile: for slide in slides: heading = slide['heading']['text'] filename = s...
[ "def", "write_slide_list", "(", "self", ",", "logname", ",", "slides", ")", ":", "# Write slides.txt with list of slides", "with", "open", "(", "'%s/%s'", "%", "(", "self", ".", "cache", ",", "logname", ")", ",", "'w'", ")", "as", "logfile", ":", "for", "s...
45.7
12.4
def format_cffi_externs(cls): """Generate stubs for the cffi bindings from @_extern_decl methods.""" extern_decls = [ f.extern_signature.pretty_print() for _, f in cls._extern_fields.items() ] return ( 'extern "Python" {\n' + '\n'.join(extern_decls) + '\n}\n')
[ "def", "format_cffi_externs", "(", "cls", ")", ":", "extern_decls", "=", "[", "f", ".", "extern_signature", ".", "pretty_print", "(", ")", "for", "_", ",", "f", "in", "cls", ".", "_extern_fields", ".", "items", "(", ")", "]", "return", "(", "'extern \"Py...
29.7
14.5
def defaults_decorator(defaults): """Decorator to append default kwargs to a function. """ def decorator(func): """Function that appends default kwargs to a function. """ kwargs = dict(header='Keyword arguments\n-----------------\n', indent=' ', ...
[ "def", "defaults_decorator", "(", "defaults", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"Function that appends default kwargs to a function.\n \"\"\"", "kwargs", "=", "dict", "(", "header", "=", "'Keyword arguments\\n-----------------\\n'", ",", "ind...
31.9375
11.9375
def _find_update_fields(cls, field, doc): """Find the fields in the update document which match the given field. Both the field and the top level keys in the doc may be in dot notation, eg "a.b.c". Returns a list of tuples (path, field_value) or the empty list if the field is not presen...
[ "def", "_find_update_fields", "(", "cls", ",", "field", ",", "doc", ")", ":", "def", "find_partial_matches", "(", ")", ":", "for", "key", "in", "doc", ":", "if", "len", "(", "key", ")", ">", "len", "(", "field", ")", ":", "# Handle case where field is a ...
48.864865
19.324324
def spit_config(self, conf_file, firstwordonly=False): """conf_file a file opened for writing.""" cfg = ConfigParser.RawConfigParser() for sec in _CONFIG_SECS: cfg.add_section(sec) sec = 'channels' for i in sorted(self.pack.D): cfg.set(sec, str(i), ...
[ "def", "spit_config", "(", "self", ",", "conf_file", ",", "firstwordonly", "=", "False", ")", ":", "cfg", "=", "ConfigParser", ".", "RawConfigParser", "(", ")", "for", "sec", "in", "_CONFIG_SECS", ":", "cfg", ".", "add_section", "(", "sec", ")", "sec", "...
30.117647
16.588235
def submit_status_external_cmd(cmd_file, status_file): ''' Submits the status lines in the status_file to Nagios' external cmd file. ''' try: with open(cmd_file, 'a') as cmd_file: cmd_file.write(status_file.read()) except IOError: exit("Fatal error: Unable to write to Nagios external command file ...
[ "def", "submit_status_external_cmd", "(", "cmd_file", ",", "status_file", ")", ":", "try", ":", "with", "open", "(", "cmd_file", ",", "'a'", ")", "as", "cmd_file", ":", "cmd_file", ".", "write", "(", "status_file", ".", "read", "(", ")", ")", "except", "...
43.777778
24.222222
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'request') and self.request is not None: _dict['request'] = self.request._to_dict() if hasattr(self, 'response') and self.response is not None: _dict['response'...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'request'", ")", "and", "self", ".", "request", "is", "not", "None", ":", "_dict", "[", "'request'", "]", "=", "self", ".", "request", ".", "_to_d...
50.238095
20.47619
def remove_data_flows_with_data_port_id(self, data_port_id): """Remove an data ports whose from_key or to_key equals the passed data_port_id :param int data_port_id: the id of a data_port of which all data_flows should be removed, the id can be a input or output data port id...
[ "def", "remove_data_flows_with_data_port_id", "(", "self", ",", "data_port_id", ")", ":", "# delete all data flows in parent related to data_port_id and self.state_id = external data flows", "# checking is_root_state_of_library is only necessary in case of scoped variables, as the scoped variables...
62.37931
35.827586
def gallery_image_versions(self): """Instance depends on the API version: * 2018-06-01: :class:`GalleryImageVersionsOperations<azure.mgmt.compute.v2018_06_01.operations.GalleryImageVersionsOperations>` * 2019-03-01: :class:`GalleryImageVersionsOperations<azure.mgmt.compute.v2019_03_01.ope...
[ "def", "gallery_image_versions", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'gallery_image_versions'", ")", "if", "api_version", "==", "'2018-06-01'", ":", "from", ".", "v2018_06_01", ".", "operations", "import", "GalleryImageV...
68.428571
40.714286
def reset(ctx): """ Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values. """ click.echo("Resetting OpenPGP data, don't remove your YubiKey...") ctx.obj['controller'].reset() click.echo('Success! All data has been cleared and defaul...
[ "def", "reset", "(", "ctx", ")", ":", "click", ".", "echo", "(", "\"Resetting OpenPGP data, don't remove your YubiKey...\"", ")", "ctx", ".", "obj", "[", "'controller'", "]", ".", "reset", "(", ")", "click", ".", "echo", "(", "'Success! All data has been cleared a...
31.909091
21.181818
def receive(self, msg): """ Returns a (receiver, msg) pair, where receiver is `None` if no route for the message was found, or otherwise an object with a `receive` method that can accept that `msg`. """ x = self.routing while not isinstance(x, ActionList): ...
[ "def", "receive", "(", "self", ",", "msg", ")", ":", "x", "=", "self", ".", "routing", "while", "not", "isinstance", "(", "x", ",", "ActionList", ")", ":", "if", "not", "x", "or", "not", "msg", ":", "return", "None", ",", "msg", "if", "not", "isi...
31.777778
17.333333
def count_alleles_subpops(self, subpops, max_allele=None): """Count alleles for multiple subpopulations simultaneously. Parameters ---------- subpops : dict (string -> sequence of ints) Mapping of subpopulation names to sample indices. max_allele : int, optional ...
[ "def", "count_alleles_subpops", "(", "self", ",", "subpops", ",", "max_allele", "=", "None", ")", ":", "if", "max_allele", "is", "None", ":", "max_allele", "=", "self", ".", "max", "(", ")", "out", "=", "{", "name", ":", "self", ".", "count_alleles", "...
30.8
22.6
def decode(self, images, save=None, round=4, names=None, **kwargs): """ Decodes a set of images. Args: images: The images to decode. Can be: - A single String specifying the filename of the image to decode - A list of filenames - A single NumPy array contai...
[ "def", "decode", "(", "self", ",", "images", ",", "save", "=", "None", ",", "round", "=", "4", ",", "names", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "images", ",", "string_types", ")", ":", "images", "=", "[", "im...
37.296296
23.240741
def _tag_net_direction(data): """Create a tag based on the direction of the traffic""" # IP or IPv6 src = data['packet']['src_domain'] dst = data['packet']['dst_domain'] if src == 'internal': if dst == 'internal' or 'multicast' in dst or 'broadcast' in dst: ...
[ "def", "_tag_net_direction", "(", "data", ")", ":", "# IP or IPv6", "src", "=", "data", "[", "'packet'", "]", "[", "'src_domain'", "]", "dst", "=", "data", "[", "'packet'", "]", "[", "'dst_domain'", "]", "if", "src", "==", "'internal'", ":", "if", "dst",...
32.133333
14.933333
def segment(self, value=None, scope=None, metric_scope=None, **selection): """ Return a new query, limited to a segment of all users or sessions. Accepts segment objects, filtered segment objects and segment names: ```python query.segment(account.segments['browser']) qu...
[ "def", "segment", "(", "self", ",", "value", "=", "None", ",", "scope", "=", "None", ",", "metric_scope", "=", "None", ",", "*", "*", "selection", ")", ":", "\"\"\"\n Technical note to self about segments:\n\n * users or sessions\n * sequence or condi...
37.147368
26.410526
def get_file(self, key, fp, headers, cb=None, num_cb=10, torrent=False, version_id=None): """ Retrieves a file from a Key :type key: :class:`boto.s3.key.Key` or subclass :param key: The Key object from which upload is to be downloaded :type fp: file ...
[ "def", "get_file", "(", "self", ",", "key", ",", "fp", ",", "headers", ",", "cb", "=", "None", ",", "num_cb", "=", "10", ",", "torrent", "=", "False", ",", "version_id", "=", "None", ")", ":", "debug", "=", "key", ".", "bucket", ".", "connection", ...
47.165289
22.603306
def col_dtypes(df): # Does some work to reduce possibility of errors and stuff """ Returns dictionary of datatypes in a DataFrame (uses string representation) Parameters: df - DataFrame The DataFrame to return the object types of Pandas datatypes are as follows: object,number,bool,datet...
[ "def", "col_dtypes", "(", "df", ")", ":", "# Does some work to reduce possibility of errors and stuff", "test_list", "=", "[", "col_isobj", ",", "col_isnum", ",", "col_isbool", ",", "col_isdt", ",", "col_iscat", ",", "col_istdelt", ",", "col_isdtz", "]", "deque_list",...
44.85
22.25