text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def subscriptions_unread(self, room_id, **kwargs): """Mark messages as unread by roomId or from a message""" return self.__call_api_post('subscriptions.unread', roomId=room_id, kwargs=kwargs)
[ "def", "subscriptions_unread", "(", "self", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'subscriptions.unread'", ",", "roomId", "=", "room_id", ",", "kwargs", "=", "kwargs", ")" ]
68.333333
0.014493
def p_value_calc(TP, POP, NIR): """ Calculate p_value. :param TP: true positive :type TP : dict :param POP: population :type POP : int :param NIR: no information rate :type NIR : float :return: p_value as float """ try: n = POP x = sum(list(TP.values())) ...
[ "def", "p_value_calc", "(", "TP", ",", "POP", ",", "NIR", ")", ":", "try", ":", "n", "=", "POP", "x", "=", "sum", "(", "list", "(", "TP", ".", "values", "(", ")", ")", ")", "p", "=", "NIR", "result", "=", "0", "for", "j", "in", "range", "("...
22.363636
0.001949
def indicator(self, data): """Update the request URI to include the Indicator for specific indicator retrieval. Args: data (string): The indicator value """ # handle hashes in form md5 : sha1 : sha256 data = self.get_first_hash(data) super(File, self).indicat...
[ "def", "indicator", "(", "self", ",", "data", ")", ":", "# handle hashes in form md5 : sha1 : sha256", "data", "=", "self", ".", "get_first_hash", "(", "data", ")", "super", "(", "File", ",", "self", ")", ".", "indicator", "(", "data", ")" ]
35.555556
0.009146
def _get_default_directory(): """Returns the default directory for the Store. This is intentionally underscored to indicate that `Store.get_default_directory` is the intended way to get this information. This is also done so `Store.get_default_directory` can be mocked in tests and `_get_default_di...
[ "def", "_get_default_directory", "(", ")", ":", "return", "os", ".", "environ", ".", "get", "(", "'PRE_COMMIT_HOME'", ")", "or", "os", ".", "path", ".", "join", "(", "os", ".", "environ", ".", "get", "(", "'XDG_CACHE_HOME'", ")", "or", "os", ".", "path...
46.090909
0.001934
def set_sort_cb(self, w, index): """This callback is invoked when the user selects a new sort order from the preferences pane.""" name = self.sort_options[index] self.t_.set(sort_order=name)
[ "def", "set_sort_cb", "(", "self", ",", "w", ",", "index", ")", ":", "name", "=", "self", ".", "sort_options", "[", "index", "]", "self", ".", "t_", ".", "set", "(", "sort_order", "=", "name", ")" ]
43.6
0.009009
def activated(self, value): """ Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value) ...
[ "def", "activated", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "bool", ",", "\"'{0}' attribute: '{1}' type is not 'bool'!\"", ".", "format", "(", "\"activated\"", ",", "value", ")"...
35.416667
0.009174
def __sendString(self, string): """ Send a string of printable characters. """ logger.debug("Sending string: %r", string) # Determine if workaround is needed if not cm.ConfigManager.SETTINGS[cm.ENABLE_QT4_WORKAROUND]: self.__checkWorkaroundNeeded() # ...
[ "def", "__sendString", "(", "self", ",", "string", ")", ":", "logger", ".", "debug", "(", "\"Sending string: %r\"", ",", "string", ")", "# Determine if workaround is needed", "if", "not", "cm", ".", "ConfigManager", ".", "SETTINGS", "[", "cm", ".", "ENABLE_QT4_W...
42.072917
0.002177
def tz(self): """Return the timezone. If none is set use system timezone""" if not self._tz: self._tz = tzlocal.get_localzone().zone return self._tz
[ "def", "tz", "(", "self", ")", ":", "if", "not", "self", ".", "_tz", ":", "self", ".", "_tz", "=", "tzlocal", ".", "get_localzone", "(", ")", ".", "zone", "return", "self", ".", "_tz" ]
36
0.01087
def import_authors(self, tree): """ Retrieve all the authors used in posts and convert it to new or existing author and return the conversion. """ self.write_out(self.style.STEP('- Importing authors\n')) post_authors = set() for item in tree.findall('chan...
[ "def", "import_authors", "(", "self", ",", "tree", ")", ":", "self", ".", "write_out", "(", "self", ".", "style", ".", "STEP", "(", "'- Importing authors\\n'", ")", ")", "post_authors", "=", "set", "(", ")", "for", "item", "in", "tree", ".", "findall", ...
36.04
0.002162
def call_good_cb(self): """ If good_cb returns True then keep it :return: """ with LiveExecution.lock: if self.good_cb and not self.good_cb(): self.good_cb = None
[ "def", "call_good_cb", "(", "self", ")", ":", "with", "LiveExecution", ".", "lock", ":", "if", "self", ".", "good_cb", "and", "not", "self", ".", "good_cb", "(", ")", ":", "self", ".", "good_cb", "=", "None" ]
27.875
0.008696
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data): """ check the status of the power units """ return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"], "Power unit '{}' redundancy: {}".format(power_unit_name_data, ...
[ "def", "check_power_unit_redundancy", "(", "power_unit_name_data", ",", "power_unit_redundancy_data", ")", ":", "return", "(", "POWER_UNIT_REDUNDANCY_STATE", "[", "int", "(", "power_unit_redundancy_data", ")", "]", "[", "\"icingastatus\"", "]", ",", "\"Power unit '{}' redun...
78.142857
0.01085
def compute_iou(bbox1, bbox2): """ :param bbox1: (page, width, height, top, left, bottom, right) :param bbox2: (page, width, height, top, left, bottom, right) :return: intersection over union if bboxes are in the same page and intersect """ top_1, left_1, bottom_1, right_1 = bbox1 top_2, lef...
[ "def", "compute_iou", "(", "bbox1", ",", "bbox2", ")", ":", "top_1", ",", "left_1", ",", "bottom_1", ",", "right_1", "=", "bbox1", "top_2", ",", "left_2", ",", "bottom_2", ",", "right_2", "=", "bbox2", "if", "doOverlap", "(", "(", "top_1", ",", "left_1...
38.047619
0.002442
def warn_deprecated( since, message='', name='', alternative='', pending=False, obj_type='attribute', addendum='', removal=''): """ Used to display deprecation in a standard way. Parameters ---------- since : str The release at which this API became deprecated. message : ...
[ "def", "warn_deprecated", "(", "since", ",", "message", "=", "''", ",", "name", "=", "''", ",", "alternative", "=", "''", ",", "pending", "=", "False", ",", "obj_type", "=", "'attribute'", ",", "addendum", "=", "''", ",", "removal", "=", "''", ")", "...
44.659574
0.000466
def top_kth_iterative(x, k): """Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: ...
[ "def", "top_kth_iterative", "(", "x", ",", "k", ")", ":", "# The iterative computation is as follows:", "#", "# cur_x = x", "# for _ in range(k):", "# top_x = maximum of elements of cur_x on the last axis", "# cur_x = cur_x where cur_x < top_x and 0 everywhere else (top elements)", "...
41.354839
0.011433
def startReceivingBoxes(self, sender): """ Start observing log events for stat events to send. """ AMP.startReceivingBoxes(self, sender) log.addObserver(self._emit)
[ "def", "startReceivingBoxes", "(", "self", ",", "sender", ")", ":", "AMP", ".", "startReceivingBoxes", "(", "self", ",", "sender", ")", "log", ".", "addObserver", "(", "self", ".", "_emit", ")" ]
33.166667
0.009804
def _hbf_handle_child_elements(self, obj, ntl): """ Indirect recursion through _gen_hbf_el """ # accumulate a list of the children names in ko, and # the a dictionary of tag to xml elements. # repetition of a tag means that it will map to a list of # xml eleme...
[ "def", "_hbf_handle_child_elements", "(", "self", ",", "obj", ",", "ntl", ")", ":", "# accumulate a list of the children names in ko, and", "# the a dictionary of tag to xml elements.", "# repetition of a tag means that it will map to a list of", "# xml elements", "cd", "=", "{",...
36.975
0.001976
def _dissect_roles(metadata): """Given a model's ``metadata``, iterate over the roles. Return values are the role identifier and role type as a tuple. """ for role_key in cnxepub.ATTRIBUTED_ROLE_KEYS: for user in metadata.get(role_key, []): if user['type'] != 'cnx-id': ...
[ "def", "_dissect_roles", "(", "metadata", ")", ":", "for", "role_key", "in", "cnxepub", ".", "ATTRIBUTED_ROLE_KEYS", ":", "for", "user", "in", "metadata", ".", "get", "(", "role_key", ",", "[", "]", ")", ":", "if", "user", "[", "'type'", "]", "!=", "'c...
43
0.00207
def plotSpikeHist (include = ['allCells', 'eachPop'], timeRange = None, binSize = 5, overlay=True, graphType='line', yaxis = 'rate', popColors = [], norm = False, dpi = 100, figSize = (10,8), smooth=None, filtFreq = False, filtOrder=3, axis = 'on', saveData = None, saveFig = None, showFig = True, **kwargs): ...
[ "def", "plotSpikeHist", "(", "include", "=", "[", "'allCells'", ",", "'eachPop'", "]", ",", "timeRange", "=", "None", ",", "binSize", "=", "5", ",", "overlay", "=", "True", ",", "graphType", "=", "'line'", ",", "yaxis", "=", "'rate'", ",", "popColors", ...
41.171429
0.014772
def has_archiver_index(config, archiver): """ Check if this archiver has an index file. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :return: the exist :rtype: ``boo...
[ "def", "has_archiver_index", "(", "config", ",", "archiver", ")", ":", "root", "=", "pathlib", ".", "Path", "(", "config", ".", "cache_path", ")", "/", "archiver", "/", "\"index.json\"", "return", "root", ".", "exists", "(", ")" ]
27.4
0.002353
def handle_note(self, note, command='', training_input=''): """Handle notes and walkthrough option. @param note: See send() """ shutit_global.shutit_global_object.yield_to_draw() if self.build['walkthrough'] and note != None and note != '': assert isinstance(note, str), shutit_util.print_d...
[ "def", "handle_note", "(", "self", ",", "note", ",", "command", "=", "''", ",", "training_input", "=", "''", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "self", ".", "build", "[", "'walkthrough'", "]", "and...
49.148148
0.026608
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands t...
[ "def", "execute", "(", "self", ")", ":", "# Preprocess options to extract --settings and --pythonpath.", "# These options could affect the commands that are available, so they", "# must be processed early.", "parser", "=", "NewOptionParser", "(", "prog", "=", "self", ".", "prog_nam...
42.125
0.010638
def iter(self, count=0): '''Iterator of infinite dice rolls. :param count: [0] Return list of ``count`` sums ''' while True: yield super(FuncRoll, self).roll(count, self._func)
[ "def", "iter", "(", "self", ",", "count", "=", "0", ")", ":", "while", "True", ":", "yield", "super", "(", "FuncRoll", ",", "self", ")", ".", "roll", "(", "count", ",", "self", ".", "_func", ")" ]
35.833333
0.009091
def outputSaveCallback(self, at_data, **kwargs): """ Test method for outputSaveCallback Simply writes a file in the output tree corresponding to the number of files in the input tree. """ path = at_data[0] d_outputInfo = at_data[1] o...
[ "def", "outputSaveCallback", "(", "self", ",", "at_data", ",", "*", "*", "kwargs", ")", ":", "path", "=", "at_data", "[", "0", "]", "d_outputInfo", "=", "at_data", "[", "1", "]", "other", ".", "mkdir", "(", "self", ".", "str_outputDir", ")", "filesSave...
34.1
0.011407
def component_basis_str(basis, elements=None): '''Print a component basis set If elements is not None, only the specified elements will be printed (see :func:`bse.misc.expand_elements`) ''' s = "Description: " + basis['description'] + '\n' eldata = basis['elements'] # Filter to the given...
[ "def", "component_basis_str", "(", "basis", ",", "elements", "=", "None", ")", ":", "s", "=", "\"Description: \"", "+", "basis", "[", "'description'", "]", "+", "'\\n'", "eldata", "=", "basis", "[", "'elements'", "]", "# Filter to the given elements", "if", "e...
25.318182
0.00173
def _placeholders_recursif(nodelist, plist, blist): """Recursively search into a template node list for PlaceholderNode node.""" # I needed to do this lazy import to compile the documentation from django.template.loader_tags import BlockNode for node in nodelist: # extends node? if...
[ "def", "_placeholders_recursif", "(", "nodelist", ",", "plist", ",", "blist", ")", ":", "# I needed to do this lazy import to compile the documentation", "from", "django", ".", "template", ".", "loader_tags", "import", "BlockNode", "for", "node", "in", "nodelist", ":", ...
41.408163
0.001444
def main_help_text(self, commands_only=False): """ Returns the script's main help text, as a string. """ if commands_only: usage = sorted(get_commands().keys()) else: usage = [ "", "Type '%s help <subcommand>' for help on a ...
[ "def", "main_help_text", "(", "self", ",", "commands_only", "=", "False", ")", ":", "if", "commands_only", ":", "usage", "=", "sorted", "(", "get_commands", "(", ")", ".", "keys", "(", ")", ")", "else", ":", "usage", "=", "[", "\"\"", ",", "\"Type '%s ...
41.205882
0.002092
def deleteStyle(self, name, verbose=None): """ Deletes the Visual Style specified by the `name` parameter. :param name: Visual Style Name :param verbose: print more :returns: default: successful operation """ response=api(url=self.___url+'styles/'+str(name)+'',...
[ "def", "deleteStyle", "(", "self", ",", "name", ",", "verbose", "=", "None", ")", ":", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'styles/'", "+", "str", "(", "name", ")", "+", "''", ",", "method", "=", "\"DELETE\"", ",",...
30.583333
0.010582
def get_relay_state(self): """Get the relay state.""" self.get_status() try: self.state = self.data['relay'] except TypeError: self.state = False return bool(self.state)
[ "def", "get_relay_state", "(", "self", ")", ":", "self", ".", "get_status", "(", ")", "try", ":", "self", ".", "state", "=", "self", ".", "data", "[", "'relay'", "]", "except", "TypeError", ":", "self", ".", "state", "=", "False", "return", "bool", "...
25.111111
0.008547
def definition(self, suffix = "", local=False, ctype=None, optionals=True, customdim=None, modifiers=None): """Returns the fortran code string that would define this value element. :arg suffix: an optional suffix to append to the name of the variable. Useful for re-using de...
[ "def", "definition", "(", "self", ",", "suffix", "=", "\"\"", ",", "local", "=", "False", ",", "ctype", "=", "None", ",", "optionals", "=", "True", ",", "customdim", "=", "None", ",", "modifiers", "=", "None", ")", ":", "kind", "=", "\"({})\"", ".", ...
51.5
0.008167
def _run_runner(self): ''' Actually execute specific runner :return: ''' import salt.minion ret = {} low = {'fun': self.opts['fun']} try: # Allocate a jid async_pub = self._gen_async_pub() self.jid = async_pub['jid'] ...
[ "def", "_run_runner", "(", "self", ")", ":", "import", "salt", ".", "minion", "ret", "=", "{", "}", "low", "=", "{", "'fun'", ":", "self", ".", "opts", "[", "'fun'", "]", "}", "try", ":", "# Allocate a jid", "async_pub", "=", "self", ".", "_gen_async...
42.349593
0.001125
def seconds2str(seconds): """Returns string such as 1h 05m 55s.""" if seconds < 0: return "{0:.3g}s".format(seconds) elif math.isnan(seconds): return "NaN" elif math.isinf(seconds): return "Inf" m, s = divmod(seconds, 60) h, m = divmod(m, 60) if h >= 1: ...
[ "def", "seconds2str", "(", "seconds", ")", ":", "if", "seconds", "<", "0", ":", "return", "\"{0:.3g}s\"", ".", "format", "(", "seconds", ")", "elif", "math", ".", "isnan", "(", "seconds", ")", ":", "return", "\"NaN\"", "elif", "math", ".", "isinf", "("...
26.444444
0.002028
def parse_msg_sender(filename, sender_known=True): """Given a filename returns the sender and the message. Here the message is assumed to be a whole MIME message or just message body. >>> sender, msg = parse_msg_sender('msg.eml') >>> sender, msg = parse_msg_sender('msg_body') If you don't wan...
[ "def", "parse_msg_sender", "(", "filename", ",", "sender_known", "=", "True", ")", ":", "import", "sys", "kwargs", "=", "{", "}", "if", "sys", ".", "version_info", ">", "(", "3", ",", "0", ")", ":", "kwargs", "[", "\"encoding\"", "]", "=", "\"utf8\"", ...
36.421053
0.000704
def _WritePathInfo(self, client_id, path_info): """Writes a single path info record for given client.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) path_record = self._GetPathRecord(client_id, path_info) path_record.AddPathInfo(path_info) parent_path_info = pa...
[ "def", "_WritePathInfo", "(", "self", ",", "client_id", ",", "path_info", ")", ":", "if", "client_id", "not", "in", "self", ".", "metadatas", ":", "raise", "db", ".", "UnknownClientError", "(", "client_id", ")", "path_record", "=", "self", ".", "_GetPathReco...
40.5
0.008048
def set_contrast(self, contrast): """Sets the contrast of the display. Contrast should be a value between 0 and 255.""" if contrast < 0 or contrast > 255: raise ValueError('Contrast must be a value from 0 to 255 (inclusive).') self.command(SSD1306_SETCONTRAST) self.c...
[ "def", "set_contrast", "(", "self", ",", "contrast", ")", ":", "if", "contrast", "<", "0", "or", "contrast", ">", "255", ":", "raise", "ValueError", "(", "'Contrast must be a value from 0 to 255 (inclusive).'", ")", "self", ".", "command", "(", "SSD1306_SETCONTRAS...
47.142857
0.011905
def read_VMP_modules(fileobj, read_module_data=True): """Reads in module headers in the VMPmodule_hdr format. Yields a dict with the headers and offset for each module. N.B. the offset yielded is the offset to the start of the data i.e. after the end of the header. The data runs from (offset) to (offse...
[ "def", "read_VMP_modules", "(", "fileobj", ",", "read_module_data", "=", "True", ")", ":", "while", "True", ":", "module_magic", "=", "fileobj", ".", "read", "(", "len", "(", "b'MODULE'", ")", ")", "if", "len", "(", "module_magic", ")", "==", "0", ":", ...
46.611111
0.000584
def get_book_ids_by_comment(self, comment_id): """Gets the list of ``Book`` ``Ids`` mapped to a ``Comment``. arg: comment_id (osid.id.Id): ``Id`` of a ``Comment`` return: (osid.id.IdList) - list of book ``Ids`` raise: NotFound - ``comment_id`` is not found raise: NullArgum...
[ "def", "get_book_ids_by_comment", "(", "self", ",", "comment_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_bin_ids_by_resource", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'COMMENTING'", ",", "local", "=", "True", ")"...
46.909091
0.001899
def nodes(self): """ Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode) """ resource = sub_collection( self.get_relation('vss_container_node'), VSSContainerNode) resource._load_from_engine(self, 'nodes...
[ "def", "nodes", "(", "self", ")", ":", "resource", "=", "sub_collection", "(", "self", ".", "get_relation", "(", "'vss_container_node'", ")", ",", "VSSContainerNode", ")", "resource", ".", "_load_from_engine", "(", "self", ",", "'nodes'", ")", "return", "resou...
30.636364
0.017291
def _identifyBranches(self): """ A helper function for determining all of the branches in the tree. This should be called after the tree has been fully constructed and its nodes and edges are populated. """ if self.debug: sys.stdout.write("Identifying branche...
[ "def", "_identifyBranches", "(", "self", ")", ":", "if", "self", ".", "debug", ":", "sys", ".", "stdout", ".", "write", "(", "\"Identifying branches: \"", ")", "start", "=", "time", ".", "clock", "(", ")", "seen", "=", "set", "(", ")", "self", ".", "...
30.310345
0.002205
def add_partition_with_environment_context(self, new_part, environment_context): """ Parameters: - new_part - environment_context """ self.send_add_partition_with_environment_context(new_part, environment_context) return self.recv_add_partition_with_environment_context()
[ "def", "add_partition_with_environment_context", "(", "self", ",", "new_part", ",", "environment_context", ")", ":", "self", ".", "send_add_partition_with_environment_context", "(", "new_part", ",", "environment_context", ")", "return", "self", ".", "recv_add_partition_with...
36.75
0.009967
def ack(self, tup): """Indicate that processing of a Tuple has succeeded It is compatible with StreamParse API. """ if not isinstance(tup, HeronTuple): Log.error("Only HeronTuple type is supported in ack()") return if self.acking_enabled: ack_tuple = tuple_pb2.AckTuple() ac...
[ "def", "ack", "(", "self", ",", "tup", ")", ":", "if", "not", "isinstance", "(", "tup", ",", "HeronTuple", ")", ":", "Log", ".", "error", "(", "\"Only HeronTuple type is supported in ack()\"", ")", "return", "if", "self", ".", "acking_enabled", ":", "ack_tup...
36.347826
0.012821
def domainogram(M, window=None, circ=False, extrapolate=True): """From a symmetrical matrix M of size n, return a vector d whose each component d[i] is the total sum of a square of 2*window+1 size centered on the i-th main diagonal element. Edge elements may be extrapolated based on the square size redu...
[ "def", "domainogram", "(", "M", ",", "window", "=", "None", ",", "circ", "=", "False", ",", "extrapolate", "=", "True", ")", ":", "# Sanity checks", "if", "not", "type", "(", "M", ")", "is", "np", ".", "ndarray", ":", "M", "=", "np", ".", "array", ...
34.75
0.000538
def unpack_rawr_zip_payload(table_sources, payload): """unpack a zipfile and turn it into a callable "tables" object.""" # the io we get from S3 is streaming, so we can't seek on it, but zipfile # seems to require that. so we buffer it all in memory. RAWR tiles are # generally up to around 100MB in size...
[ "def", "unpack_rawr_zip_payload", "(", "table_sources", ",", "payload", ")", ":", "# the io we get from S3 is streaming, so we can't seek on it, but zipfile", "# seems to require that. so we buffer it all in memory. RAWR tiles are", "# generally up to around 100MB in size, which should be safe t...
42.6
0.001148
def create_function_f_i(self): """state reinitialization (reset) function""" return ca.Function( 'f_i', [self.t, self.x, self.y, self.m, self.p, self.c, self.pre_c, self.ng, self.nu], [self.f_i], ['t', 'x', 'y', 'm', 'p', 'c', 'pre_c', 'ng', 'nu'], ['x_n']...
[ "def", "create_function_f_i", "(", "self", ")", ":", "return", "ca", ".", "Function", "(", "'f_i'", ",", "[", "self", ".", "t", ",", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "m", ",", "self", ".", "p", ",", "self", ".", "c", ...
47.142857
0.011905
def generate_account(self, services, resource_types, permission, expiry, start=None, ip=None, protocol=None): ''' Generates a shared access signature for the account. Use the returned signature with the sas_token parameter of the service or to create a new accou...
[ "def", "generate_account", "(", "self", ",", "services", ",", "resource_types", ",", "permission", ",", "expiry", ",", "start", "=", "None", ",", "ip", "=", "None", ",", "protocol", "=", "None", ")", ":", "sas", "=", "_SharedAccessHelper", "(", ")", "sas...
58.269231
0.012009
def closest_allzero_pixel(self, pixel, direction, w=13, t=0.5): """Starting at pixel, moves pixel by direction * t until all zero pixels within a radius w of pixel. Then, returns pixel. Parameters ---------- pixel : :obj:`numpy.ndarray` of float The initial pixel loc...
[ "def", "closest_allzero_pixel", "(", "self", ",", "pixel", ",", "direction", ",", "w", "=", "13", ",", "t", "=", "0.5", ")", ":", "# create circular structure for checking clearance", "y", ",", "x", "=", "np", ".", "meshgrid", "(", "np", ".", "arange", "("...
38.288136
0.002158
def map_colors(arr, crange, cmap, hex=True): """ Maps an array of values to RGB hex strings, given a color range and colormap. """ if isinstance(crange, np.ndarray): xsorted = np.argsort(crange) ypos = np.searchsorted(crange, arr) arr = xsorted[ypos] else: if isin...
[ "def", "map_colors", "(", "arr", ",", "crange", ",", "cmap", ",", "hex", "=", "True", ")", ":", "if", "isinstance", "(", "crange", ",", "np", ".", "ndarray", ")", ":", "xsorted", "=", "np", ".", "argsort", "(", "crange", ")", "ypos", "=", "np", "...
29.714286
0.001553
def reaction_elements(reaction): """ Split metabolites into the atoms times their stoichiometric coefficients. Parameters ---------- reaction : Reaction The metabolic reaction whose components are desired. Returns ------- list Each of the reaction's metabolites' desired...
[ "def", "reaction_elements", "(", "reaction", ")", ":", "c_elements", "=", "[", "coeff", "*", "met", ".", "elements", ".", "get", "(", "'C'", ",", "0", ")", "for", "met", ",", "coeff", "in", "iteritems", "(", "reaction", ".", "metabolites", ")", "]", ...
31.666667
0.001704
def exclude(self, regex, which='exclude'): """Exclude source lines from execution consideration. A number of lists of regular expressions are maintained. Each list selects lines that are treated differently during reporting. `which` determines which list is modified. The "exclude" li...
[ "def", "exclude", "(", "self", ",", "regex", ",", "which", "=", "'exclude'", ")", ":", "excl_list", "=", "getattr", "(", "self", ".", "config", ",", "which", "+", "\"_list\"", ")", "excl_list", ".", "append", "(", "regex", ")", "self", ".", "_exclude_r...
44.555556
0.002442
def configure_logger_for_colour(logger: logging.Logger, level: int = logging.INFO, remove_existing: bool = False, extranames: List[str] = None, with_process_id: bool = False, ...
[ "def", "configure_logger_for_colour", "(", "logger", ":", "logging", ".", "Logger", ",", "level", ":", "int", "=", "logging", ".", "INFO", ",", "remove_existing", ":", "bool", "=", "False", ",", "extranames", ":", "List", "[", "str", "]", "=", "None", ",...
45.642857
0.000766
def bytes(self): """ Encoded instruction """ b = [bytes([self._opcode])] for offset in reversed(range(self.operand_size)): b.append(bytes([(self.operand >> offset * 8) & 0xff])) return b''.join(b)
[ "def", "bytes", "(", "self", ")", ":", "b", "=", "[", "bytes", "(", "[", "self", ".", "_opcode", "]", ")", "]", "for", "offset", "in", "reversed", "(", "range", "(", "self", ".", "operand_size", ")", ")", ":", "b", ".", "append", "(", "bytes", ...
39.166667
0.008333
def _prune_some_if_small(self, small_size, a_or_u): "Merge some nodes in the directory, whilst keeping others." # Assert that we're not messing things up. prev_app_size = self.app_size() prev_use_size = self.use_size() keep_nodes = [] prune_app_size = 0 prune_use...
[ "def", "_prune_some_if_small", "(", "self", ",", "small_size", ",", "a_or_u", ")", ":", "# Assert that we're not messing things up.", "prev_app_size", "=", "self", ".", "app_size", "(", ")", "prev_use_size", "=", "self", ".", "use_size", "(", ")", "keep_nodes", "=...
41.458333
0.000982
def set_default_verify_paths(self): """ Specify that the platform provided CA certificates are to be used for verification purposes. This method has some caveats related to the binary wheels that cryptography (pyOpenSSL's primary dependency) ships: * macOS will only load certi...
[ "def", "set_default_verify_paths", "(", "self", ")", ":", "# SSL_CTX_set_default_verify_paths will attempt to load certs from", "# both a cafile and capath that are set at compile time. However,", "# it will first check environment variables and, if present, load", "# those paths instead", "set_...
50.6875
0.000806
def _add_parameter(self_, param_name,param_obj): """ Add a new Parameter object into this object's class. Supposed to result in a Parameter equivalent to one declared in the class's source code. """ # CEBALERT: can't we just do # setattr(cls,param_name,param_obj)...
[ "def", "_add_parameter", "(", "self_", ",", "param_name", ",", "param_obj", ")", ":", "# CEBALERT: can't we just do", "# setattr(cls,param_name,param_obj)? The metaclass's", "# __setattr__ is actually written to handle that. (Would also", "# need to do something about the params() cache....
43.217391
0.008858
def score(self, seq, fwd='Y'): """ m.score(seq, fwd='Y') -- Returns the score of the first w-bases of the sequence, where w is the motif width. """ matches, endpoints, scores = self._scan(seq,threshold=-100000,forw_only=fwd) return scores[0]
[ "def", "score", "(", "self", ",", "seq", ",", "fwd", "=", "'Y'", ")", ":", "matches", ",", "endpoints", ",", "scores", "=", "self", ".", "_scan", "(", "seq", ",", "threshold", "=", "-", "100000", ",", "forw_only", "=", "fwd", ")", "return", "scores...
46
0.021352
def select(data, trial=None, invert=False, **axes_to_select): """Define the selection of trials, using ranges or actual values. Parameters ---------- data : instance of Data data to select from. trial : list of int or ndarray (dtype='i'), optional index of trials of interest **a...
[ "def", "select", "(", "data", ",", "trial", "=", "None", ",", "invert", "=", "False", ",", "*", "*", "axes_to_select", ")", ":", "if", "trial", "is", "not", "None", "and", "not", "isinstance", "(", "trial", ",", "Iterable", ")", ":", "raise", "TypeEr...
37.910112
0.000289
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` clas...
[ "def", "checkArgs", "(", "args", ")", ":", "# Check if we have the tped and the tfam files", "prefixes_to_check", "=", "[", "args", ".", "bfile", "]", "if", "not", "args", ".", "skip_ref_pops", ":", "for", "pop", "in", "(", "\"ceu\"", ",", "\"yri\"", ",", "\"j...
33.797297
0.000389
def process_openxml_file(filename: str, print_good: bool, delete_if_bad: bool) -> None: """ Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if `...
[ "def", "process_openxml_file", "(", "filename", ":", "str", ",", "print_good", ":", "bool", ",", "delete_if_bad", ":", "bool", ")", "->", "None", ":", "print_bad", "=", "not", "print_good", "try", ":", "file_good", "=", "is_openxml_good", "(", "filename", ")...
36.62069
0.000917
def execDetails(self, reqId, contract, execution): """ This wrapper handles both live fills and responses to reqExecutions. """ if execution.orderId == UNSET_INTEGER: # bug in TWS: executions of manual orders have unset value execution.orderId = 0 key = se...
[ "def", "execDetails", "(", "self", ",", "reqId", ",", "contract", ",", "execution", ")", ":", "if", "execution", ".", "orderId", "==", "UNSET_INTEGER", ":", "# bug in TWS: executions of manual orders have unset value", "execution", ".", "orderId", "=", "0", "key", ...
44.055556
0.001234
def _set_join(self, query=None): """ Set the join clause for the query. """ if not query: query = self._query foreign_key = '%s.%s' % (self._related.get_table(), self._second_key) query.join(self._parent.get_table(), self.get_qualified_parent_key_name(), '='...
[ "def", "_set_join", "(", "self", ",", "query", "=", "None", ")", ":", "if", "not", "query", ":", "query", "=", "self", ".", "_query", "foreign_key", "=", "'%s.%s'", "%", "(", "self", ".", "_related", ".", "get_table", "(", ")", ",", "self", ".", "_...
32.5
0.008982
def nucmer_hit_containing_reference_position(nucmer_hits, ref_name, ref_position, qry_name=None): '''Returns the first nucmer match found that contains the given reference location. nucmer_hits = hits made by self._parse_nucmer_coords_file. Returns None if no matching hit found''' ...
[ "def", "nucmer_hit_containing_reference_position", "(", "nucmer_hits", ",", "ref_name", ",", "ref_position", ",", "qry_name", "=", "None", ")", ":", "for", "contig_name", "in", "nucmer_hits", ":", "for", "hit", "in", "nucmer_hits", "[", "contig_name", "]", ":", ...
59.7
0.008251
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'): """Replaces <table> elements with its ASCII equivalent. """ tables = self._parse_tables(soup) v_sep_len = len(v_separator) v_left_sep = v_separator.lstrip() for t in tables: html = '' ...
[ "def", "_replace_tables", "(", "self", ",", "soup", ",", "v_separator", "=", "' | '", ",", "h_separator", "=", "'-'", ")", ":", "tables", "=", "self", ".", "_parse_tables", "(", "soup", ")", "v_sep_len", "=", "len", "(", "v_separator", ")", "v_left_sep", ...
42.655172
0.001581
def save_config(self, cmd="save force", confirm=False, confirm_response=""): """Save Config.""" return super(HPComwareBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
[ "def", "save_config", "(", "self", ",", "cmd", "=", "\"save force\"", ",", "confirm", "=", "False", ",", "confirm_response", "=", "\"\"", ")", ":", "return", "super", "(", "HPComwareBase", ",", "self", ")", ".", "save_config", "(", "cmd", "=", "cmd", ","...
47.2
0.008333
def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq): """ Solves the power flow using a full Newton's method. """ i = 0 Va = angle(V) Vm = abs(V) # FIXME: Do not repeat build for each Q limit loop. Bp, Bpp = self.case.makeB(method=self.method) # Evalua...
[ "def", "_run_power_flow", "(", "self", ",", "Ybus", ",", "Sbus", ",", "V", ",", "pv", ",", "pq", ",", "pvpq", ")", ":", "i", "=", "0", "Va", "=", "angle", "(", "V", ")", "Vm", "=", "abs", "(", "V", ")", "# FIXME: Do not repeat build for each Q limit ...
34.797101
0.002025
def actually_mount(self, client): """Actually mount something in Vault""" a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] try: m_fun = getattr(client, self.mount_fun) if self.description and a_obj: m_fun(...
[ "def", "actually_mount", "(", "self", ",", "client", ")", ":", "a_obj", "=", "self", ".", "config", ".", "copy", "(", ")", "if", "'description'", "in", "a_obj", ":", "del", "a_obj", "[", "'description'", "]", "try", ":", "m_fun", "=", "getattr", "(", ...
38.25
0.001594
def gsea_pval(es, esnull): """Compute nominal p-value. From article (PNAS): estimate nominal p-value for S from esnull by using the positive or negative portion of the distribution corresponding to the sign of the observed ES(S). """ # to speed up, using numpy function to compute pval in p...
[ "def", "gsea_pval", "(", "es", ",", "esnull", ")", ":", "# to speed up, using numpy function to compute pval in parallel.", "condlist", "=", "[", "es", "<", "0", ",", "es", ">=", "0", "]", "choicelist", "=", "[", "np", ".", "sum", "(", "esnull", "<", "es", ...
37.25
0.01473
def get_adaptive_threshold(threshold_method, image, threshold, mask = None, adaptive_window_size = 10, **kwargs): """Given a global threshold, compute a threshold per pixel Break the image into blocks, computing the thres...
[ "def", "get_adaptive_threshold", "(", "threshold_method", ",", "image", ",", "threshold", ",", "mask", "=", "None", ",", "adaptive_window_size", "=", "10", ",", "*", "*", "kwargs", ")", ":", "# for the X and Y direction, find the # of blocks, given the", "# size constra...
38.588235
0.012635
def decodeMotorInput(self, motorInputPattern): """ Decode motor command from bit vector. @param motorInputPattern (1D numpy.array) Encoded motor command. @return (1D numpy.array) Decoded motor command. """ key = self.motorEncoder.decode(motorInputPattern)[0].k...
[ "def", "decodeMotorInput", "(", "self", ",", "motorInputPattern", ")", ":", "key", "=", "self", ".", "motorEncoder", ".", "decode", "(", "motorInputPattern", ")", "[", "0", "]", ".", "keys", "(", ")", "[", "0", "]", "motorCommand", "=", "self", ".", "m...
29.714286
0.002331
def shutit_method_scope(func): """Notifies the ShutIt object whenever we call a shutit module method. This allows setting values for the 'scope' of a function. """ def wrapper(self, shutit): """Wrapper to call a shutit module method, notifying the ShutIt object. """ ret = func(self, shutit) return ret retu...
[ "def", "shutit_method_scope", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "shutit", ")", ":", "\"\"\"Wrapper to call a shutit module method, notifying the ShutIt object.\n\t\t\"\"\"", "ret", "=", "func", "(", "self", ",", "shutit", ")", "return", "ret",...
32.1
0.030303
def checkEdges(ringSet, lookup, oatoms): """atoms, lookup -> ring atoms must be in the order of traversal around a ring! break an optimal non N2 node and return the largest ring found """ bondedAtoms = map( None, ringSet[:-1], ringSet[1:] ) bondedAtoms += [ (ringSet[-1], ringSet[0]) ] #...
[ "def", "checkEdges", "(", "ringSet", ",", "lookup", ",", "oatoms", ")", ":", "bondedAtoms", "=", "map", "(", "None", ",", "ringSet", "[", ":", "-", "1", "]", ",", "ringSet", "[", "1", ":", "]", ")", "bondedAtoms", "+=", "[", "(", "ringSet", "[", ...
29.272727
0.016525
def verify_notification(data): """ Function to verify notification came from a trusted source Returns True if verfied, False if not verified """ pemfile = grab_keyfile(data['SigningCertURL']) cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile) signature = base64.decodestring(six.b(...
[ "def", "verify_notification", "(", "data", ")", ":", "pemfile", "=", "grab_keyfile", "(", "data", "[", "'SigningCertURL'", "]", ")", "cert", "=", "crypto", ".", "load_certificate", "(", "crypto", ".", "FILETYPE_PEM", ",", "pemfile", ")", "signature", "=", "b...
30
0.001538
def _iter_matches(self, input_match, subject_graph, one_match, level=0): """Given an onset for a match, iterate over all completions of that match This iterator works recursively. At each level the match is extended with a new set of relations based on vertices in the pattern graph ...
[ "def", "_iter_matches", "(", "self", ",", "input_match", ",", "subject_graph", ",", "one_match", ",", "level", "=", "0", ")", ":", "self", ".", "print_debug", "(", "\"ENTERING _ITER_MATCHES\"", ",", "1", ")", "self", ".", "print_debug", "(", "\"input_match: %s...
56.065217
0.001905
def filter_by_label(self, pores=[], throats=[], labels=None, mode='or'): r""" Returns which of the supplied pores (or throats) has the specified label Parameters ---------- pores, or throats : array_like List of pores or throats to be filtered labels...
[ "def", "filter_by_label", "(", "self", ",", "pores", "=", "[", "]", ",", "throats", "=", "[", "]", ",", "labels", "=", "None", ",", "mode", "=", "'or'", ")", ":", "# Convert inputs to locations and element", "if", "(", "sp", ".", "size", "(", "throats", ...
35.351351
0.000744
def install_all_integration_alerts(self, id, **kwargs): # noqa: E501 """Enable all alerts associated with this integration # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> ...
[ "def", "install_all_integration_alerts", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", ...
44.636364
0.001994
def next_partname(self, template): """Return a |PackURI| instance representing partname matching *template*. The returned part-name has the next available numeric suffix to distinguish it from other parts of its type. *template* is a printf (%)-style template string containing a single ...
[ "def", "next_partname", "(", "self", ",", "template", ")", ":", "partnames", "=", "{", "part", ".", "partname", "for", "part", "in", "self", ".", "iter_parts", "(", ")", "}", "for", "n", "in", "range", "(", "1", ",", "len", "(", "partnames", ")", "...
54
0.008403
def button_state(self): """The button state of the event. For events that are not of type :attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property raises :exc:`AttributeError`. Returns: ~libinput.constant.ButtonState: The button state triggering this event. """ if self.type != Event...
[ "def", "button_state", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "TABLET_TOOL_BUTTON", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput"...
29.375
0.028866
def table_from_root(source, treename=None, columns=None, **kwargs): """Read a Table from a ROOT tree """ import root_numpy # parse column filters into tree2array ``selection`` keyword # NOTE: not all filters can be passed directly to root_numpy, so we store # those separately and apply th...
[ "def", "table_from_root", "(", "source", ",", "treename", "=", "None", ",", "columns", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "root_numpy", "# parse column filters into tree2array ``selection`` keyword", "# NOTE: not all filters can be passed directly to ...
36.235294
0.000527
def translate_dict(cls, val): """Translate dicts to scala Maps""" escaped = ', '.join( ["{} -> {}".format(cls.translate_str(k), cls.translate(v)) for k, v in val.items()] ) return 'Map({})'.format(escaped)
[ "def", "translate_dict", "(", "cls", ",", "val", ")", ":", "escaped", "=", "', '", ".", "join", "(", "[", "\"{} -> {}\"", ".", "format", "(", "cls", ".", "translate_str", "(", "k", ")", ",", "cls", ".", "translate", "(", "v", ")", ")", "for", "k", ...
40.666667
0.012048
def all(self): """ Returns all the values joined together. :return <int> """ out = 0 for key, value in self.items(): out |= value return out
[ "def", "all", "(", "self", ")", ":", "out", "=", "0", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", ":", "out", "|=", "value", "return", "out" ]
21.2
0.013575
def init_all(self,roots=None,inverted_edges=None,optimize=False): """initializes the layout algorithm by computing roots (unless provided), inverted edges (unless provided), vertices ranks and creates all dummy vertices and layers. Parameters: ro...
[ "def", "init_all", "(", "self", ",", "roots", "=", "None", ",", "inverted_edges", "=", "None", ",", "optimize", "=", "False", ")", ":", "if", "self", ".", "initdone", ":", "return", "# For layered sugiyama algorithm, the input graph must be acyclic,", "# so we must ...
47.111111
0.013867
def _get_temp_file_location(): ''' Returns user specified temporary file location. The temporary location is specified through: >>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) ''' from .._connect import main as _glconnect unity = _glconnect.get_unity() cache_...
[ "def", "_get_temp_file_location", "(", ")", ":", "from", ".", ".", "_connect", "import", "main", "as", "_glconnect", "unity", "=", "_glconnect", ".", "get_unity", "(", ")", "cache_dir", "=", "_convert_slashes", "(", "unity", ".", "get_current_cache_file_location",...
33
0.002105
def set_legend(self, legend): """legend needs to be a list, tuple or None""" assert(isinstance(legend, list) or isinstance(legend, tuple) or legend is None) if legend: self.legend = [quote(a) for a in legend] else: self.legend = None
[ "def", "set_legend", "(", "self", ",", "legend", ")", ":", "assert", "(", "isinstance", "(", "legend", ",", "list", ")", "or", "isinstance", "(", "legend", ",", "tuple", ")", "or", "legend", "is", "None", ")", "if", "legend", ":", "self", ".", "legen...
36.75
0.009967
def prox_l0(v, alpha): r"""Compute the proximal operator of the :math:`\ell_0` "norm" (hard thresholding) .. math:: \mathrm{prox}_{\alpha f}(v) = \mathcal{S}_{0,\alpha}(\mathbf{v}) = \left\{ \begin{array}{ccc} 0 & \text{if} & | v | < \sqrt{2 \alpha} \\ v &\text{if} & | v | \geq \s...
[ "def", "prox_l0", "(", "v", ",", "alpha", ")", ":", "return", "(", "np", ".", "abs", "(", "v", ")", ">=", "np", ".", "sqrt", "(", "2.0", "*", "alpha", ")", ")", "*", "v" ]
34.153846
0.00073
def agg(self, func, *fields, **name): """ Calls the aggregation function `func` on each group in the GroubyTable, and leaves the results in a new column with the name of the aggregation function. Call `.agg` with `name='desired_column_name' to choose a column name for th...
[ "def", "agg", "(", "self", ",", "func", ",", "*", "fields", ",", "*", "*", "name", ")", ":", "if", "name", ":", "if", "len", "(", "name", ")", ">", "1", "or", "'name'", "not", "in", "name", ":", "raise", "TypeError", "(", "\"Unknown keyword args pa...
39.957447
0.00104
def main(pattern_filename, input_filenames, pattern_format, output_filename, encoding, words, by_line, slow, verbose, quiet): ''' Search and replace on INPUT_FILE(s) (or standard input), with matching on fixed strings. ''' set_log_level(verbose, quiet) if slow: by_line ...
[ "def", "main", "(", "pattern_filename", ",", "input_filenames", ",", "pattern_format", ",", "output_filename", ",", "encoding", ",", "words", ",", "by_line", ",", "slow", ",", "verbose", ",", "quiet", ")", ":", "set_log_level", "(", "verbose", ",", "quiet", ...
43.564103
0.002303
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler.library_dirs``. On macOS, a Homebrew installed ``gfortran`` needs some help. The ``numpy.distutils`` "default" constructor for ``Gnu95FCompiler`` only has a single library search path, but there are many library paths included in the ...
[ "def", "patch_f90_compiler", "(", "f90_compiler", ")", ":", "if", "not", "is_macos_gfortran", "(", "f90_compiler", ")", ":", "return", "library_dirs", "=", "f90_compiler", ".", "library_dirs", "# ``library_dirs`` is a list (i.e. mutable), so we can update in place.", "library...
38.666667
0.001403
def add_all(self, items, overflow_policy=OVERFLOW_POLICY_OVERWRITE): """ Adds all of the item in the specified collection to the tail of the Ringbuffer. An add_all is likely to outperform multiple calls to add(object) due to better io utilization and a reduced number of executed operatio...
[ "def", "add_all", "(", "self", ",", "items", ",", "overflow_policy", "=", "OVERFLOW_POLICY_OVERWRITE", ")", ":", "check_not_empty", "(", "items", ",", "\"items can't be empty\"", ")", "if", "len", "(", "items", ")", ">", "MAX_BATCH_SIZE", ":", "raise", "Assertio...
61.809524
0.008346
def sync(opts, form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None): ''' Sync custom modules into the extension_modules directory ''' if saltenv is None: saltenv = ['base'] if extmod_whitelist is None: extmod_whitelist = opts['extmod_...
[ "def", "sync", "(", "opts", ",", "form", ",", "saltenv", "=", "None", ",", "extmod_whitelist", "=", "None", ",", "extmod_blacklist", "=", "None", ")", ":", "if", "saltenv", "is", "None", ":", "saltenv", "=", "[", "'base'", "]", "if", "extmod_whitelist", ...
44.213675
0.001134
def _ToCamelCase(name): """Converts name to camel-case and returns it.""" capitalize_next = False result = [] for c in name: if c == '_': if result: capitalize_next = True elif capitalize_next: result.append(c.upper()) capitalize_next = False else: result += c # L...
[ "def", "_ToCamelCase", "(", "name", ")", ":", "capitalize_next", "=", "False", "result", "=", "[", "]", "for", "c", "in", "name", ":", "if", "c", "==", "'_'", ":", "if", "result", ":", "capitalize_next", "=", "True", "elif", "capitalize_next", ":", "re...
22.368421
0.027088
def euclidean_distance_numpy(object1, object2): """! @brief Calculate Euclidean distance between two objects using numpy. @param[in] object1 (array_like): The first array_like object. @param[in] object2 (array_like): The second array_like object. @return (double) Euclidean distance between ...
[ "def", "euclidean_distance_numpy", "(", "object1", ",", "object2", ")", ":", "return", "numpy", ".", "sum", "(", "numpy", ".", "sqrt", "(", "numpy", ".", "square", "(", "object1", "-", "object2", ")", ")", ",", "axis", "=", "1", ")", ".", "T" ]
37.272727
0.002381
def cancelAll(self): """ Cancel all submitted IO blocks. Blocks until all submitted transfers have been finalised. Submitting more transfers or processing completion events while this method is running produces undefined behaviour. Returns the list of values returned by ...
[ "def", "cancelAll", "(", "self", ")", ":", "cancel", "=", "self", ".", "cancel", "result", "=", "[", "]", "for", "block", ",", "_", "in", "self", ".", "_submitted", ".", "itervalues", "(", ")", ":", "try", ":", "result", ".", "append", "(", "cancel...
39.590909
0.002242
def _parse_tags(tag_file): """Parses a tag file, according to RFC 2822. This includes line folding, permitting extra-long field values. See http://www.faqs.org/rfcs/rfc2822.html for more information. """ tag_name = None tag_value = None # Line folding is handled by yi...
[ "def", "_parse_tags", "(", "tag_file", ")", ":", "tag_name", "=", "None", "tag_value", "=", "None", "# Line folding is handled by yielding values only after we encounter", "# the start of a new tag, or if we pass the EOF.", "for", "num", ",", "line", "in", "enumerate", "(", ...
34.175
0.002134
def get_ccle_mutations(gene_list, cell_lines, mutation_type=None): """Return a dict of mutations in given genes and cell lines from CCLE. This is a specialized call to get_mutations tailored to CCLE cell lines. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get ...
[ "def", "get_ccle_mutations", "(", "gene_list", ",", "cell_lines", ",", "mutation_type", "=", "None", ")", ":", "mutations", "=", "{", "cl", ":", "{", "g", ":", "[", "]", "for", "g", "in", "gene_list", "}", "for", "cl", "in", "cell_lines", "}", "for", ...
39.166667
0.000692
def actionsFreqs(self,*args,**kwargs): """ NAME: actionsFreqs PURPOSE: evaluate the actions and frequencies (jr,lz,jz,Omegar,Omegaphi,Omegaz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for sing...
[ "def", "actionsFreqs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "_actionsFreqs", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "AttributeError", ":", "#pragma: no cover", "raise", ...
27.628571
0.012987
def _get_stub_and_request_classes(self, service_name): """ import protobuf and return stub and request class """ # Compile protobuf if needed codegen_dir = Path.home().joinpath(".snet", "mpe_client", "control_service") proto_dir = Path(__file__).absolute().parent.joinpath("resources", ...
[ "def", "_get_stub_and_request_classes", "(", "self", ",", "service_name", ")", ":", "# Compile protobuf if needed", "codegen_dir", "=", "Path", ".", "home", "(", ")", ".", "joinpath", "(", "\".snet\"", ",", "\"mpe_client\"", ",", "\"control_service\"", ")", "proto_d...
61.5
0.014423
def sha1(self): """Return a sha1 hash of the model items. :rtype: str """ sha1 = hashlib.sha1(''.join(['%s:%s' % (k,v) for k,v in self.items()])) return str(sha1.hexdigest())
[ "def", "sha1", "(", "self", ")", ":", "sha1", "=", "hashlib", ".", "sha1", "(", "''", ".", "join", "(", "[", "'%s:%s'", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", "]", ")", ")", "return", "str"...
26.125
0.018519
def get_cumulative_spend(key): """ Get the sum of spending for this category up to and including the given month. """ query = ('ROUND(SUM(total_ex_vat), 2) AS total ' 'FROM {table} ' 'WHERE date <= "{year}-{month:02}-01" ' 'AND lot="{lot}" ' 'AND c...
[ "def", "get_cumulative_spend", "(", "key", ")", ":", "query", "=", "(", "'ROUND(SUM(total_ex_vat), 2) AS total '", "'FROM {table} '", "'WHERE date <= \"{year}-{month:02}-01\" '", "'AND lot=\"{lot}\" '", "'AND customer_sector=\"{sector}\" '", "'AND supplier_type=\"{sme_large}\"'", ".", ...
36
0.00123
def parse(self, argv, command): """ Splits an argument list into an options dictionary and a fieldname list. The argument list, `argv`, must be of the form:: *[option]... *[<field-name>] Options are validated and assigned to items in `command.options`. Field names ...
[ "def", "parse", "(", "self", ",", "argv", ",", "command", ")", ":", "# Prepare", "command_args", "=", "' '", ".", "join", "(", "argv", ")", "command", ".", "fieldnames", "=", "None", "command", ".", "options", ".", "reset", "(", ")", "command_args", "=...
32.75
0.00247
def __do_grep(curr_line, pattern, **kwargs): """ Do grep on a single string. See 'grep' docs for info about kwargs. :param curr_line: a single line to test. :param pattern: pattern to search. :return: (matched, position, end_position). """ # currently found position position = -1 ...
[ "def", "__do_grep", "(", "curr_line", ",", "pattern", ",", "*", "*", "kwargs", ")", ":", "# currently found position", "position", "=", "-", "1", "end_pos", "=", "-", "1", "# check if fixed strings mode", "if", "kwargs", ".", "get", "(", "'fixed_strings'", ")"...
28.04878
0.00084
def slice_sequence(self,start,end): """Slice the mapping by the position in the sequence First coordinate is 0-indexed start Second coordinate is 1-indexed finish """ #find the sequence length l = self.length indexstart = start indexend = end ns = [] tot...
[ "def", "slice_sequence", "(", "self", ",", "start", ",", "end", ")", ":", "#find the sequence length", "l", "=", "self", ".", "length", "indexstart", "=", "start", "indexend", "=", "end", "ns", "=", "[", "]", "tot", "=", "0", "for", "r", "in", "self", ...
25.413793
0.037908
def get_locations(self, ip, detailed=False): """Returns a list of dictionaries with location data or False on failure. Argument `ip` must be an iterable object. Amount of information about IP contained in the dictionary depends upon `detailed` flag state. """ if...
[ "def", "get_locations", "(", "self", ",", "ip", ",", "detailed", "=", "False", ")", ":", "if", "isinstance", "(", "ip", ",", "str", ")", ":", "ip", "=", "[", "ip", "]", "seek", "=", "map", "(", "self", ".", "_get_pos", ",", "ip", ")", "return", ...
38.923077
0.011583