text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _print_dict_files(self, case, target): """Prints the file names and available properties in the specified test case's 'target' dictionary. :arg case: the identifier of the test case to print contents for. :arg target: one of ['inputs', 'outputs', 'percent'] """ ...
[ "def", "_print_dict_files", "(", "self", ",", "case", ",", "target", ")", ":", "if", "case", "in", "self", ".", "live", "and", "target", "in", "self", ".", "live", "[", "case", "]", ":", "lines", "=", "[", "]", "data", "=", "self", ".", "live", "...
44.058824
15.941176
def cursor_position_col(self): """ Current column. (0-based.) """ # (Don't use self.text_before_cursor to calculate this. Creating # substrings and doing rsplit is too expensive for getting the cursor # position.) _, line_start_index = self._find_line_start_index(...
[ "def", "cursor_position_col", "(", "self", ")", ":", "# (Don't use self.text_before_cursor to calculate this. Creating", "# substrings and doing rsplit is too expensive for getting the cursor", "# position.)", "_", ",", "line_start_index", "=", "self", ".", "_find_line_start_index", ...
43.111111
17.555556
def _get_parser(f): """ Gets the parser for the command f, if it not exists it creates a new one """ _COMMAND_GROUPS[f.__module__].load() if f.__name__ not in _COMMAND_GROUPS[f.__module__].parsers: parser = _COMMAND_GROUPS[f.__module__].parser_generator.add_parser(f.__name__, help=f.__doc__...
[ "def", "_get_parser", "(", "f", ")", ":", "_COMMAND_GROUPS", "[", "f", ".", "__module__", "]", ".", "load", "(", ")", "if", "f", ".", "__name__", "not", "in", "_COMMAND_GROUPS", "[", "f", ".", "__module__", "]", ".", "parsers", ":", "parser", "=", "_...
40.857143
26.428571
def day_fraction(time): """Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python ...
[ "def", "day_fraction", "(", "time", ")", ":", "hour", "=", "int", "(", "time", ".", "split", "(", "\":\"", ")", "[", "0", "]", ")", "minute", "=", "int", "(", "time", ".", "split", "(", "\":\"", ")", "[", "1", "]", ")", "return", "hour", "/", ...
22.05
21.05
def update_key_bundle(key_bundle, diff): """ Apply a diff specification to a KeyBundle. The keys that are to be added are added. The keys that should be deleted are marked as inactive. :param key_bundle: The original KeyBundle :param diff: The difference specification :return: An updated ke...
[ "def", "update_key_bundle", "(", "key_bundle", ",", "diff", ")", ":", "try", ":", "_add", "=", "diff", "[", "'add'", "]", "except", "KeyError", ":", "pass", "else", ":", "key_bundle", ".", "extend", "(", "_add", ")", "try", ":", "_del", "=", "diff", ...
23.64
16.84
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ """ POST request """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) msg = "" error = False data = web.input() if not data.get("token", "") == self.user_manager.session_tok...
[ "def", "POST_AUTH", "(", "self", ",", "courseid", ")", ":", "# pylint: disable=arguments-differ", "course", ",", "__", "=", "self", ".", "get_course_and_check_rights", "(", "courseid", ",", "allow_all_staff", "=", "False", ")", "msg", "=", "\"\"", "error", "=", ...
40.617021
20.361702
def wif(self, s): """ Parse a WIF. Return a :class:`Key <pycoin.key.Key>` or None. """ data = self.parse_b58_hashed(s) if data is None or not data.startswith(self._wif_prefix): return None data = data[len(self._wif_prefix):] is_compressed = (le...
[ "def", "wif", "(", "self", ",", "s", ")", ":", "data", "=", "self", ".", "parse_b58_hashed", "(", "s", ")", "if", "data", "is", "None", "or", "not", "data", ".", "startswith", "(", "self", ".", "_wif_prefix", ")", ":", "return", "None", "data", "="...
34.5
12.357143
def fpkm(args): """ %prog fpkm fastafile *.bam Calculate FPKM values from BAM file. """ p = OptionParser(fpkm.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) fastafile = args[0] bamfiles = args[1:] # Create a DUMMY gff file for c...
[ "def", "fpkm", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "fpkm", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "<", "2", ":", "sys", ".", "exit", "(", "not", ...
29.851852
16.518519
def matrix_diag_transform(matrix, transform=None, name=None): """Transform diagonal of [batch-]matrix, leave rest of matrix unchanged. Create a trainable covariance defined by a Cholesky factor: ```python # Transform network layer into 2 x 2 array. matrix_values = tf.contrib.layers.fully_connected(activatio...
[ "def", "matrix_diag_transform", "(", "matrix", ",", "transform", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", "or", "\"matrix_diag_transform\"", ")", ":", "matrix", "=", "tf", ".", "convert_to_tensor", "(", ...
35.733333
23.983333
def export_losses_by_asset(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ loss_dt = dstore['oqparam'].loss_dt(stat_dt) losses_by_asset = dstore[ekey[0]].value rlzs = dstore['csm_info'].get_rlzs_assoc().realizations assets ...
[ "def", "export_losses_by_asset", "(", "ekey", ",", "dstore", ")", ":", "loss_dt", "=", "dstore", "[", "'oqparam'", "]", ".", "loss_dt", "(", "stat_dt", ")", "losses_by_asset", "=", "dstore", "[", "ekey", "[", "0", "]", "]", ".", "value", "rlzs", "=", "...
40.5625
11.5625
def associate_hosting_device_with_config_agent( self, client, config_agent_id, body): """Associates a hosting_device with a config agent.""" return client.post((ConfigAgentHandlingHostingDevice.resource_path + CFG_AGENT_HOSTING_DEVICES) % config_agent_id, ...
[ "def", "associate_hosting_device_with_config_agent", "(", "self", ",", "client", ",", "config_agent_id", ",", "body", ")", ":", "return", "client", ".", "post", "(", "(", "ConfigAgentHandlingHostingDevice", ".", "resource_path", "+", "CFG_AGENT_HOSTING_DEVICES", ")", ...
57.333333
14.666667
async def restrict(self, user_id: base.Integer, until_date: typing.Union[base.Integer, None] = None, can_send_messages: typing.Union[base.Boolean, None] = None, can_send_media_messages: typing.Union[base.Boolean, None] = None, c...
[ "async", "def", "restrict", "(", "self", ",", "user_id", ":", "base", ".", "Integer", ",", "until_date", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "None", "]", "=", "None", ",", "can_send_messages", ":", "typing", ".", "Union", "["...
71.083333
37.416667
def data_from_stream(self, stream): """ Creates a data element reading a representation from the given stream. :returns: object implementing :class:`everest.representers.interfaces.IExplicitDataElement` """ parser = self._make_representation_parser(stream, self.resou...
[ "def", "data_from_stream", "(", "self", ",", "stream", ")", ":", "parser", "=", "self", ".", "_make_representation_parser", "(", "stream", ",", "self", ".", "resource_class", ",", "self", ".", "_mapping", ")", "return", "parser", ".", "run", "(", ")" ]
41.4
19.4
def put_device(self, pin, state, momentary=None, times=None, pause=None): """ Actuate a device pin """ url = self.base_url + '/device' payload = { "pin": pin, "state": state } if momentary is not None: payload["momentary"] = momentary ...
[ "def", "put_device", "(", "self", ",", "pin", ",", "state", ",", "momentary", "=", "None", ",", "times", "=", "None", ",", "pause", "=", "None", ")", ":", "url", "=", "self", ".", "base_url", "+", "'/device'", "payload", "=", "{", "\"pin\"", ":", "...
26.521739
18.26087
def update(self, new_email_address, name): """Updates the details for an administrator.""" params = {"email": self.email_address} body = { "EmailAddress": new_email_address, "Name": name} response = self._put("/admins.json", body=json....
[ "def", "update", "(", "self", ",", "new_email_address", ",", "name", ")", ":", "params", "=", "{", "\"email\"", ":", "self", ".", "email_address", "}", "body", "=", "{", "\"EmailAddress\"", ":", "new_email_address", ",", "\"Name\"", ":", "name", "}", "resp...
43.545455
13.272727
def get_status(self): ''' Gets a summary of what passed/failed for the push ''' jobs = Job.objects.filter(push=self).filter( Q(failure_classification__isnull=True) | Q(failure_classification__name='not classified')).exclude(tier=3) status_dict = {} ...
[ "def", "get_status", "(", "self", ")", ":", "jobs", "=", "Job", ".", "objects", ".", "filter", "(", "push", "=", "self", ")", ".", "filter", "(", "Q", "(", "failure_classification__isnull", "=", "True", ")", "|", "Q", "(", "failure_classification__name", ...
36.571429
17.047619
def pitch_contour(annotation, sr=22050, length=None, **kwargs): '''Sonify pitch contours. This uses mir_eval.sonify.pitch_contour, and should only be applied to pitch annotations using the pitch_contour namespace. Each contour is sonified independently, and the resulting waveforms are summed toget...
[ "def", "pitch_contour", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Map contours to lists of observations", "times", "=", "defaultdict", "(", "list", ")", "freqs", "=", "defaultdict", "(", "li...
33.483871
23.677419
def update_model(self, tfi): """Update the model for the given tfi :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None """ if tfi.task.department.assetflag: browser = self.assetbrws else...
[ "def", "update_model", "(", "self", ",", "tfi", ")", ":", "if", "tfi", ".", "task", ".", "department", ".", "assetflag", ":", "browser", "=", "self", ".", "assetbrws", "else", ":", "browser", "=", "self", ".", "shotbrws", "if", "tfi", ".", "version", ...
32.6
13
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ expr = str(self.resolve_option("expression")) expr = expr.replace("{X}", str(self.input.payload)) self._output.append(Token(e...
[ "def", "do_execute", "(", "self", ")", ":", "expr", "=", "str", "(", "self", ".", "resolve_option", "(", "\"expression\"", ")", ")", "expr", "=", "expr", ".", "replace", "(", "\"{X}\"", ",", "str", "(", "self", ".", "input", ".", "payload", ")", ")",...
31
14.636364
def return_action(self, return_action): """Sets the return_action of this ReturnSettings. :param return_action: The return_action of this ReturnSettings. :type: str """ allowed_values = ["refund", "storeCredit"] # noqa: E501 if return_action is not None and return_acti...
[ "def", "return_action", "(", "self", ",", "return_action", ")", ":", "allowed_values", "=", "[", "\"refund\"", ",", "\"storeCredit\"", "]", "# noqa: E501", "if", "return_action", "is", "not", "None", "and", "return_action", "not", "in", "allowed_values", ":", "r...
37.8
22.733333
def get_counter(self, key, **kwargs): """ Gets the value of a counter stored in this bucket. See :meth:`RiakClient.get_counter() <riak.client.RiakClient.get_counter>` for options. .. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are deprecated in favor of the ...
[ "def", "get_counter", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", ".", "get_counter", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")" ]
34.8
17.333333
def only(self, *fields): ''' Restricts the fields to be fetched when mapping. Set to `__model` to fetch all fields define in the ModelIndex. ''' s = self._clone() if len(fields) == 1 and fields[0] == '__model': s._only = '__model' else: s._only = f...
[ "def", "only", "(", "self", ",", "*", "fields", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "if", "len", "(", "fields", ")", "==", "1", "and", "fields", "[", "0", "]", "==", "'__model'", ":", "s", ".", "_only", "=", "'__model'", "else"...
33.3
25.5
def _get_lb(self, lb_or_id): """ Accepts either a loadbalancer or the ID of a loadbalancer, and returns the CloudLoadBalancer instance. """ if isinstance(lb_or_id, CloudLoadBalancer): ret = lb_or_id else: ret = self.get(lb_or_id) return ret
[ "def", "_get_lb", "(", "self", ",", "lb_or_id", ")", ":", "if", "isinstance", "(", "lb_or_id", ",", "CloudLoadBalancer", ")", ":", "ret", "=", "lb_or_id", "else", ":", "ret", "=", "self", ".", "get", "(", "lb_or_id", ")", "return", "ret" ]
31.1
12.9
def get_person(people_id): ''' Return a single person ''' result = _get(people_id, settings.PEOPLE) return People(result.content)
[ "def", "get_person", "(", "people_id", ")", ":", "result", "=", "_get", "(", "people_id", ",", "settings", ".", "PEOPLE", ")", "return", "People", "(", "result", ".", "content", ")" ]
34.5
8
def dataset_create_new(self, folder, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ create a new dataset, meaning the same as creating a version but ...
[ "def", "dataset_create_new", "(", "self", ",", "folder", ",", "public", "=", "False", ",", "quiet", "=", "False", ",", "convert_to_csv", "=", "True", ",", "dir_mode", "=", "'skip'", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder",...
40.683544
16.56962
def append(self, key, item): """Append item to the list at key. Creates the list at key if it doesn't exist. """ with self._lock: if key in self._dict: self._dict[key].append(item) else: self._dict[key] = [item]
[ "def", "append", "(", "self", ",", "key", ",", "item", ")", ":", "with", "self", ".", "_lock", ":", "if", "key", "in", "self", ".", "_dict", ":", "self", ".", "_dict", "[", "key", "]", ".", "append", "(", "item", ")", "else", ":", "self", ".", ...
32.333333
8.888889
def add_tag_to_derived_metric(self, id, tag_value, **kwargs): # noqa: E501 """Add a tag to a specific Derived Metric # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread...
[ "def", "add_tag_to_derived_metric", "(", "self", ",", "id", ",", "tag_value", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", ...
44.681818
21.136364
def add_labels_to_subsets(ax, subset_by, subset_order, text_kwargs=None, add_hlines=True, hline_kwargs=None): """ Helper function for adding labels to subsets within a heatmap. Assumes that imshow() was called with `subsets` and `subset_order`. Parameters ---------- a...
[ "def", "add_labels_to_subsets", "(", "ax", ",", "subset_by", ",", "subset_order", ",", "text_kwargs", "=", "None", ",", "add_hlines", "=", "True", ",", "hline_kwargs", "=", "None", ")", ":", "_text_kwargs", "=", "dict", "(", "transform", "=", "ax", ".", "g...
32.189189
20.837838
def _get_gce_credentials(request=None): """Gets credentials and project ID from the GCE Metadata Service.""" # Ping requires a transport, but we want application default credentials # to require no arguments. So, we'll use the _http_client transport which # uses http.client. This is only acceptable beca...
[ "def", "_get_gce_credentials", "(", "request", "=", "None", ")", ":", "# Ping requires a transport, but we want application default credentials", "# to require no arguments. So, we'll use the _http_client transport which", "# uses http.client. This is only acceptable because the metadata server"...
38.571429
21.642857
def angle2vecs(vec1, vec2): """angle between two vectors""" # vector a * vector b = |a|*|b|* cos(angle between vector a and vector b) dot = np.dot(vec1, vec2) vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum()) vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum()) if (vec1_modulus * vec2_modul...
[ "def", "angle2vecs", "(", "vec1", ",", "vec2", ")", ":", "# vector a * vector b = |a|*|b|* cos(angle between vector a and vector b)", "dot", "=", "np", ".", "dot", "(", "vec1", ",", "vec2", ")", "vec1_modulus", "=", "np", ".", "sqrt", "(", "np", ".", "multiply",...
44.1
13.4
def from_payload(type_code, payload, connection): """Generator function to create lob from payload. Depending on lob type a BLOB, CLOB, or NCLOB instance will be returned. This function is usually called from types.*LobType.from_resultset() """ lob_header = ReadLobHeader(payload) if lob_header.i...
[ "def", "from_payload", "(", "type_code", ",", "payload", ",", "connection", ")", ":", "lob_header", "=", "ReadLobHeader", "(", "payload", ")", "if", "lob_header", ".", "isnull", "(", ")", ":", "lob", "=", "None", "else", ":", "data", "=", "payload", ".",...
40.857143
15.571429
def get_portals_list(self): """ Method to return a list of Portal names with their id's. Returns list of tuples as [(id_1, portal_name1), (id_2, portal_name2)] """ portal_ids = self.get_domain_portal_ids() portals = [ (p, self.get_portal_by_id(p)) for p in porta...
[ "def", "get_portals_list", "(", "self", ")", ":", "portal_ids", "=", "self", ".", "get_domain_portal_ids", "(", ")", "portals", "=", "[", "(", "p", ",", "self", ".", "get_portal_by_id", "(", "p", ")", ")", "for", "p", "in", "portal_ids", "]", "return", ...
50.375
21.125
def _decontextualise_connection(self, connection): """ Remove a connection from the appcontext. Args: connection (ldap3.Connection): connection to remove from the appcontext """ ctx = stack.top if ctx is not None and connection in ctx.ldap3_...
[ "def", "_decontextualise_connection", "(", "self", ",", "connection", ")", ":", "ctx", "=", "stack", ".", "top", "if", "ctx", "is", "not", "None", "and", "connection", "in", "ctx", ".", "ldap3_manager_connections", ":", "ctx", ".", "ldap3_manager_connections", ...
29.923077
21.769231
def handle(self, type: str, *, kwargs: dict = None) -> Callable: """ Register an event handler with the :obj:`Layabout` instance. Args: type: The name of a Slack RTM API event to be handled. As a special case, although it is not a proper RTM event, ``*`` may ...
[ "def", "handle", "(", "self", ",", "type", ":", "str", ",", "*", ",", "kwargs", ":", "dict", "=", "None", ")", "->", "Callable", ":", "def", "decorator", "(", "fn", ":", "Callable", ")", "->", "Callable", ":", "# Validate that the wrapped callable is a sui...
41.484848
23.242424
def trigger_event(self, element, event, event_type=None, options=None): """ :Description: Trigger specified event of the given element. :param element: Element for browser instance to target. :type element: WebElement, (WebElement, ...) :param event: Event to trigger from target ...
[ "def", "trigger_event", "(", "self", ",", "element", ",", "event", ",", "event_type", "=", "None", ",", "options", "=", "None", ")", ":", "if", "not", "isinstance", "(", "element", ",", "(", "tuple", ",", "list", ")", ")", ":", "element", "=", "[", ...
46.222222
15.407407
def plotcdf(x,xmin,alpha): """ Plots CDF and powerlaw """ x=sort(x) n=len(x) xcdf = arange(n,0,-1,dtype='float')/float(n) q = x[x>=xmin] fcdf = (q/xmin)**(1-alpha) nc = xcdf[argmax(x>=xmin)] fcdf_norm = nc*fcdf loglog(x,xcdf) loglog(q,fcdf_norm)
[ "def", "plotcdf", "(", "x", ",", "xmin", ",", "alpha", ")", ":", "x", "=", "sort", "(", "x", ")", "n", "=", "len", "(", "x", ")", "xcdf", "=", "arange", "(", "n", ",", "0", ",", "-", "1", ",", "dtype", "=", "'float'", ")", "/", "float", "...
17.5625
19.3125
def parse_arc_record(self, record): """ Parse arc record """ url = record.rec_headers.get_header('uri') url = url.replace('\r', '%0D') url = url.replace('\n', '%0A') # replace formfeed url = url.replace('\x0c', '%0C') # replace nulls url = url.repl...
[ "def", "parse_arc_record", "(", "self", ",", "record", ")", ":", "url", "=", "record", ".", "rec_headers", ".", "get_header", "(", "'uri'", ")", "url", "=", "url", ".", "replace", "(", "'\\r'", ",", "'%0D'", ")", "url", "=", "url", ".", "replace", "(...
29.233333
18.066667
def get_soap_structure(obj, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0): """Get the RBF basis SOAP output for atoms in a finite structure. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. alp: Alphas bet: Be...
[ "def", "get_soap_structure", "(", "obj", ",", "alp", ",", "bet", ",", "rCut", "=", "5.0", ",", "nMax", "=", "5", ",", "Lmax", "=", "5", ",", "crossOver", "=", "True", ",", "all_atomtypes", "=", "None", ",", "eta", "=", "1.0", ")", ":", "Hpos", "=...
38.708333
25.458333
def get_icon_url(self, icon): """ Replaces the "icon name" with a full usable URL. * When the icon is an absolute URL, it is used as-is. * When the icon contains a slash, it is relative from the ``STATIC_URL``. * Otherwise, it's relative to the theme url folder. """ ...
[ "def", "get_icon_url", "(", "self", ",", "icon", ")", ":", "if", "not", "icon", ".", "startswith", "(", "'/'", ")", "and", "not", "icon", ".", "startswith", "(", "'http://'", ")", "and", "not", "icon", ".", "startswith", "(", "'https://'", ")", ":", ...
37.058824
16.235294
def stop_capture(self, adapter_number): """ Stops a packet capture. :param adapter_number: adapter number """ try: adapter = self._ethernet_adapters[adapter_number] except KeyError: raise VMwareError("Adapter {adapter_number} doesn't exist on VMw...
[ "def", "stop_capture", "(", "self", ",", "adapter_number", ")", ":", "try", ":", "adapter", "=", "self", ".", "_ethernet_adapters", "[", "adapter_number", "]", "except", "KeyError", ":", "raise", "VMwareError", "(", "\"Adapter {adapter_number} doesn't exist on VMware ...
42.576923
34.576923
def delete_messages(self, only_processed=True): """Delete the messages previously leased. Unless otherwise directed, only the messages iterated over will be deleted. """ messages = self._processed_messages if not only_processed: messages += self._messages ...
[ "def", "delete_messages", "(", "self", ",", "only_processed", "=", "True", ")", ":", "messages", "=", "self", ".", "_processed_messages", "if", "not", "only_processed", ":", "messages", "+=", "self", ".", "_messages", "if", "messages", ":", "try", ":", "self...
31.4375
16.4375
def session_preparation(self): """Prepare the session after the connection has been established.""" self.ansi_escape_codes = True self._test_channel_read() self.set_base_prompt() self.disable_paging() self.set_terminal_width(command="terminal width 511") # Clear t...
[ "def", "session_preparation", "(", "self", ")", ":", "self", ".", "ansi_escape_codes", "=", "True", "self", ".", "_test_channel_read", "(", ")", "self", ".", "set_base_prompt", "(", ")", "self", ".", "disable_paging", "(", ")", "self", ".", "set_terminal_width...
40.4
9.4
def _prepend_name(self, prefix, dict_): '''changes the keys of the dictionary prepending them with "name."''' return dict(['.'.join([prefix, name]), msg] for name, msg in dict_.iteritems())
[ "def", "_prepend_name", "(", "self", ",", "prefix", ",", "dict_", ")", ":", "return", "dict", "(", "[", "'.'", ".", "join", "(", "[", "prefix", ",", "name", "]", ")", ",", "msg", "]", "for", "name", ",", "msg", "in", "dict_", ".", "iteritems", "(...
55.5
16
def notify_event(self, conn_string, name, event): """Notify an event. This method will launch a coroutine that runs all callbacks (and awaits all coroutines) attached to the given event that was just raised. Internally it uses :meth:`BackgroundEventLoop.launch_coroutine` which ...
[ "def", "notify_event", "(", "self", ",", "conn_string", ",", "name", ",", "event", ")", ":", "return", "self", ".", "_loop", ".", "launch_coroutine", "(", "self", ".", "_notify_event_internal", ",", "conn_string", ",", "name", ",", "event", ")" ]
44.576923
28.115385
def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(GmetricHandler, self).get_default_config_help() config.update({ 'host': 'Hostname', 'port': 'Port', 'protocol': 'udp...
[ "def", "get_default_config_help", "(", "self", ")", ":", "config", "=", "super", "(", "GmetricHandler", ",", "self", ")", ".", "get_default_config_help", "(", ")", "config", ".", "update", "(", "{", "'host'", ":", "'Hostname'", ",", "'port'", ":", "'Port'", ...
27
18.692308
def _tensor_decompose_series(lhs, rhs): """Simplification method for lhs << rhs Decompose a series product of two reducible circuits with compatible block structures into a concatenation of individual series products between subblocks. This method raises CannotSimplify when rhs is a CPermutation in ...
[ "def", "_tensor_decompose_series", "(", "lhs", ",", "rhs", ")", ":", "if", "isinstance", "(", "rhs", ",", "CPermutation", ")", ":", "raise", "CannotSimplify", "(", ")", "lhs_structure", "=", "lhs", ".", "block_structure", "rhs_structure", "=", "rhs", ".", "b...
43.428571
14.190476
def get_filesystem(filename): """Return the registered filesystem for the given file.""" filename = compat.as_str_any(filename) prefix = "" index = filename.find("://") if index >= 0: prefix = filename[:index] fs = _REGISTERED_FILESYSTEMS.get(prefix, None) if fs is None: rais...
[ "def", "get_filesystem", "(", "filename", ")", ":", "filename", "=", "compat", ".", "as_str_any", "(", "filename", ")", "prefix", "=", "\"\"", "index", "=", "filename", ".", "find", "(", "\"://\"", ")", "if", "index", ">=", "0", ":", "prefix", "=", "fi...
35.181818
15.363636
def visible(self, visible): """When visible changed, do setup or unwatch and call visible_callback""" self._visible = visible if visible and len(self.panel.objects) == 0: self.setup() self.select.visible = True self.control_panel.extend(self.controls) ...
[ "def", "visible", "(", "self", ",", "visible", ")", ":", "self", ".", "_visible", "=", "visible", "if", "visible", "and", "len", "(", "self", ".", "panel", ".", "objects", ")", "==", "0", ":", "self", ".", "setup", "(", ")", "self", ".", "select", ...
37.578947
9.526316
def submit(self, func, *args, **kwargs): """Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`""" with self._shutdown_lock: if PY3 and self._broken: raise BrokenProcessPool( "A child process terminated " "abruptly,...
[ "def", "submit", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_shutdown_lock", ":", "if", "PY3", "and", "self", ".", "_broken", ":", "raise", "BrokenProcessPool", "(", "\"A child process terminated \"...
40.448276
13.172414
def encodeValue(value): """ TODO """ if isinstance(value, (list, tuple)): return [common.AttributeValue(string_value=str(v)) for v in value] else: return [common.AttributeValue(string_value=str(value))]
[ "def", "encodeValue", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "common", ".", "AttributeValue", "(", "string_value", "=", "str", "(", "v", ")", ")", "for", "v", "in", "v...
28.875
17.125
def update(self, **kwargs): """Returns new command with replaced fields. :rtype: Command """ kwargs.setdefault('script', self.script) kwargs.setdefault('output', self.output) return Command(**kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'script'", ",", "self", ".", "script", ")", "kwargs", ".", "setdefault", "(", "'output'", ",", "self", ".", "output", ")", "return", "Command", "(", "...
26.777778
14.888889
def _make_signature_key(args, kwargs): """ Transforms function args into a key that can be used by the cache CommandLine: xdoctest -m ubelt.util_memoize _make_signature_key Example: >>> args = (4, [1, 2]) >>> kwargs = {'a': 'b'} >>> key = _make_signature_key(args, kwarg...
[ "def", "_make_signature_key", "(", "args", ",", "kwargs", ")", ":", "kwitems", "=", "kwargs", ".", "items", "(", ")", "# TODO: we should check if Python is at least 3.7 and sort by kwargs", "# keys otherwise. Should we use hash_data for key generation", "if", "(", "sys", ".",...
38.744186
17.674419
def data_to_list(self, sysbase=False): """ Return the loaded model data as a list of dictionaries. Each dictionary contains the full parameters of an element. :param sysbase: use system base quantities :type sysbase: bool """ ret = list() # for each elem...
[ "def", "data_to_list", "(", "self", ",", "sysbase", "=", "False", ")", ":", "ret", "=", "list", "(", ")", "# for each element", "for", "i", "in", "range", "(", "self", ".", "n", ")", ":", "# read the parameter values and put in the temp dict ``e``", "e", "=", ...
29.416667
17.666667
def create_trial_from_spec(spec, output_path, parser, **trial_kwargs): """Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_pars...
[ "def", "create_trial_from_spec", "(", "spec", ",", "output_path", ",", "parser", ",", "*", "*", "trial_kwargs", ")", ":", "try", ":", "args", "=", "parser", ".", "parse_args", "(", "to_argv", "(", "spec", ")", ")", "except", "SystemExit", ":", "raise", "...
44.065217
16
def is_autoshape(self): """ True if this shape is an auto shape. A shape is an auto shape if it has a ``<a:prstGeom>`` element and does not have a txBox="1" attribute on cNvSpPr. """ prstGeom = self.prstGeom if prstGeom is None: return False if...
[ "def", "is_autoshape", "(", "self", ")", ":", "prstGeom", "=", "self", ".", "prstGeom", "if", "prstGeom", "is", "None", ":", "return", "False", "if", "self", ".", "nvSpPr", ".", "cNvSpPr", ".", "txBox", "is", "True", ":", "return", "False", "return", "...
32.416667
15.75
def login(self, username, password, login_token=None): """ Authenticate with the given credentials. If authentication is successful, all further requests sent will be signed the authenticated user. Note that passwords are sent as plaintext. This is a limitation of the M...
[ "def", "login", "(", "self", ",", "username", ",", "password", ",", "login_token", "=", "None", ")", ":", "if", "login_token", "is", "None", ":", "token_doc", "=", "self", ".", "post", "(", "action", "=", "'query'", ",", "meta", "=", "'tokens'", ",", ...
45.058824
25.529412
def addtrack(self, shipment_increment_id, carrier, title, track_number): """ Add new tracking number :param shipment_increment_id: Shipment ID :param carrier: Carrier Code :param title: Tracking title :param track_number: Tracking Number """ return self.c...
[ "def", "addtrack", "(", "self", ",", "shipment_increment_id", ",", "carrier", ",", "title", ",", "track_number", ")", ":", "return", "self", ".", "call", "(", "'sales_order_shipment.addTrack'", ",", "[", "shipment_increment_id", ",", "carrier", ",", "title", ","...
33.307692
13.615385
def main(): """Entry point of rw cli""" # check logging log_level = os.environ.get('LOG_LEVEL', 'INFO') logging.basicConfig(level=getattr(logging, log_level), format='%(asctime)s %(name)s[%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S') curre...
[ "def", "main", "(", ")", ":", "# check logging", "log_level", "=", "os", ".", "environ", ".", "get", "(", "'LOG_LEVEL'", ",", "'INFO'", ")", "logging", ".", "basicConfig", "(", "level", "=", "getattr", "(", "logging", ",", "log_level", ")", ",", "format"...
36.5
14.571429
def cprint(text, color=None, on_color=None, attrs=None, **kwargs): """Print colorize text. It accepts arguments of print function. """ try: print((colored(text, color, on_color, attrs)), **kwargs) except TypeError: # flush is not supported by py2.7 kwargs.pop("flush", None) ...
[ "def", "cprint", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "print", "(", "(", "colored", "(", "text", ",", "color", ",", "on_color", ",", "attrs...
34
16
def parse_usearch61_clusters(clustered_uc_lines, otu_prefix='denovo', ref_clustered=False): """ Returns dict of cluster ID:seq IDs clustered_uc_lines: lines from .uc file resulting from de novo clustering otu_prefix: string added to beginning of OTU...
[ "def", "parse_usearch61_clusters", "(", "clustered_uc_lines", ",", "otu_prefix", "=", "'denovo'", ",", "ref_clustered", "=", "False", ")", ":", "clusters", "=", "{", "}", "failures", "=", "[", "]", "seed_hit_ix", "=", "0", "otu_id_ix", "=", "1", "seq_id_ix", ...
37.928571
19.714286
def update(self, host_list=[], serial=None, instance_name=None, use_mgmt_port=False, interval=None, bandwidth_base=None, bandwidth_unrestricted=None): """Update a license manager entry Keyword arguments: instance_name -- license manager instance name host_list -- list(dic...
[ "def", "update", "(", "self", ",", "host_list", "=", "[", "]", ",", "serial", "=", "None", ",", "instance_name", "=", "None", ",", "use_mgmt_port", "=", "False", ",", "interval", "=", "None", ",", "bandwidth_base", "=", "None", ",", "bandwidth_unrestricted...
52.2
23.5
def intersect_sites_method(form): """Return a method to intersect sites.""" if settings.PAGE_USE_SITE_ID: if settings.PAGE_HIDE_SITES: site_ids = [global_settings.SITE_ID] else: site_ids = [int(x) for x in form.data.getlist('sites')] def intersects_sites(sibling):...
[ "def", "intersect_sites_method", "(", "form", ")", ":", "if", "settings", ".", "PAGE_USE_SITE_ID", ":", "if", "settings", ".", "PAGE_HIDE_SITES", ":", "site_ids", "=", "[", "global_settings", ".", "SITE_ID", "]", "else", ":", "site_ids", "=", "[", "int", "("...
36.769231
13.307692
def transform_record(self, pid, record, links_factory=None, **kwargs): """Transform record into an intermediate representation.""" context = kwargs.get('marshmallow_context', {}) context.setdefault('pid', pid) return self.dump(self.preprocess_record(pid, record, ...
[ "def", "transform_record", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "context", "=", "kwargs", ".", "get", "(", "'marshmallow_context'", ",", "{", "}", ")", "context", ".", "setdefault",...
60.5
16.666667
def effect_info(self, mechanism, purview): """Return the effect information for a mechanism over a purview.""" return repertoire_distance( Direction.EFFECT, self.effect_repertoire(mechanism, purview), self.unconstrained_effect_repertoire(purview) )
[ "def", "effect_info", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "repertoire_distance", "(", "Direction", ".", "EFFECT", ",", "self", ".", "effect_repertoire", "(", "mechanism", ",", "purview", ")", ",", "self", ".", "unconstrained_effe...
43.142857
11.571429
def pruneChanges(self, changeHorizon): """ Called periodically by DBConnector, this method deletes changes older than C{changeHorizon}. """ if not changeHorizon: return None def thd(conn): changes_tbl = self.db.model.changes # First,...
[ "def", "pruneChanges", "(", "self", ",", "changeHorizon", ")", ":", "if", "not", "changeHorizon", ":", "return", "None", "def", "thd", "(", "conn", ")", ":", "changes_tbl", "=", "self", ".", "db", ".", "model", ".", "changes", "# First, get the list of chang...
43.333333
21.272727
def use(parser, token): ''' Counterpart to `macro`, lets you render any block/macro in place. ''' args, kwargs = parser.parse_args(token) assert isinstance(args[0], ast.Str), \ 'First argument to "include" tag must be a string' name = args[0].s action = ast.YieldFrom( value...
[ "def", "use", "(", "parser", ",", "token", ")", ":", "args", ",", "kwargs", "=", "parser", ".", "parse_args", "(", "token", ")", "assert", "isinstance", "(", "args", "[", "0", "]", ",", "ast", ".", "Str", ")", ",", "'First argument to \"include\" tag mus...
25.571429
23.857143
def system_update_column_family(self, cf_def): """ updates properties of a column family. returns the new schema id. Parameters: - cf_def """ self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_system_update_column_family(cf_def) return d
[ "def", "system_update_column_family", "(", "self", ",", "cf_def", ")", ":", "self", ".", "_seqid", "+=", "1", "d", "=", "self", ".", "_reqs", "[", "self", ".", "_seqid", "]", "=", "defer", ".", "Deferred", "(", ")", "self", ".", "send_system_update_colum...
26.181818
17.636364
def return_handler(module_logger, first_is_session=True): """Decorator for VISA library classes. """ def _outer(visa_library_method): def _inner(self, session, *args, **kwargs): ret_value = visa_library_method(*args, **kwargs) module_logger.debug('%s%s -> %r', ...
[ "def", "return_handler", "(", "module_logger", ",", "first_is_session", "=", "True", ")", ":", "def", "_outer", "(", "visa_library_method", ")", ":", "def", "_inner", "(", "self", ",", "session", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret_...
30.942857
22.171429
def get_success_url(self): """ By default we use the referer that was stuffed in our form when it was created """ if self.success_url: # if our smart url references an object, pass that in if self.success_url.find('@') > 0: return smart_url...
[ "def", "get_success_url", "(", "self", ")", ":", "if", "self", ".", "success_url", ":", "# if our smart url references an object, pass that in", "if", "self", ".", "success_url", ".", "find", "(", "'@'", ")", ">", "0", ":", "return", "smart_url", "(", "self", ...
39
19.75
def start(self, wait_for_completion=True, operation_timeout=None): """ Start this CPC, using the HMC operation "Start CPC". Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Start (start a single DPM system)" task. Parameter...
[ "def", "start", "(", "self", ",", "wait_for_completion", "=", "True", ",", "operation_timeout", "=", "None", ")", ":", "result", "=", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", "+", "'/operations/start'", ",", "wait_for_c...
37.90566
22.584906
def iter_gists(self, username=None, number=-1, etag=None): """If no username is specified, GET /gists, otherwise GET /users/:username/gists :param str login: (optional), login of the user to check :param int number: (optional), number of gists to return. Default: -1 returns ...
[ "def", "iter_gists", "(", "self", ",", "username", "=", "None", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "if", "username", ":", "url", "=", "self", ".", "_build_url", "(", "'users'", ",", "username", ",", "'gists'", ")", "e...
44.0625
19.0625
def aimport_module(self, module_name): """Import a module, and mark it reloadable Returns ------- top_module : module The imported module if it is top-level, or the top-level top_name : module Name of top_module """ self.mark_module_reloa...
[ "def", "aimport_module", "(", "self", ",", "module_name", ")", ":", "self", ".", "mark_module_reloadable", "(", "module_name", ")", "import_module", "(", "module_name", ")", "top_name", "=", "module_name", ".", "split", "(", "'.'", ")", "[", "0", "]", "top_m...
28.352941
15.470588
def acceleration_magnitude(ax, ay, az): '''Cacluate the magnitude of 3D acceleration Args ---- ax: ndarray x-axis acceleration values ay: ndarray y-axis acceleration values az: ndarray z-axis acceleration values Returns ------- acc_mag: ndarray Magni...
[ "def", "acceleration_magnitude", "(", "ax", ",", "ay", ",", "az", ")", ":", "import", "numpy", "return", "numpy", ".", "sqrt", "(", "ax", "**", "2", "+", "ay", "**", "2", "+", "az", "**", "2", ")" ]
22.619048
21.952381
def _do_lumping(self): """Do the MVCA lumping. """ model = LandmarkAgglomerative(linkage='ward', n_clusters=self.n_macrostates, metric=self.metric, n_landmarks=self.n_landmarks, ...
[ "def", "_do_lumping", "(", "self", ")", ":", "model", "=", "LandmarkAgglomerative", "(", "linkage", "=", "'ward'", ",", "n_clusters", "=", "self", ".", "n_macrostates", ",", "metric", "=", "self", ".", "metric", ",", "n_landmarks", "=", "self", ".", "n_lan...
39.444444
22.111111
def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no oth...
[ "def", "get_installation_order", "(", "self", ",", "req_set", ")", ":", "# type: (RequirementSet) -> List[InstallRequirement]", "# The current implementation, which we may change at any point", "# installs the user specified things in the order given, except when", "# dependencies must come ea...
39
19.37037
def _extract(self): """Extract email addresses from results. Text content from all crawled pages are ran through a simple email extractor. Data is cleaned prior to running pattern expressions. """ self.log.debug("Extracting emails from text content") for item in self.dat...
[ "def", "_extract", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Extracting emails from text content\"", ")", "for", "item", "in", "self", ".", "data", ":", "emails", "=", "extract_emails", "(", "item", ",", "self", ".", "domain", ",", ...
42.5
16.583333
def validate_email(addr): """Validate an email address. This function raises ``ValueError`` if the email address is not valid. >>> validate_email('foo@bar.com') 'foo@bar.com' >>> validate_email('foo@bar com') Traceback (most recent call last): ... ValueError: Invalid domain: bar co...
[ "def", "validate_email", "(", "addr", ")", ":", "if", "'@'", "not", "in", "addr", ":", "raise", "ValueError", "(", "'Invalid email address: %s'", "%", "addr", ")", "node", ",", "domain", "=", "addr", ".", "split", "(", "'@'", ",", "1", ")", "try", ":",...
27.26087
18.304348
def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie')
[ "def", "get_cookie_header", "(", "jar", ",", "request", ")", ":", "r", "=", "MockRequest", "(", "request", ")", "jar", ".", "add_cookie_header", "(", "r", ")", "return", "r", ".", "get_new_headers", "(", ")", ".", "get", "(", "'Cookie'", ")" ]
27.555556
15.555556
def fileModifiedTimestamp(fname): """return "YYYY-MM-DD" when the file was modified.""" modifiedTime=os.path.getmtime(fname) stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime)) return stamp
[ "def", "fileModifiedTimestamp", "(", "fname", ")", ":", "modifiedTime", "=", "os", ".", "path", ".", "getmtime", "(", "fname", ")", "stamp", "=", "time", ".", "strftime", "(", "'%Y-%m-%d'", ",", "time", ".", "localtime", "(", "modifiedTime", ")", ")", "r...
43
11.4
def processor(status, sender, instance, updated=None, addition=''): """ This is the standard logging processor. This is used to send the log to the handler and to other systems. """ logger = logging.getLogger(__name__) if validate_instance(instance): user = get_current_user() ap...
[ "def", "processor", "(", "status", ",", "sender", ",", "instance", ",", "updated", "=", "None", ",", "addition", "=", "''", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "validate_instance", "(", "instance", ")", ":", ...
37.903226
14.806452
def insult(rest): "Generate a random insult from datahamster" # not supplying any style will automatically redirect to a random url = 'http://autoinsult.datahamster.com/' ins_type = random.randrange(4) ins_url = url + "?style={ins_type}".format(**locals()) insre = re.compile('<div class="insult" id="insult">(.*?)...
[ "def", "insult", "(", "rest", ")", ":", "# not supplying any style will automatically redirect to a random", "url", "=", "'http://autoinsult.datahamster.com/'", "ins_type", "=", "random", ".", "randrange", "(", "4", ")", "ins_url", "=", "url", "+", "\"?style={ins_type}\""...
33.541667
14.791667
def from_shorthand(shorthand_string, slash=None): """Take a chord written in shorthand and return the notes in the chord. The function can recognize triads, sevenths, sixths, ninths, elevenths, thirteenths, slashed chords and a number of altered chords. The second argument should not be given and is o...
[ "def", "from_shorthand", "(", "shorthand_string", ",", "slash", "=", "None", ")", ":", "# warning reduce??", "if", "type", "(", "shorthand_string", ")", "==", "list", ":", "res", "=", "[", "]", "for", "x", "in", "shorthand_string", ":", "res", ".", "append...
32.816
20.768
def _stop_index(self, stop_point, inclusive): """ Determine index of stage of stopping point for run(). :param str | pypiper.Stage | function stop_point: Stopping point itself or name of it. :param bool inclusive: Whether the stopping point is to be regarded as i...
[ "def", "_stop_index", "(", "self", ",", "stop_point", ",", "inclusive", ")", ":", "if", "not", "stop_point", ":", "# Null case, no stopping point", "return", "len", "(", "self", ".", "_stages", ")", "stop_name", "=", "parse_stage_name", "(", "stop_point", ")", ...
47.75
21
def siteblock(parser, token): """Two notation types are acceptable: 1. Two arguments: {% siteblock "myblock" %} Used to render "myblock" site block. 2. Four arguments: {% siteblock "myblock" as myvar %} Used to put "myblock" site block into "m...
[ "def", "siteblock", "(", "parser", ",", "token", ")", ":", "tokens", "=", "token", ".", "split_contents", "(", ")", "tokens_num", "=", "len", "(", "tokens", ")", "if", "tokens_num", "not", "in", "(", "2", ",", "4", ")", ":", "raise", "template", ".",...
31.62963
18
def from_node(cls, node): """ Creates a new spade.message.Message from an aixoxmpp.stanza.Message Args: node (aioxmpp.stanza.Message): an aioxmpp Message Returns: spade.message.Message: a new spade Message """ if not isinstance(node, aioxmpp.stanza....
[ "def", "from_node", "(", "cls", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "aioxmpp", ".", "stanza", ".", "Message", ")", ":", "raise", "AttributeError", "(", "\"node must be a aioxmpp.stanza.Message instance\"", ")", "msg", "=", "cls"...
31.15625
18.46875
def index_nearest(array, value): """ Finds index of nearest value in array. Args: array: numpy array value: Returns: int http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array """ idx = (np.abs(array-value)).argmin() return i...
[ "def", "index_nearest", "(", "array", ",", "value", ")", ":", "idx", "=", "(", "np", ".", "abs", "(", "array", "-", "value", ")", ")", ".", "argmin", "(", ")", "return", "idx" ]
20.533333
21.2
def load(self, commit=None): """Load a result from the storage directory.""" git_info = self.record_git_info(commit) LOGGER.debug("Loading the result for commit '%s'.", git_info.hexsha) filename = self.get_filename(git_info) LOGGER.debug("Loading the result '%s'.", filename) ...
[ "def", "load", "(", "self", ",", "commit", "=", "None", ")", ":", "git_info", "=", "self", ".", "record_git_info", "(", "commit", ")", "LOGGER", ".", "debug", "(", "\"Loading the result for commit '%s'.\"", ",", "git_info", ".", "hexsha", ")", "filename", "=...
48.444444
13.666667
def getModule(metricSpec): """ Factory method to return an appropriate :class:`MetricsIface` module. - ``rmse``: :class:`MetricRMSE` - ``nrmse``: :class:`MetricNRMSE` - ``aae``: :class:`MetricAAE` - ``acc``: :class:`MetricAccuracy` - ``avg_err``: :class:`MetricAveError` - ``trivial``: :class:`MetricT...
[ "def", "getModule", "(", "metricSpec", ")", ":", "metricName", "=", "metricSpec", ".", "metric", "if", "metricName", "==", "'rmse'", ":", "return", "MetricRMSE", "(", "metricSpec", ")", "if", "metricName", "==", "'nrmse'", ":", "return", "MetricNRMSE", "(", ...
35.864865
10.432432
def Exit(msg, code=1): """Exit execution with return code and message :param msg: Message displayed prior to exit :param code: code returned upon exiting """ print >> sys.stderr, msg sys.exit(code)
[ "def", "Exit", "(", "msg", ",", "code", "=", "1", ")", ":", "print", ">>", "sys", ".", "stderr", ",", "msg", "sys", ".", "exit", "(", "code", ")" ]
30.714286
8.857143
def sweObject(obj, jd): """ Returns an object from the Ephemeris. """ sweObj = SWE_OBJECTS[obj] sweList = swisseph.calc_ut(jd, sweObj) return { 'id': obj, 'lon': sweList[0], 'lat': sweList[1], 'lonspeed': sweList[3], 'latspeed': sweList[4] }
[ "def", "sweObject", "(", "obj", ",", "jd", ")", ":", "sweObj", "=", "SWE_OBJECTS", "[", "obj", "]", "sweList", "=", "swisseph", ".", "calc_ut", "(", "jd", ",", "sweObj", ")", "return", "{", "'id'", ":", "obj", ",", "'lon'", ":", "sweList", "[", "0"...
26.454545
14.727273
def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. """ g.clog.debug('Entering postJSON') # encode data as json json_dat...
[ "def", "postJSON", "(", "g", ",", "data", ")", ":", "g", ".", "clog", ".", "debug", "(", "'Entering postJSON'", ")", "# encode data as json", "json_data", "=", "json", ".", "dumps", "(", "data", ")", ".", "encode", "(", "'utf-8'", ")", "# Send the xml to t...
37.098039
20.078431
def accept_connection(self): """ Accept a pending connection. """ assert self.pending, "Connection is not pending." self.server_protocol = self.server.server_factory.buildProtocol(None) self._accept_d.callback( FakeServerProtocolWrapper(self, self.server_proto...
[ "def", "accept_connection", "(", "self", ")", ":", "assert", "self", ".", "pending", ",", "\"Connection is not pending.\"", "self", ".", "server_protocol", "=", "self", ".", "server", ".", "server_factory", ".", "buildProtocol", "(", "None", ")", "self", ".", ...
39.444444
11.888889
def qteAdjustWidgetSizes(self, handlePos: int=None): """ Adjust the widget size inside the splitter according to ``handlePos``. See ``pos`` argument in _qteSplitterMovedEvent for a more detailed explanation. If ``handlePos`` is **None**, then the widgets are assigne equal size....
[ "def", "qteAdjustWidgetSizes", "(", "self", ",", "handlePos", ":", "int", "=", "None", ")", ":", "# Do not adjust anything if there are less than two widgets.", "if", "self", ".", "count", "(", ")", "<", "2", ":", "return", "if", "self", ".", "orientation", "(",...
29.627907
26.046512
def parse_txt_hdrs(self, s, # type: str stream_id=1, # type: int body=None, # type: Optional[str] max_frm_sz=4096, # type: int max_hdr_lst_sz=0, # type: int is_sensitive=lambda ...
[ "def", "parse_txt_hdrs", "(", "self", ",", "s", ",", "# type: str", "stream_id", "=", "1", ",", "# type: int", "body", "=", "None", ",", "# type: Optional[str]", "max_frm_sz", "=", "4096", ",", "# type: int", "max_hdr_lst_sz", "=", "0", ",", "# type: int", "is...
50.613208
28.707547
def send_request(self, request): """ Create the transaction and fill it with the outgoing request. :type request: Request :param request: the request to send :rtype : Transaction :return: the created transaction """ logger.debug("send_request - " + str(re...
[ "def", "send_request", "(", "self", ",", "request", ")", ":", "logger", ".", "debug", "(", "\"send_request - \"", "+", "str", "(", "request", ")", ")", "assert", "isinstance", "(", "request", ",", "Request", ")", "try", ":", "host", ",", "port", "=", "...
33.903226
17.129032
def remove_all_gap_columns( components ): """ Remove any columns containing only gaps from a set of alignment components, text of components is modified IN PLACE. TODO: Optimize this with Pyrex. """ seqs = [ list( c.text ) for c in components ] i = 0 text_size = len( seqs[0]...
[ "def", "remove_all_gap_columns", "(", "components", ")", ":", "seqs", "=", "[", "list", "(", "c", ".", "text", ")", "for", "c", "in", "components", "]", "i", "=", "0", "text_size", "=", "len", "(", "seqs", "[", "0", "]", ")", "while", "i", "<", "...
30
13.428571
def get_interval(x, intervals): """ finds interval of the interpolation in which x lies. :param x: :param intervals: the interpolation intervals :return: """ n = len(intervals) if n < 2: return intervals[0] n2 = n / 2 if x < int...
[ "def", "get_interval", "(", "x", ",", "intervals", ")", ":", "n", "=", "len", "(", "intervals", ")", "if", "n", "<", "2", ":", "return", "intervals", "[", "0", "]", "n2", "=", "n", "/", "2", "if", "x", "<", "intervals", "[", "n2", "]", "[", "...
30
15.066667
def VerifyStructure(self, parser_mediator, line): """Verify that this file is an IIS log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. line (str): line from a text file. Returns: bool: True i...
[ "def", "VerifyStructure", "(", "self", ",", "parser_mediator", ",", "line", ")", ":", "# TODO: self._line_structures is a work-around and this needs", "# a structural fix.", "self", ".", "_line_structures", "=", "self", ".", "LINE_STRUCTURES", "self", ".", "_day_of_month", ...
31.04
22.44
def tmpl_ifdef(self, field, trueval=u'', falseval=u''): """If field exists return trueval or the field (default) otherwise, emit return falseval (if provided). * synopsis: ``%ifdef{field}``, ``%ifdef{field,text}`` or \ ``%ifdef{field,text,falsetext}`` * description: If field...
[ "def", "tmpl_ifdef", "(", "self", ",", "field", ",", "trueval", "=", "u''", ",", "falseval", "=", "u''", ")", ":", "if", "field", "in", "self", ".", "values", ":", "return", "trueval", "else", ":", "return", "falseval" ]
40.894737
16.578947
def samples(self, gp, Y_metadata=None): """ Returns a set of samples of observations based on a given value of the latent variable. :param gp: latent variable """ orig_shape = gp.shape gp = gp.flatten() # Ysim = np.random.poisson(self.gp_link.transf(gp), [samples...
[ "def", "samples", "(", "self", ",", "gp", ",", "Y_metadata", "=", "None", ")", ":", "orig_shape", "=", "gp", ".", "shape", "gp", "=", "gp", ".", "flatten", "(", ")", "# Ysim = np.random.poisson(self.gp_link.transf(gp), [samples, gp.size]).T", "# return Ysim.reshape(...
39.416667
16.583333