text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def add_reads(self, reads): """ Create another VariantSequence with more supporting reads. """ if len(reads) == 0: return self new_reads = self.reads.union(reads) if len(new_reads) > len(self.reads): return VariantSequence( prefix=s...
[ "def", "add_reads", "(", "self", ",", "reads", ")", ":", "if", "len", "(", "reads", ")", "==", "0", ":", "return", "self", "new_reads", "=", "self", ".", "reads", ".", "union", "(", "reads", ")", "if", "len", "(", "new_reads", ")", ">", "len", "(...
30.266667
10.266667
def convert_html_to_xml(self): """ Parses the HTML parsed texts and converts its tags to XML valid tags. :returns: HTML enabled text in a XML valid format. :rtype: str """ if hasattr(self, 'content') and self.content != '': regex = r'<(?!/)(?!!)' ...
[ "def", "convert_html_to_xml", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'content'", ")", "and", "self", ".", "content", "!=", "''", ":", "regex", "=", "r'<(?!/)(?!!)'", "xml_content", "=", "re", ".", "sub", "(", "regex", ",", "'<xhtml:'"...
30.5
19.357143
def set_control_scheme(self, index): """Sets the control scheme for the agent. See :obj:`ControlSchemes`. Args: index (int): The control scheme to use. Should be set with an enum from :obj:`ControlSchemes`. """ self._current_control_scheme = index % self._num_control_schemes...
[ "def", "set_control_scheme", "(", "self", ",", "index", ")", ":", "self", ".", "_current_control_scheme", "=", "index", "%", "self", ".", "_num_control_schemes", "self", ".", "_control_scheme_buffer", "[", "0", "]", "=", "self", ".", "_current_control_scheme" ]
47.875
24.75
def _from_dict(cls, _dict): """Initialize a DocumentAccepted object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: args['status'] = _dict.get('status') if 'notices' in _d...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'document_id'", "in", "_dict", ":", "args", "[", "'document_id'", "]", "=", "_dict", ".", "get", "(", "'document_id'", ")", "if", "'status'", "in", "_dict", ":", "...
37.916667
13.916667
def assert_no_current_path(self, path, **kwargs): """ Asserts that the page doesn't have the given path. Args: path (str | RegexObject): The string or regex that the current "path" should match. **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`. ...
[ "def", "assert_no_current_path", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "query", "=", "CurrentPathQuery", "(", "path", ",", "*", "*", "kwargs", ")", "@", "self", ".", "document", ".", "synchronize", "def", "assert_no_current_path", "(...
29.24
25
def _generate_base_svm_classifier_spec(model): """ Takes an SVM classifier produces a starting spec using the parts. that are shared between all SVMs. """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') check_fitted(model, la...
[ "def", "_generate_base_svm_classifier_spec", "(", "model", ")", ":", "if", "not", "(", "_HAS_SKLEARN", ")", ":", "raise", "RuntimeError", "(", "'scikit-learn not found. scikit-learn conversion API is disabled.'", ")", "check_fitted", "(", "model", ",", "lambda", "m", ":...
33.787879
18.757576
def define(self): """Defines a new server.""" self.server_def = self.consul.define_server( self.name, self.server_tpl, self.server_tpl_rev, self.instance_type, self.ssh_key_name, tags=self.tags, ...
[ "def", "define", "(", "self", ")", ":", "self", ".", "server_def", "=", "self", ".", "consul", ".", "define_server", "(", "self", ".", "name", ",", "self", ".", "server_tpl", ",", "self", ".", "server_tpl_rev", ",", "self", ".", "instance_type", ",", "...
37.071429
10.857143
def multiple(layer: int, limit: int) -> Set[str]: """Returns a set of strings to be used as Slots with Pabianas default Clock. Args: layer: The layer in the hierarchy this Area is placed in. Technically, the number specifies how many of the Clocks signals are relevant to the Area. Between 1 and limit. limi...
[ "def", "multiple", "(", "layer", ":", "int", ",", "limit", ":", "int", ")", "->", "Set", "[", "str", "]", ":", "return", "{", "str", "(", "x", ")", ".", "zfill", "(", "2", ")", "for", "x", "in", "[", "2", "**", "x", "for", "x", "in", "range...
44.8
22.9
def _calculate_aes_cipher(key): """ Determines if the key is a valid AES 128, 192 or 256 key :param key: A byte string of the key to use :raises: ValueError - when an invalid key is provided :return: A unicode string of the AES variation - "aes128", "aes192" or "aes256" ...
[ "def", "_calculate_aes_cipher", "(", "key", ")", ":", "if", "len", "(", "key", ")", "not", "in", "[", "16", ",", "24", ",", "32", "]", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be either 16, 24 or 32 bytes (128, 192 or 256 ...
22.83871
21.612903
def do_upgrade(self): """Implement your upgrades here.""" sql = text('delete from upgrade where upgrade = :upgrade') db.engine.execute( sct(ql, upgrade='invenio_upgrader_2015_11_12_innodb_removal'))
[ "def", "do_upgrade", "(", "self", ")", ":", "sql", "=", "text", "(", "'delete from upgrade where upgrade = :upgrade'", ")", "db", ".", "engine", ".", "execute", "(", "sct", "(", "ql", ",", "upgrade", "=", "'invenio_upgrader_2015_11_12_innodb_removal'", ")", ")" ]
46
18.6
def all_coplanar(triangles): """ Check to see if a list of triangles are all coplanar Parameters ---------------- triangles: (n, 3, 3) float Vertices of triangles Returns --------------- all_coplanar : bool True if all triangles are coplanar """ triangles = np.asany...
[ "def", "all_coplanar", "(", "triangles", ")", ":", "triangles", "=", "np", ".", "asanyarray", "(", "triangles", ",", "dtype", "=", "np", ".", "float64", ")", "if", "not", "util", ".", "is_shape", "(", "triangles", ",", "(", "-", "1", ",", "3", ",", ...
31.64
17.72
def fullversion(): ''' Shows installed version of dnsmasq and compile options. CLI Example: .. code-block:: bash salt '*' dnsmasq.fullversion ''' cmd = 'dnsmasq -v' out = __salt__['cmd.run'](cmd).splitlines() comps = out[0].split() version_num = comps[2] comps = out[1]...
[ "def", "fullversion", "(", ")", ":", "cmd", "=", "'dnsmasq -v'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ".", "splitlines", "(", ")", "comps", "=", "out", "[", "0", "]", ".", "split", "(", ")", "version_num", "=", "comps", "...
22.941176
20.235294
def calc_mass(nu_max, delta_nu, teff): """ asteroseismic scaling relations """ NU_MAX = 3140.0 # microHz DELTA_NU = 135.03 # microHz TEFF = 5777.0 return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5
[ "def", "calc_mass", "(", "nu_max", ",", "delta_nu", ",", "teff", ")", ":", "NU_MAX", "=", "3140.0", "# microHz", "DELTA_NU", "=", "135.03", "# microHz", "TEFF", "=", "5777.0", "return", "(", "nu_max", "/", "NU_MAX", ")", "**", "3", "*", "(", "delta_nu", ...
39
13.5
def range_compress(ol): ''' #only support sorted-ints or sorted-ascii l = [1,5,6,7,8,13,14,18,30,31,32,33,34] range_compress(l) l = [1,5,6,7,8,13,14,18,30,31,32,33,34,40] range_compress(l) l = ['a','b','c','d','j','k','l','m','n','u','y','z'] range_compress(l)...
[ "def", "range_compress", "(", "ol", ")", ":", "T", "=", "(", "type", "(", "ol", "[", "0", "]", ")", "==", "type", "(", "0", ")", ")", "if", "(", "T", ")", ":", "l", "=", "ol", "else", ":", "l", "=", "array_map", "(", "ol", ",", "ord", ")"...
22.265306
19.653061
def transform_data(self, data): '''Transform Pandas Timeseries into JSON format Parameters ---------- data: DataFrame or Series Pandas DataFrame or Series must have datetime index Returns ------- JSON to object.json_data Example ----...
[ "def", "transform_data", "(", "self", ",", "data", ")", ":", "def", "type_check", "(", "value", ")", ":", "'''Type check values for JSON serialization. Native Python JSON\n serialization will not recognize some Numpy data types properly,\n so they must be explictly ...
34.276596
19.723404
def convert_uv(pinyin): """ü 转换,还原原始的韵母 ü行的韵跟声母j,q,x拼的时候,写成ju(居),qu(区),xu(虚), ü上两点也省略;但是跟声母n,l拼的时候,仍然写成nü(女),lü(吕)。 """ return UV_RE.sub( lambda m: ''.join((m.group(1), UV_MAP[m.group(2)], m.group(3))), pinyin)
[ "def", "convert_uv", "(", "pinyin", ")", ":", "return", "UV_RE", ".", "sub", "(", "lambda", "m", ":", "''", ".", "join", "(", "(", "m", ".", "group", "(", "1", ")", ",", "UV_MAP", "[", "m", ".", "group", "(", "2", ")", "]", ",", "m", ".", "...
26.555556
15
def disconnect(self): """Gracefully disconnect from the server.""" with self.lock: if self.stream: if self.settings[u"initial_presence"]: self.send(Presence(stanza_type = "unavailable")) self.stream.disconnect()
[ "def", "disconnect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "stream", ":", "if", "self", ".", "settings", "[", "u\"initial_presence\"", "]", ":", "self", ".", "send", "(", "Presence", "(", "stanza_type", "=", "\"una...
40.714286
13
def tilequeue_enqueue_random_pyramids(cfg, peripherals, args): """enqueue random pyramids""" from tilequeue.stats import RawrTileEnqueueStatsHandler from tilequeue.rawr import make_rawr_enqueuer_from_cfg logger = make_logger(cfg, 'enqueue_random_pyramids') rawr_yaml = cfg.yml.get('rawr') asse...
[ "def", "tilequeue_enqueue_random_pyramids", "(", "cfg", ",", "peripherals", ",", "args", ")", ":", "from", "tilequeue", ".", "stats", "import", "RawrTileEnqueueStatsHandler", "from", "tilequeue", ".", "rawr", "import", "make_rawr_enqueuer_from_cfg", "logger", "=", "ma...
34.656716
18.253731
def create_attachment(self, container, attachment_file, **kw): """Create an Attachment object in the given container """ filename = getattr(attachment_file, "filename", "Attachment") attachment = api.create(container, "Attachment", title=filename) attachment.edit(AttachmentFile=a...
[ "def", "create_attachment", "(", "self", ",", "container", ",", "attachment_file", ",", "*", "*", "kw", ")", ":", "filename", "=", "getattr", "(", "attachment_file", ",", "\"filename\"", ",", "\"Attachment\"", ")", "attachment", "=", "api", ".", "create", "(...
48.636364
14.636364
def add_inputs(self, inputs): # type: (Iterable[Address]) -> None """ Adds inputs to spend in the bundle. Note that each input may require multiple transactions, in order to hold the entire signature. :param inputs: Addresses to use as the inputs for this bu...
[ "def", "add_inputs", "(", "self", ",", "inputs", ")", ":", "# type: (Iterable[Address]) -> None", "if", "self", ".", "hash", ":", "raise", "RuntimeError", "(", "'Bundle is already finalized.'", ")", "for", "addy", "in", "inputs", ":", "if", "addy", ".", "balance...
31.666667
17.541667
def encode(self): ''' Encode and store a CONNACK control packet. ''' header = bytearray(1) varHeader = bytearray(2) header[0] = 0x20 varHeader[0] = self.session varHeader[1] = self.resultCode header.extend(encodeLength(len(varHe...
[ "def", "encode", "(", "self", ")", ":", "header", "=", "bytearray", "(", "1", ")", "varHeader", "=", "bytearray", "(", "2", ")", "header", "[", "0", "]", "=", "0x20", "varHeader", "[", "0", "]", "=", "self", ".", "session", "varHeader", "[", "1", ...
30.714286
14.142857
def remove(name): """Removes a snapshot""" app = get_app() snapshot = app.get_snapshot(name) if not snapshot: click.echo("Couldn't find snapshot %s" % name) sys.exit(1) click.echo("Deleting snapshot %s" % name) app.remove_snapshot(snapshot) click.echo("Deleted")
[ "def", "remove", "(", "name", ")", ":", "app", "=", "get_app", "(", ")", "snapshot", "=", "app", ".", "get_snapshot", "(", "name", ")", "if", "not", "snapshot", ":", "click", ".", "echo", "(", "\"Couldn't find snapshot %s\"", "%", "name", ")", "sys", "...
24.75
17.416667
def assert_in_setup_repo(setup_fpath, name=''): """ pass in __file__ from setup.py """ setup_dir, setup_fname = split(setup_fpath) cwd = os.getcwd() #repo_dname = split(setup_dir)[1] #print('cwd = %r' % (cwd)) #print('repo_dname = %r' % repo_dname) #print('setup_dir = %r' % (setup_dir)...
[ "def", "assert_in_setup_repo", "(", "setup_fpath", ",", "name", "=", "''", ")", ":", "setup_dir", ",", "setup_fname", "=", "split", "(", "setup_fpath", ")", "cwd", "=", "os", ".", "getcwd", "(", ")", "#repo_dname = split(setup_dir)[1]", "#print('cwd = %r' % ...
42.947368
14.105263
def _request(self, *args, **kwargs): """Make the request""" try: self.response = self.request( *args, headers=self._request_headers(), **kwargs) except BaseException, err: code = 520 if hasattr(err, 'status_int'): code = err.sta...
[ "def", "_request", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "response", "=", "self", ".", "request", "(", "*", "args", ",", "headers", "=", "self", ".", "_request_headers", "(", ")", ",", "*", "*"...
40.454545
11.727273
def get_linked_agenda_items(self) -> List[str]: """ Returns entities that can be linked to spans in the question, that should be in the agenda, for training a coverage based semantic parser. This method essentially does a heuristic entity linking, to provide weak supervision for a learni...
[ "def", "get_linked_agenda_items", "(", "self", ")", "->", "List", "[", "str", "]", ":", "agenda_items", ":", "List", "[", "str", "]", "=", "[", "]", "for", "entity", "in", "self", ".", "_get_longest_span_matching_entities", "(", ")", ":", "agenda_items", "...
55.857143
23.285714
def day_crumb(date): """ Crumb for a day. """ year = date.strftime('%Y') month = date.strftime('%m') day = date.strftime('%d') return Crumb(day, reverse('zinnia:entry_archive_day', args=[year, month, day]))
[ "def", "day_crumb", "(", "date", ")", ":", "year", "=", "date", ".", "strftime", "(", "'%Y'", ")", "month", "=", "date", ".", "strftime", "(", "'%m'", ")", "day", "=", "date", ".", "strftime", "(", "'%d'", ")", "return", "Crumb", "(", "day", ",", ...
28.444444
11.333333
def create( cls, api_key=None, idempotency_key=None, stripe_account=None, **params ): """Return a deferred.""" url = cls.class_url() headers = populate_headers(idempotency_key) return make_request( cls, 'post', url, stripe_account=stripe_account, heade...
[ "def", "create", "(", "cls", ",", "api_key", "=", "None", ",", "idempotency_key", "=", "None", ",", "stripe_account", "=", "None", ",", "*", "*", "params", ")", ":", "url", "=", "cls", ".", "class_url", "(", ")", "headers", "=", "populate_headers", "("...
37.555556
17.555556
def firehose(self, **params): """Stream statuses/firehose :param \*\*params: Parameters to send with your stream request Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/statuses/firehose """ url = 'https://stream.twitter.com/%s/statuses/firehose.json'...
[ "def", "firehose", "(", "self", ",", "*", "*", "params", ")", ":", "url", "=", "'https://stream.twitter.com/%s/statuses/firehose.json'", "%", "self", ".", "streamer", ".", "api_version", "self", ".", "streamer", ".", "_request", "(", "url", ",", "params", "=",...
36.818182
17.727273
def preprovision_rbridge_id_wwn(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") preprovision = ET.SubElement(config, "preprovision", xmlns="urn:brocade.com:mgmt:brocade-preprovision") rbridge_id = ET.SubElement(preprovision, "rbridge-id") rbridge...
[ "def", "preprovision_rbridge_id_wwn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "preprovision", "=", "ET", ".", "SubElement", "(", "config", ",", "\"preprovision\"", ",", "xmlns", "=", "\"u...
45.153846
16.769231
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. Call super class method with hypocentral depth fixed at 20 km """ ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# fix hypocentral depth to 20 km. Create new rupture context to avoid", "# changing the original one", "new_rup", "=", "copy", ".", "deepcopy", ...
36.411765
17.823529
def connect_euca(host=None, aws_access_key_id=None, aws_secret_access_key=None, port=8773, path='/services/Eucalyptus', is_secure=False, **kwargs): """ Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server...
[ "def", "connect_euca", "(", "host", "=", "None", ",", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "port", "=", "8773", ",", "path", "=", "'/services/Eucalyptus'", ",", "is_secure", "=", "False", ",", "*", "*", "kwargs", ...
34.210526
18.842105
def process_data(self, sockets): """Called when there is more data to read on connection sockets. Arguments: sockets -- A list of socket objects. See documentation for Reactor.__init__. """ with self.mutex: log.log(logging.DEBUG - 2, "process_data()") ...
[ "def", "process_data", "(", "self", ",", "sockets", ")", ":", "with", "self", ".", "mutex", ":", "log", ".", "log", "(", "logging", ".", "DEBUG", "-", "2", ",", "\"process_data()\"", ")", "for", "sock", ",", "conn", "in", "itertools", ".", "product", ...
32.928571
16.714286
def clear_values(self, red=0.0, green=0.0, blue=0.0, alpha=0.0, depth=1.0): """ Sets the clear values for the window buffer. Args: red (float): red compoent green (float): green compoent blue (float): blue compoent alpha (float): alpha compoent ...
[ "def", "clear_values", "(", "self", ",", "red", "=", "0.0", ",", "green", "=", "0.0", ",", "blue", "=", "0.0", ",", "alpha", "=", "0.0", ",", "depth", "=", "1.0", ")", ":", "self", ".", "clear_color", "=", "(", "red", ",", "green", ",", "blue", ...
34
10.923077
def overlay_gateway_attach_rbridge_id(self, **kwargs): """Configure Overlay Gateway attach rbridge id Args: gw_name: Name of Overlay Gateway <WORD:1-32> rbridge_id: Single or range of rbridge id to be added/removed get (bool): Get config instead of editing config. ...
[ "def", "overlay_gateway_attach_rbridge_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "get_config", "=", "kwargs", ".", "pop", "(", "'get'", ",", "False", ...
43.651515
20.30303
def get_re_experiment(case, minor=1): """ Returns an experiment that uses the Roth-Erev learning method. """ gen = case.generators profile = array([1.0]) maxSteps = len(profile) experimentation = 0.55 recency = 0.3 tau = 100.0 decay = 0.99#9995 market = pyreto.SmartMarket(case,...
[ "def", "get_re_experiment", "(", "case", ",", "minor", "=", "1", ")", ":", "gen", "=", "case", ".", "generators", "profile", "=", "array", "(", "[", "1.0", "]", ")", "maxSteps", "=", "len", "(", "profile", ")", "experimentation", "=", "0.55", "recency"...
31.212121
21.424242
def user(self, base_dn, samaccountname, attributes=(), explicit_membership_only=False): """Produces a single, populated ADUser object through the object factory. Does not populate attributes for the caller instance. :param str base_dn: The base DN to search within :param str samaccountn...
[ "def", "user", "(", "self", ",", "base_dn", ",", "samaccountname", ",", "attributes", "=", "(", ")", ",", "explicit_membership_only", "=", "False", ")", ":", "users", "=", "self", ".", "users", "(", "base_dn", ",", "samaccountnames", "=", "[", "samaccountn...
47.681818
28.318182
def mutate(self, node, index): """Modify the numeric value on `node`.""" assert index < len(OFFSETS), 'received count with no associated offset' assert isinstance(node, parso.python.tree.Number) val = eval(node.value) + OFFSETS[index] # pylint: disable=W0123 return parso.pytho...
[ "def", "mutate", "(", "self", ",", "node", ",", "index", ")", ":", "assert", "index", "<", "len", "(", "OFFSETS", ")", ",", "'received count with no associated offset'", "assert", "isinstance", "(", "node", ",", "parso", ".", "python", ".", "tree", ".", "N...
44.75
26.125
def TypeFactory(type_): """ This function creates a standard form type from a simplified form. >>> from datetime import date, datetime >>> from pyws.functions.args import TypeFactory >>> from pyws.functions.args import String, Integer, Float, Date, DateTime >>> TypeFactory(str) == String Tr...
[ "def", "TypeFactory", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "type", ")", "and", "issubclass", "(", "type_", ",", "Type", ")", ":", "return", "type_", "for", "x", "in", "__types__", ":", "if", "x", ".", "represents", "(", "typ...
26.5
18.78
def num_lines(self): """ Lazy evaluation of the number of lines. Returns None for stdin input currently. """ if self.from_stdin: return None if not self._num_lines: self._iterate_lines() return self._num_lines
[ "def", "num_lines", "(", "self", ")", ":", "if", "self", ".", "from_stdin", ":", "return", "None", "if", "not", "self", ".", "_num_lines", ":", "self", ".", "_iterate_lines", "(", ")", "return", "self", ".", "_num_lines" ]
25.454545
11.818182
def get_arp_output_arp_entry_mac_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_arp = ET.Element("get_arp") config = get_arp output = ET.SubElement(get_arp, "output") arp_entry = ET.SubElement(output, "arp-entry") ip_...
[ "def", "get_arp_output_arp_entry_mac_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_arp", "=", "ET", ".", "Element", "(", "\"get_arp\"", ")", "config", "=", "get_arp", "output", "...
41.266667
13.066667
def Sign(self, context): """ Sign the verifiable items ( Transaction, Block, etc ) in the context with the Keypairs in this wallet. Args: context (ContractParameterContext): the context to sign. Returns: bool: if signing is successful for all contracts in this w...
[ "def", "Sign", "(", "self", ",", "context", ")", ":", "success", "=", "False", "for", "hash", "in", "context", ".", "ScriptHashes", ":", "contract", "=", "self", ".", "GetContract", "(", "hash", ")", "if", "contract", "is", "None", ":", "logger", ".", ...
30.375
28.5
def get_init_container(self, init_command, init_args, env_vars, context_mounts, persistence_outputs, persistence_data): """Pod init container for sett...
[ "def", "get_init_container", "(", "self", ",", "init_command", ",", "init_args", ",", "env_vars", ",", "context_mounts", ",", "persistence_outputs", ",", "persistence_data", ")", ":", "env_vars", "=", "to_list", "(", "env_vars", ",", "check_none", "=", "True", "...
48.166667
16.5
def query(function, api_key=None, args=None, method='GET', header_dict=None, data=None, opts=None): ''' Slack object method function to construct and execute on the API URL. :param api_key: The Slack api key. :param function: The Slack ...
[ "def", "query", "(", "function", ",", "api_key", "=", "None", ",", "args", "=", "None", ",", "method", "=", "'GET'", ",", "header_dict", "=", "None", ",", "data", "=", "None", ",", "opts", "=", "None", ")", ":", "ret", "=", "{", "'message'", ":", ...
27.8
18.84
def requires_auth(f): """ Class decorator for XML-RPC functions that requires auth """ @wraps(f) def decorated(self, *args, **kwargs): """ """ # Fetch auth options from args auth_options = {} nipap_args = {} # validate function arguments if len(...
[ "def", "requires_auth", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n \"\"\"", "# Fetch auth options from args", "auth_options", "=", "{", "}", "nipap...
34.508197
22.065574
def pos_tag(sentence, format=None): """ Vietnamese POS tagging Parameters ========== sentence: {unicode, str} Raw sentence Returns ======= tokens: list of tuple with word, pos tag tagged sentence Examples -------- >>> # -*- coding: utf-8 -*- >>> from un...
[ "def", "pos_tag", "(", "sentence", ",", "format", "=", "None", ")", ":", "sentence", "=", "word_tokenize", "(", "sentence", ")", "crf_model", "=", "CRFPOSTagPredictor", ".", "Instance", "(", ")", "result", "=", "crf_model", ".", "predict", "(", "sentence", ...
21.848485
18.636364
def get_speaker_muted(self): """Return whether or not the speaker is muted.""" if not self.camera_extended_properties: return None speaker = self.camera_extended_properties.get('speaker') if not speaker: return None return speaker.get('mute')
[ "def", "get_speaker_muted", "(", "self", ")", ":", "if", "not", "self", ".", "camera_extended_properties", ":", "return", "None", "speaker", "=", "self", ".", "camera_extended_properties", ".", "get", "(", "'speaker'", ")", "if", "not", "speaker", ":", "return...
29.9
18
def run(self): """ Runs the optimization using the previously loaded elements. """ space = self._get_space() obj_func = self._get_obj(space) model = self._get_model() acq = self._get_acquisition(model, space) acq_eval = self._get_acq_evaluator(acq) ...
[ "def", "run", "(", "self", ")", ":", "space", "=", "self", ".", "_get_space", "(", ")", "obj_func", "=", "self", ".", "_get_obj", "(", "space", ")", "model", "=", "self", ".", "_get_model", "(", ")", "acq", "=", "self", ".", "_get_acquisition", "(", ...
48.5
30.6
def purchase_ip(self, debug=False): """ Return an ip object representing a new bought IP @param debug [Boolean] if true, request and response will be printed @return (Ip): Ip object """ json_scheme = self.gen_def_json_scheme('SetPurchaseIpAddress') json_obj = self...
[ "def", "purchase_ip", "(", "self", ",", "debug", "=", "False", ")", ":", "json_scheme", "=", "self", ".", "gen_def_json_scheme", "(", "'SetPurchaseIpAddress'", ")", "json_obj", "=", "self", ".", "call_method_post", "(", "method", "=", "'SetPurchaseIpAddress'", "...
42.133333
20
def _request(self, url, method = u"get", data = None, headers=None, **kwargs): """ does the request via requests - oauth not implemented yet - use basic auth please """ # if self.access_token: # auth_header = { # u"Authoriz...
[ "def", "_request", "(", "self", ",", "url", ",", "method", "=", "u\"get\"", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# if self.access_token:", "# auth_header = {", "# u\"Authorizati...
41.32
16.76
def is_main_process(): """ Check if this is the main control process and may handle one time tasks """ try: from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() return rank == 0 except (ImportError, ValueError, RuntimeError): return True
[ "def", "is_main_process", "(", ")", ":", "try", ":", "from", "mpi4py", "import", "MPI", "comm", "=", "MPI", ".", "COMM_WORLD", "rank", "=", "comm", ".", "Get_rank", "(", ")", "return", "rank", "==", "0", "except", "(", "ImportError", ",", "ValueError", ...
29.9
12.9
def to_add(self, citiao): ''' To Add page. ''' kwd = { 'cats': MCategory.query_all(), 'slug': citiao, 'pager': '', } self.render('wiki_page/page_add.html', kwd=kwd, userinfo=self.userinfo)
[ "def", "to_add", "(", "self", ",", "citiao", ")", ":", "kwd", "=", "{", "'cats'", ":", "MCategory", ".", "query_all", "(", ")", ",", "'slug'", ":", "citiao", ",", "'pager'", ":", "''", ",", "}", "self", ".", "render", "(", "'wiki_page/page_add.html'", ...
23.153846
18.538462
def show_colormaps(names=[], N=10, show=True, use_qt=None): """Function to show standard colormaps from pyplot Parameters ---------- ``*args``: str or :class:`matplotlib.colors.Colormap` If a colormap, it returned unchanged. %(cmap_note)s N: int, optional Default: 11. The nu...
[ "def", "show_colormaps", "(", "names", "=", "[", "]", ",", "N", "=", "10", ",", "show", "=", "True", ",", "use_qt", "=", "None", ")", ":", "names", "=", "safe_list", "(", "names", ")", "if", "use_qt", "or", "(", "use_qt", "is", "None", "and", "ps...
41.448276
20.568966
def get_proxies_from_environ(): """Get proxies from os.environ.""" proxies = {} http_proxy = os.getenv('http_proxy') or os.getenv('HTTP_PROXY') https_proxy = os.getenv('https_proxy') or os.getenv('HTTPS_PROXY') if http_proxy: proxies['http'] = http_proxy if https_proxy: proxies['...
[ "def", "get_proxies_from_environ", "(", ")", ":", "proxies", "=", "{", "}", "http_proxy", "=", "os", ".", "getenv", "(", "'http_proxy'", ")", "or", "os", ".", "getenv", "(", "'HTTP_PROXY'", ")", "https_proxy", "=", "os", ".", "getenv", "(", "'https_proxy'"...
35.1
16.1
def authenticate(self, dn='', password=''): """ Attempt to authenticate given dn and password using a bind operation. Return True if the bind is successful, and return False there was an exception raised that is contained in self.failed_authentication_exceptions. """ ...
[ "def", "authenticate", "(", "self", ",", "dn", "=", "''", ",", "password", "=", "''", ")", ":", "try", ":", "self", ".", "connection", ".", "simple_bind_s", "(", "dn", ",", "password", ")", "except", "tuple", "(", "self", ".", "failed_authentication_exce...
38.153846
16.153846
def _parse_codeargs(argstr): ''' Parse and clean up argument to user code; separate *args from **kwargs. ''' args = [] kwargs = {} if isinstance(argstr, str): for a in argstr.split(): if '=' in a: k,attr = a.split('=') kwargs[k] = attr ...
[ "def", "_parse_codeargs", "(", "argstr", ")", ":", "args", "=", "[", "]", "kwargs", "=", "{", "}", "if", "isinstance", "(", "argstr", ",", "str", ")", ":", "for", "a", "in", "argstr", ".", "split", "(", ")", ":", "if", "'='", "in", "a", ":", "k...
25.1875
17.9375
def update_expression_list(self): """Extract a list of expressions from the dictionary of expressions.""" self.expression_list = [] # code arrives in dictionary, but is passed in this list self.expression_keys = [] # Keep track of the dictionary keys. self.expression_order = [] # This ma...
[ "def", "update_expression_list", "(", "self", ")", ":", "self", ".", "expression_list", "=", "[", "]", "# code arrives in dictionary, but is passed in this list", "self", ".", "expression_keys", "=", "[", "]", "# Keep track of the dictionary keys.", "self", ".", "expressi...
69.586207
33.068966
def inc(self, key, key_length=0): """Increment key-value Params: <str> key <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) return _madoka.Sketch_inc(self, key, key_length)
[ "def", "inc", "(", "self", ",", "key", ",", "key_length", "=", "0", ")", ":", "if", "key_length", "<", "1", ":", "key_length", "=", "len", "(", "key", ")", "return", "_madoka", ".", "Sketch_inc", "(", "self", ",", "key", ",", "key_length", ")" ]
26.818182
12.545455
def check_method_requirements(func): """Check methods requirements :param callable func: the function to decorate :return callable: the wrapped function """ @wraps(func) def wrapper(*args, **kwargs): error_message = "You must provide {error_field} in {cls} to get access to the default {...
[ "def", "check_method_requirements", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "error_message", "=", "\"You must provide {error_field} in {cls} to get access to the default {method} met...
38.333333
20.888889
def create_object(container, portal_type, **data): """Creates an object slug :returns: The new created content object :rtype: object """ if "id" in data: # always omit the id as senaite LIMS generates a proper one id = data.pop("id") logger.warn("Passed in ID '{}' omitted! ...
[ "def", "create_object", "(", "container", ",", "portal_type", ",", "*", "*", "data", ")", ":", "if", "\"id\"", "in", "data", ":", "# always omit the id as senaite LIMS generates a proper one", "id", "=", "data", ".", "pop", "(", "\"id\"", ")", "logger", ".", "...
34.463415
20.170732
def CacheFileSystem(self, path_spec, file_system): """Caches a file system object based on a path specification. Args: path_spec (PathSpec): path specification. file_system (FileSystem): file system object. """ identifier = self._GetFileSystemCacheIdentifier(path_spec) self._file_system...
[ "def", "CacheFileSystem", "(", "self", ",", "path_spec", ",", "file_system", ")", ":", "identifier", "=", "self", ".", "_GetFileSystemCacheIdentifier", "(", "path_spec", ")", "self", ".", "_file_system_cache", ".", "CacheObject", "(", "identifier", ",", "file_syst...
39.444444
16.111111
def kernels_status(self, kernel): """ call to the api to get the status of a kernel. Parameters ========== kernel: the kernel to get the status for """ if kernel is None: raise ValueError('A kernel must be specified') if '/' in kernel: ...
[ "def", "kernels_status", "(", "self", ",", "kernel", ")", ":", "if", "kernel", "is", "None", ":", "raise", "ValueError", "(", "'A kernel must be specified'", ")", "if", "'/'", "in", "kernel", ":", "self", ".", "validate_kernel_string", "(", "kernel", ")", "k...
38.842105
12.368421
def patched_get_current(self, request=None): """ Monkey patched version of Django's SiteManager.get_current() function. Returns the current Site based on a given request or the SITE_ID in the project's settings. If a request is given attempts to match a site with domain matching request.get_host()....
[ "def", "patched_get_current", "(", "self", ",", "request", "=", "None", ")", ":", "# Imported here to avoid circular import", "from", "django", ".", "conf", "import", "settings", "if", "request", ":", "try", ":", "return", "self", ".", "_get_site_by_request", "(",...
42.111111
23.222222
def dump_info(self, dump=None): """Dump all the PE header information into human readable string.""" if dump is None: dump = Dump() warnings = self.get_warnings() if warnings: dump.add_header('Parsing Warnings') for warning i...
[ "def", "dump_info", "(", "self", ",", "dump", "=", "None", ")", ":", "if", "dump", "is", "None", ":", "dump", "=", "Dump", "(", ")", "warnings", "=", "self", ".", "get_warnings", "(", ")", "if", "warnings", ":", "dump", ".", "add_header", "(", "'Pa...
42.390728
19.933775
def initialize_wind_turbine_cluster(example_farm, example_farm_2): r""" Initializes a :class:`~.wind_turbine_cluster.WindTurbineCluster` object. Function shows how to initialize a WindTurbineCluster object. In this case the cluster only contains two wind farms. Parameters ---------- exampl...
[ "def", "initialize_wind_turbine_cluster", "(", "example_farm", ",", "example_farm_2", ")", ":", "# specification of cluster data", "example_cluster_data", "=", "{", "'name'", ":", "'example_cluster'", ",", "'wind_farms'", ":", "[", "example_farm", ",", "example_farm_2", "...
27.034483
22.724138
def validate_parsed_json(obj_json, options=None): """ Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance ...
[ "def", "validate_parsed_json", "(", "obj_json", ",", "options", "=", "None", ")", ":", "validating_list", "=", "isinstance", "(", "obj_json", ",", "list", ")", "if", "not", "options", ":", "options", "=", "ValidationOptions", "(", ")", "if", "not", "options"...
36.065217
21.586957
def build_collection(df, **kwargs): ''' Generates a list of Record objects given a DataFrame. Each Record instance has a series attribute which is a pandas.Series of the same attributes in the DataFrame. Optional data can be passed in through kwargs which will be included by the name of each object...
[ "def", "build_collection", "(", "df", ",", "*", "*", "kwargs", ")", ":", "print", "'Generating the Record Collection...\\n'", "df", "[", "'index_original'", "]", "=", "df", ".", "index", "df", ".", "reset_index", "(", "drop", "=", "True", ",", "inplace", "="...
34.086957
24.586957
def list_listeners(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_listeners for a project.""" return self.list('listeners', self.lbaas_listeners_path, retrieve_all, **_params)
[ "def", "list_listeners", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "list", "(", "'listeners'", ",", "self", ".", "lbaas_listeners_path", ",", "retrieve_all", ",", "*", "*", "_params", ")" ]
58.5
12
def sleep(seconds=0): """Yield control to another eligible coroutine until at least *seconds* have elapsed. *seconds* may be specified as an integer, or a float if fractional seconds are desired. """ loop = evergreen.current.loop current = Fiber.current() assert loop.task is not current...
[ "def", "sleep", "(", "seconds", "=", "0", ")", ":", "loop", "=", "evergreen", ".", "current", ".", "loop", "current", "=", "Fiber", ".", "current", "(", ")", "assert", "loop", ".", "task", "is", "not", "current", "timer", "=", "loop", ".", "call_late...
28.4
18.733333
def kld(d1, d2): """Return the Kullback-Leibler Divergence (KLD) between two distributions. Args: d1 (np.ndarray): The first distribution. d2 (np.ndarray): The second distribution. Returns: float: The KLD of ``d1`` from ``d2``. """ d1, d2 = flatten(d1), flatten(d2) retu...
[ "def", "kld", "(", "d1", ",", "d2", ")", ":", "d1", ",", "d2", "=", "flatten", "(", "d1", ")", ",", "flatten", "(", "d2", ")", "return", "entropy", "(", "d1", ",", "d2", ",", "2.0", ")" ]
27.666667
16.416667
def encode(self): """ Just iterate over the child elements and append them to the current element :return: the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element( self.name, attrib={'type': FieldConstants.ARRAY...
[ "def", "encode", "(", "self", ")", ":", "element", "=", "ElementTree", ".", "Element", "(", "self", ".", "name", ",", "attrib", "=", "{", "'type'", ":", "FieldConstants", ".", "ARRAY", "}", ",", ")", "for", "item", "in", "self", ".", "value", ":", ...
29.714286
14.571429
def set_to_tuple(tokens): """Converts set literal tokens to tuples.""" internal_assert(len(tokens) == 1, "invalid set maker tokens", tokens) if "comp" in tokens or "list" in tokens: return "(" + tokens[0] + ")" elif "test" in tokens: return "(" + tokens[0] + ",)" else: raise ...
[ "def", "set_to_tuple", "(", "tokens", ")", ":", "internal_assert", "(", "len", "(", "tokens", ")", "==", "1", ",", "\"invalid set maker tokens\"", ",", "tokens", ")", "if", "\"comp\"", "in", "tokens", "or", "\"list\"", "in", "tokens", ":", "return", "\"(\"",...
41.444444
15.444444
def get_default_config(self): """ Returns the default collector settings """ config = super(ExampleCollector, self).get_default_config() config.update({ 'path': 'example' }) return config
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "ExampleCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'example'", "}", ")", "return", "config" ]
27.888889
13
def discrete(cats, name='discrete'): """Return a class category that shows the encoding""" import json ks = list(cats) for key in ks: if isinstance(key, bytes): cats[key.decode('utf-8')] = cats.pop(key) return 'discrete(' + json.dumps([cats, name]) + ')'
[ "def", "discrete", "(", "cats", ",", "name", "=", "'discrete'", ")", ":", "import", "json", "ks", "=", "list", "(", "cats", ")", "for", "key", "in", "ks", ":", "if", "isinstance", "(", "key", ",", "bytes", ")", ":", "cats", "[", "key", ".", "deco...
35.875
13.25
def get_mesh(oqparam): """ Extract the mesh of points to compute from the sites, the sites_csv, or the region. :param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance """ global pmap, exposure, gmfs, eids if 'exposure' in oqparam.inputs and exposure is None: ...
[ "def", "get_mesh", "(", "oqparam", ")", ":", "global", "pmap", ",", "exposure", ",", "gmfs", ",", "eids", "if", "'exposure'", "in", "oqparam", ".", "inputs", "and", "exposure", "is", "None", ":", "# read it only once", "exposure", "=", "get_exposure", "(", ...
42.913043
15
def isometric_view_interactive(self): """ sets the current interactive render window to isometric view """ interactor = self.iren.GetInteractorStyle() renderer = interactor.GetCurrentRenderer() renderer.view_isometric()
[ "def", "isometric_view_interactive", "(", "self", ")", ":", "interactor", "=", "self", ".", "iren", ".", "GetInteractorStyle", "(", ")", "renderer", "=", "interactor", ".", "GetCurrentRenderer", "(", ")", "renderer", ".", "view_isometric", "(", ")" ]
49.4
6.2
def set_parent(self, parent): """Set parent ``Expression`` for this object. Args: parent (Expression): The ``Expression`` which contains this object. Raises: FiqlObjectException: Parent must be of type ``Expression``. """ if not isinstance(parent, Expres...
[ "def", "set_parent", "(", "self", ",", "parent", ")", ":", "if", "not", "isinstance", "(", "parent", ",", "Expression", ")", ":", "raise", "FiqlObjectException", "(", "\"Parent must be of %s not %s\"", "%", "(", "Expression", ",", "type", "(", "parent", ")", ...
35.230769
20.307692
def get_preflist(self, bucket, key): """ Get the preflist for a bucket/key :param bucket: Riak Bucket :type bucket: :class:`~riak.bucket.RiakBucket` :param key: Riak Key :type key: string :rtype: list of dicts """ if not self.preflists(): ...
[ "def", "get_preflist", "(", "self", ",", "bucket", ",", "key", ")", ":", "if", "not", "self", ".", "preflists", "(", ")", ":", "raise", "NotImplementedError", "(", "\"fetching preflists is not supported.\"", ")", "bucket_type", "=", "self", ".", "_get_bucket_typ...
36.571429
16.380952
def run(self): """ Ping entries to a directory in a thread. """ logger = getLogger('zinnia.ping.directory') socket.setdefaulttimeout(self.timeout) for entry in self.entries: reply = self.ping_entry(entry) self.results.append(reply) logg...
[ "def", "run", "(", "self", ")", ":", "logger", "=", "getLogger", "(", "'zinnia.ping.directory'", ")", "socket", ".", "setdefaulttimeout", "(", "self", ".", "timeout", ")", "for", "entry", "in", "self", ".", "entries", ":", "reply", "=", "self", ".", "pin...
36.636364
8.454545
def ancestor(self, value): """Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key """ if not isinstance(value, Key): raise TypeError("Ancestor must be a Key") self._ancestor = value
[ "def", "ancestor", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Key", ")", ":", "raise", "TypeError", "(", "\"Ancestor must be a Key\"", ")", "self", ".", "_ancestor", "=", "value" ]
33.555556
11.333333
def write(version): # type: (str) -> None """ Write the given version to the VERSION_FILE """ if not is_valid(version): raise ValueError("Invalid version: ".format(version)) storage = get_version_storage() storage.write(version)
[ "def", "write", "(", "version", ")", ":", "# type: (str) -> None", "if", "not", "is_valid", "(", "version", ")", ":", "raise", "ValueError", "(", "\"Invalid version: \"", ".", "format", "(", "version", ")", ")", "storage", "=", "get_version_storage", "(", ")",...
31.25
15.875
def ensure_stopped(self): """Idempotent channel stop""" if not self.active: return self self.stop() self.observer.cancel() self._manager.remove_routes(self, self.get_routing_keys()) self._active = False return self
[ "def", "ensure_stopped", "(", "self", ")", ":", "if", "not", "self", ".", "active", ":", "return", "self", "self", ".", "stop", "(", ")", "self", ".", "observer", ".", "cancel", "(", ")", "self", ".", "_manager", ".", "remove_routes", "(", "self", ",...
30.444444
15
def paintEvent(self, event): """Fills the panel background using QPalette.""" if self.isVisible() and self.position != self.Position.FLOATING: # fill background self._background_brush = QBrush(QColor( self.editor.sideareas_color)) self._foreground_pen ...
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "isVisible", "(", ")", "and", "self", ".", "position", "!=", "self", ".", "Position", ".", "FLOATING", ":", "# fill background", "self", ".", "_background_brush", "=", "QBrush", ...
48.3
12.1
def _write_multiplicons(self, filename): """ Write multiplicons to file. - filename, (str) location of output file """ # Column headers mhead = '\t'.join(['id', 'genome_x', 'list_x', 'parent', 'genome_y', 'list_y', 'level', 'number_of_anchorpoints'...
[ "def", "_write_multiplicons", "(", "self", ",", "filename", ")", ":", "# Column headers", "mhead", "=", "'\\t'", ".", "join", "(", "[", "'id'", ",", "'genome_x'", ",", "'list_x'", ",", "'parent'", ",", "'genome_y'", ",", "'list_y'", ",", "'level'", ",", "'...
45.5
15.785714
def _finalize(self): """ command to run at the end of sprinter's run """ self.logger.info("Finalizing...") self.write_manifest() if self.directory.rewrite_config: # always ensure .rc is written (sourcing .env) self.directory.add_to_rc('') # prepend br...
[ "def", "_finalize", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Finalizing...\"", ")", "self", ".", "write_manifest", "(", ")", "if", "self", ".", "directory", ".", "rewrite_config", ":", "# always ensure .rc is written (sourcing .env)", "...
46.8
26.028571
def get_names(list_of_taxids): """ >>> mylist = [3702, 3649, 3694, 3880] >>> get_names(mylist) ['Arabidopsis thaliana', 'Carica papaya', 'Populus trichocarpa', 'Medicago truncatula'] """ from jcvi.apps.fetch import batch_taxonomy list_of_taxids = [str(x) for x in list_of_taxids] return l...
[ "def", "get_names", "(", "list_of_taxids", ")", ":", "from", "jcvi", ".", "apps", ".", "fetch", "import", "batch_taxonomy", "list_of_taxids", "=", "[", "str", "(", "x", ")", "for", "x", "in", "list_of_taxids", "]", "return", "list", "(", "batch_taxonomy", ...
38.555556
11.444444
def new_utterance(self, utterance_idx, track_idx, issuer_idx=None, start=0, end=float('inf')): """ Add a new utterance to the corpus with the given data. Parameters: track_idx (str): The track id the utterance is in. utterance_idx (str): The id to associate with the utte...
[ "def", "new_utterance", "(", "self", ",", "utterance_idx", ",", "track_idx", ",", "issuer_idx", "=", "None", ",", "start", "=", "0", ",", "end", "=", "float", "(", "'inf'", ")", ")", ":", "new_utt_idx", "=", "utterance_idx", "# Check if there is a track with t...
39.466667
24.044444
def register_directory(self, directory, parent, ensure_uniqueness=False): """ Registers given directory in the Model. :param directory: Directory to register. :type directory: unicode :param parent: DirectoryNode parent. :type parent: GraphModelNode :param ensure...
[ "def", "register_directory", "(", "self", ",", "directory", ",", "parent", ",", "ensure_uniqueness", "=", "False", ")", ":", "if", "ensure_uniqueness", ":", "if", "self", ".", "get_directory_nodes", "(", "directory", ")", ":", "raise", "foundations", ".", "exc...
38.032258
20.032258
def update_external_store(self, project_name, config): """ update the logstore meta info Unsuccessful opertaion will cause an LogException. :type config: ExternalStoreConfig :param config : external store config :return: UpdateExternalStoreResponse ...
[ "def", "update_external_store", "(", "self", ",", "project_name", ",", "config", ")", ":", "headers", "=", "{", "\"x-log-bodyrawsize\"", ":", "'0'", ",", "\"Content-Type\"", ":", "\"application/json\"", "}", "params", "=", "{", "}", "resource", "=", "\"/external...
38
19.947368
def extract_boto_args_from_env(env_vars): """Return boto3 client args dict with environment creds.""" boto_args = {} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if env_vars.get(i.upper()): boto_args[i] = env_vars[i.upper()] return boto_...
[ "def", "extract_boto_args_from_env", "(", "env_vars", ")", ":", "boto_args", "=", "{", "}", "for", "i", "in", "[", "'aws_access_key_id'", ",", "'aws_secret_access_key'", ",", "'aws_session_token'", "]", ":", "if", "env_vars", ".", "get", "(", "i", ".", "upper"...
39.625
9.75
def flush(self): """ Flush message queue if there's an active connection running """ self._pending_flush = False if self.handler is None: return if self.send_queue.is_empty(): return self.handler.send_pack('a[%s]' % self.send_queue.get()) self.s...
[ "def", "flush", "(", "self", ")", ":", "self", ".", "_pending_flush", "=", "False", "if", "self", ".", "handler", "is", "None", ":", "return", "if", "self", ".", "send_queue", ".", "is_empty", "(", ")", ":", "return", "self", ".", "handler", ".", "se...
27.166667
19.583333
def _gate_height(self, gate): """ Return the height to use for this gate. :param string gate: The name of the gate whose height is desired. :return: Height of the gate. :rtype: float """ try: height = self.settings['gates'][gate.__class__.__name__]['h...
[ "def", "_gate_height", "(", "self", ",", "gate", ")", ":", "try", ":", "height", "=", "self", ".", "settings", "[", "'gates'", "]", "[", "gate", ".", "__class__", ".", "__name__", "]", "[", "'height'", "]", "except", "KeyError", ":", "height", "=", "...
29.692308
17.846154
def plot_max_median_position_concentration(positions, ax=None, **kwargs): """ Plots the max and median of long and short position concentrations over the time. Parameters ---------- positions : pd.DataFrame The positions that the strategy takes over time. ax : matplotlib.Axes, optio...
[ "def", "plot_max_median_position_concentration", "(", "positions", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "alloc_summary", "=", "pos", ".", "get_max_median_position_...
28.366667
23.5
def recv(self, timeout=None): """Overwrite standard recv for timeout calls to catch interrupt errors. """ if timeout: try: testsock = self._zmq.select([self.socket], [], [], timeout)[0] except zmq.ZMQError as e: if e.errno == errno.EINTR: ...
[ "def", "recv", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", ":", "try", ":", "testsock", "=", "self", ".", "_zmq", ".", "select", "(", "[", "self", ".", "socket", "]", ",", "[", "]", ",", "[", "]", ",", "timeout", ")", ...
36.882353
14.529412
def invite(self, address, text=None, *, mode=InviteMode.DIRECT, allow_upgrade=False): """ Invite another entity to the conversation. :param address: The address of the entity to invite. :type address: :class:`aioxmpp.JID` :param text: A reason/accom...
[ "def", "invite", "(", "self", ",", "address", ",", "text", "=", "None", ",", "*", ",", "mode", "=", "InviteMode", ".", "DIRECT", ",", "allow_upgrade", "=", "False", ")", ":", "raise", "self", ".", "_not_implemented_error", "(", "\"inviting entities\"", ")"...
44.523077
23.938462
def _handle_tag_jpegtables(self): """Handle the JPEGTables tag.""" obj = _make_object("JPEGTables") assert self._src.read(2) == b'\xFF\xD8' # SOI marker eoimark1 = eoimark2 = None allbytes = [b'\xFF\xD8'] while not (eoimark1 == b'\xFF' and eoimark2 == b'\xD9'): ...
[ "def", "_handle_tag_jpegtables", "(", "self", ")", ":", "obj", "=", "_make_object", "(", "\"JPEGTables\"", ")", "assert", "self", ".", "_src", ".", "read", "(", "2", ")", "==", "b'\\xFF\\xD8'", "# SOI marker", "eoimark1", "=", "eoimark2", "=", "None", "allby...
37.266667
11.533333
def _kpost(url, data): ''' create any object in kubernetes based on URL ''' # Prepare headers headers = {"Content-Type": "application/json"} # Make request log.trace("url is: %s, data is: %s", url, data) ret = http.query(url, method='POST', header_dict=...
[ "def", "_kpost", "(", "url", ",", "data", ")", ":", "# Prepare headers", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", "}", "# Make request", "log", ".", "trace", "(", "\"url is: %s, data is: %s\"", ",", "url", ",", "data", ")", "ret", ...
31.5
16.625
def add_vertex(self, v): """ Add a vertex to the graph :param v: The vertex name. """ self.graph.add_vertex(v) self.vs.add(v)
[ "def", "add_vertex", "(", "self", ",", "v", ")", ":", "self", ".", "graph", ".", "add_vertex", "(", "v", ")", "self", ".", "vs", ".", "add", "(", "v", ")" ]
22.857143
12.571429
def delete_collection_storage_class(self, **kwargs): # noqa: E501 """delete_collection_storage_class # noqa: E501 delete collection of StorageClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
[ "def", "delete_collection_storage_class", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "delete_coll...
163.655172
135.275862
def switch(condition, then_expression, else_expression): """Switches between two operations depending on a scalar value (int or bool). Note that both `then_expression` and `else_expression` should be symbolic tensors of the *same shape*. # Arguments condition: scalar tensor. then_expres...
[ "def", "switch", "(", "condition", ",", "then_expression", ",", "else_expression", ")", ":", "x_shape", "=", "copy", ".", "copy", "(", "then_expression", ".", "get_shape", "(", ")", ")", "x", "=", "tf", ".", "cond", "(", "tf", ".", "cast", "(", "condit...
37.75
11.75
def _default_headers(self): """Set the default header for a Twilio SendGrid v3 API call""" headers = { "Authorization": 'Bearer {}'.format(self.api_key), "User-agent": self.useragent, "Accept": 'application/json' } if self.impersonate_subuser: ...
[ "def", "_default_headers", "(", "self", ")", ":", "headers", "=", "{", "\"Authorization\"", ":", "'Bearer {}'", ".", "format", "(", "self", ".", "api_key", ")", ",", "\"User-agent\"", ":", "self", ".", "useragent", ",", "\"Accept\"", ":", "'application/json'",...
36.181818
15.545455