text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def surface_ras_shift(self): """Freesurfer uses two coordinate systems: one for volumes ("RAS") and one for surfaces ("tkReg", "tkRAS", and "Surface RAS"). To get from surface to volume coordinates, add this numbers. To get from volume to surface coordinates, substract this numbers. ...
[ "def", "surface_ras_shift", "(", "self", ")", ":", "T1_path", "=", "self", ".", "dir", "/", "'mri'", "/", "'T1.mgz'", "assert", "T1_path", ".", "exists", "(", ")", "T1", "=", "nload", "(", "str", "(", "T1_path", ")", ")", "return", "T1", ".", "header...
38.666667
17.083333
def AppendToFile(filename, contents, eol_style=EOL_STYLE_NATIVE, encoding=None, binary=False): ''' Appends content to a local file. :param unicode filename: :param unicode contents: :type eol_style: EOL_STYLE_XXX constant :param eol_style: Replaces the EOL by the appropriate EOL depen...
[ "def", "AppendToFile", "(", "filename", ",", "contents", ",", "eol_style", "=", "EOL_STYLE_NATIVE", ",", "encoding", "=", "None", ",", "binary", "=", "False", ")", ":", "_AssertIsLocal", "(", "filename", ")", "assert", "isinstance", "(", "contents", ",", "si...
32.888889
27.333333
def to_dict(self): """ Convert this VirtualIP to a dict representation for passing to the API. """ if self.id: return {"id": self.id} return {"type": self.type, "ipVersion": self.ip_version}
[ "def", "to_dict", "(", "self", ")", ":", "if", "self", ".", "id", ":", "return", "{", "\"id\"", ":", "self", ".", "id", "}", "return", "{", "\"type\"", ":", "self", ".", "type", ",", "\"ipVersion\"", ":", "self", ".", "ip_version", "}" ]
30.375
15.125
async def on_raw_329(self, message): """ Channel creation time. """ target, channel, timestamp = message.params if not self.in_channel(channel): return self.channels[channel]['created'] = datetime.datetime.fromtimestamp(int(timestamp))
[ "async", "def", "on_raw_329", "(", "self", ",", "message", ")", ":", "target", ",", "channel", ",", "timestamp", "=", "message", ".", "params", "if", "not", "self", ".", "in_channel", "(", "channel", ")", ":", "return", "self", ".", "channels", "[", "c...
39.142857
18.285714
def auth_proxy(self, method): """Authentication proxy for API requests. This is required because the API objects are naive of ``HelpScout``, so they would otherwise be unauthenticated. Args: method (callable): A method call that should be authenticated. It shou...
[ "def", "auth_proxy", "(", "self", ",", "method", ")", ":", "def", "_proxy", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"The actual proxy, which instantiates and authenticates the API.\n\n Args:\n *args (mixed): Args to send to class ins...
35.555556
23.074074
def reset(self): """Reset the value to the default""" if self.resetable: for i in range(len(self)): self[i] = self.default
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "resetable", ":", "for", "i", "in", "range", "(", "len", "(", "self", ")", ")", ":", "self", "[", "i", "]", "=", "self", ".", "default" ]
32.4
8.4
def middleware(self, *args, **kwargs): """ A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group. In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recur...
[ "def", "middleware", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"bp_group\"", "]", "=", "True", "def", "register_middleware_for_blueprints", "(", "fn", ")", ":", "for", "blueprint", "in", "self", ".", "blueprints", ...
40.105263
20.947368
def store_file(self, filename, file_content, content_type): """ Store a small file in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file will have in the Upload Area :param str file_content: The contents of the ...
[ "def", "store_file", "(", "self", ",", "filename", ",", "file_content", ",", "content_type", ")", ":", "return", "self", ".", "upload_service", ".", "api_client", ".", "store_file", "(", "area_uuid", "=", "self", ".", "uuid", ",", "filename", "=", "filename"...
51.764706
26.941176
def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
[ "def", "delete_saml_provider", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", ...
36
25.75
def list(gandi, state, id, limit, datacenter): """List virtual machines.""" options = { 'items_per_page': limit, } if state: options['state'] = state if datacenter: options['datacenter_id'] = gandi.datacenter.usable_id(datacenter) output_keys = ['hostname', 'state'] ...
[ "def", "list", "(", "gandi", ",", "state", ",", "id", ",", "limit", ",", "datacenter", ")", ":", "options", "=", "{", "'items_per_page'", ":", "limit", ",", "}", "if", "state", ":", "options", "[", "'state'", "]", "=", "state", "if", "datacenter", ":...
25.333333
18.47619
def reduce_filename(f): r''' Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb Where XXX is a variation on the model size for example And where YYY is a const related to the training dataset ''' f = os.path.basename(f).split('.') return keep_only_digits(f[-3])
[ "def", "reduce_filename", "(", "f", ")", ":", "f", "=", "os", ".", "path", ".", "basename", "(", "f", ")", ".", "split", "(", "'.'", ")", "return", "keep_only_digits", "(", "f", "[", "-", "3", "]", ")" ]
33.666667
22.555556
def _processSegmentUpdates(self, activeColumns): """ Go through the list of accumulated segment updates and process them as follows: if the segment update is too old, remove the update else if the cell received bottom-up, update its permanences else if it's still being predicted, leave it in th...
[ "def", "_processSegmentUpdates", "(", "self", ",", "activeColumns", ")", ":", "# The segmentUpdates dict has keys which are the column,cellIdx of the", "# owner cell. The values are lists of segment updates for that cell", "removeKeys", "=", "[", "]", "trimSegments", "=", "[", "]",...
35.457143
21.542857
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary ...
[ "def", "dict_of_sets_add", "(", "dictionary", ",", "key", ",", "value", ")", ":", "# type: (DictUpperBound, Any, Any) -> None", "set_objs", "=", "dictionary", ".", "get", "(", "key", ",", "set", "(", ")", ")", "set_objs", ".", "add", "(", "value", ")", "dict...
27.3125
18.125
def _query_iterator(self, result, chunksize, columns, coerce_float=True, parse_dates=None): """Return generator through chunked result set.""" while True: data = result.fetchmany(chunksize) if not data: break else: ...
[ "def", "_query_iterator", "(", "self", ",", "result", ",", "chunksize", ",", "columns", ",", "coerce_float", "=", "True", ",", "parse_dates", "=", "None", ")", ":", "while", "True", ":", "data", "=", "result", ".", "fetchmany", "(", "chunksize", ")", "if...
34.666667
21.111111
def get_vlan_from_query_reply(self, reply, vsiid, mac): """Parse the query reply from VDP daemon to get the VLAN value. """ hints_ret, fail_reason = self.check_hints(reply) if not hints_ret: LOG.error("Incorrect hints found %s", reply) return constants.INVALID_VLAN, fail_...
[ "def", "get_vlan_from_query_reply", "(", "self", ",", "reply", ",", "vsiid", ",", "mac", ")", ":", "hints_ret", ",", "fail_reason", "=", "self", ".", "check_hints", "(", "reply", ")", "if", "not", "hints_ret", ":", "LOG", ".", "error", "(", "\"Incorrect hi...
46.956522
15
def to_lal_type_str(pytype): """Convert the input python type to a LAL type string Examples -------- To convert a python type: >>> from gwpy.utils.lal import to_lal_type_str >>> to_lal_type_str(float) 'REAL8' To convert a `numpy.dtype`: >>> import numpy >>> to_lal_type_str(nu...
[ "def", "to_lal_type_str", "(", "pytype", ")", ":", "# noop", "if", "pytype", "in", "LAL_TYPE_FROM_STR", ":", "return", "pytype", "# convert type code", "if", "pytype", "in", "LAL_TYPE_STR", ":", "return", "LAL_TYPE_STR", "[", "pytype", "]", "# convert python type", ...
21.170732
21.560976
def irecarray_to_py(a): """Slow conversion of a recarray into a list of records with python types. Get the field names from :attr:`a.dtype.names`. :Returns: iterator so that one can handle big input arrays """ pytypes = [pyify(typestr) for name,typestr in a.dtype.descr] def convert_record(r): ...
[ "def", "irecarray_to_py", "(", "a", ")", ":", "pytypes", "=", "[", "pyify", "(", "typestr", ")", "for", "name", ",", "typestr", "in", "a", ".", "dtype", ".", "descr", "]", "def", "convert_record", "(", "r", ")", ":", "return", "tuple", "(", "[", "c...
39.181818
18.909091
def set_params(self, params): """Sets multiple GO-PCA Server parameters using a dictionary. Parameters ---------- params: dict Dictionary containing the parameter values. Returns ------- None """ for k,v in params.iteritems(): ...
[ "def", "set_params", "(", "self", ",", "params", ")", ":", "for", "k", ",", "v", "in", "params", ".", "iteritems", "(", ")", ":", "self", ".", "set_param", "(", "k", ",", "v", ")" ]
23.642857
18.5
def _rightleft(self, direction): """Provides curses horizontal padding""" if direction == "left" and self.padding != 0: self.padding -= 1 if direction == "right" and \ self.screen.getmaxyx()[1] + self.padding < self.max_width: self.padding += 1
[ "def", "_rightleft", "(", "self", ",", "direction", ")", ":", "if", "direction", "==", "\"left\"", "and", "self", ".", "padding", "!=", "0", ":", "self", ".", "padding", "-=", "1", "if", "direction", "==", "\"right\"", "and", "self", ".", "screen", "."...
33.555556
17.777778
def find_revision_number(self, revision=None): """Find the local revision number of the given revision.""" # Make sure the local repository exists. self.create() # Try to find the revision number of the specified revision. revision = revision or self.default_revision outp...
[ "def", "find_revision_number", "(", "self", ",", "revision", "=", "None", ")", ":", "# Make sure the local repository exists.", "self", ".", "create", "(", ")", "# Try to find the revision number of the specified revision.", "revision", "=", "revision", "or", "self", ".",...
52.666667
17.416667
def __annotate_sequence_with_quality(seq, q_line_parts): """Extract meta data from pre-tokenized maf q-line and populate sequence. q -- quality information about an aligned base in a species. Two fields after the 'q': the source name and a single digit for each nucleotide in its sequence (0-9 or F, o...
[ "def", "__annotate_sequence_with_quality", "(", "seq", ",", "q_line_parts", ")", ":", "if", "q_line_parts", "[", "1", "]", "!=", "seq", ".", "name", ":", "raise", "MAFError", "(", "\"trying to populate meta data for sequence \"", "+", "seq", ".", "name", "+", "\...
54.058824
20.882353
def doFeedback(self, item_id, use_comment_template, buyer_id, comment, comment_type, op): """http://allegro.pl/webapi/documentation.php/show/id,42""" return self.__ask__('doFeedback', feItemId=item_id, feUseCommentTemplate=use_comment_template, ...
[ "def", "doFeedback", "(", "self", ",", "item_id", ",", "use_comment_template", ",", "buyer_id", ",", "comment", ",", "comment_type", ",", "op", ")", ":", "return", "self", ".", "__ask__", "(", "'doFeedback'", ",", "feItemId", "=", "item_id", ",", "feUseComme...
56.777778
13.777778
def _construct_module(info, target): """Build a module from templates and user supplied information""" for path in paths: real_path = os.path.abspath(os.path.join(target, path.format(**info))) log("Making directory '%s'" % real_path) os.makedirs(real_path) # pprint(info) for it...
[ "def", "_construct_module", "(", "info", ",", "target", ")", ":", "for", "path", "in", "paths", ":", "real_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "target", ",", "path", ".", "format", "(", "*", "*",...
38.8125
16.375
def match_tweet(self, tweet, user_stream): """ Check if a tweet matches the defined criteria :param tweet: The tweet in question :type tweet: :class:`~responsebot.models.Tweet` :return: True if matched, False otherwise """ if user_stream: if len(self....
[ "def", "match_tweet", "(", "self", ",", "tweet", ",", "user_stream", ")", ":", "if", "user_stream", ":", "if", "len", "(", "self", ".", "track", ")", ">", "0", ":", "return", "self", ".", "is_tweet_match_track", "(", "tweet", ")", "return", "True", "re...
32.266667
17.333333
def _get_alpha(self, C, vs30, pga_rock): """ Returns the alpha, the linearised functional relationship between the site amplification and the PGA on rock. Equation 31. """ alpha = np.zeros(len(pga_rock)) idx = vs30 < C["k1"] if np.any(idx): af1 = pga_r...
[ "def", "_get_alpha", "(", "self", ",", "C", ",", "vs30", ",", "pga_rock", ")", ":", "alpha", "=", "np", ".", "zeros", "(", "len", "(", "pga_rock", ")", ")", "idx", "=", "vs30", "<", "C", "[", "\"k1\"", "]", "if", "np", ".", "any", "(", "idx", ...
42.230769
15.307692
def google_maps_geoloc_link(data): """ Get a link to google maps pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to google maps pointing on this IP's geolocation. """ if isinstance(data, str): lat_lon ...
[ "def", "google_maps_geoloc_link", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "lat_lon", "=", "ip_geoloc", "(", "data", ")", "if", "lat_lon", "is", "None", ":", "return", "''", "lat", ",", "lon", "=", "lat_lon", "else"...
28.904762
18.809524
def report_view(self, request, key, period): """ Processes the reporting action. """ if not self.has_change_permission(request, None): raise PermissionDenied reporters = self.get_reporters() try: reporter = reporters[key] except KeyError:...
[ "def", "report_view", "(", "self", ",", "request", ",", "key", ",", "period", ")", ":", "if", "not", "self", ".", "has_change_permission", "(", "request", ",", "None", ")", ":", "raise", "PermissionDenied", "reporters", "=", "self", ".", "get_reporters", "...
37
25.307692
def score(self, query, normalized=True, synonimizer=None, return_suffix_scores=False): """ Matches the string against the GAST using the algorithm described in [Chernyak, sections 1.3 & 1.4]. Expects the input string to consist of alphabet letters only (no whitespaces et...
[ "def", "score", "(", "self", ",", "query", ",", "normalized", "=", "True", ",", "synonimizer", "=", "None", ",", "return_suffix_scores", "=", "False", ")", ":", "query", "=", "query", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "result", "=", "0", ...
34.090909
17.909091
def delete(self, path, data={}): '''Perform DELETE Request''' if len(data) != 0: parameter_string = '' for k,v in data.items(): parameter_string += '{}={}'.format(k,v) parameter_string += '&' path += '?' + parameter_string resp...
[ "def", "delete", "(", "self", ",", "path", ",", "data", "=", "{", "}", ")", ":", "if", "len", "(", "data", ")", "!=", "0", ":", "parameter_string", "=", "''", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "parameter_string", ...
40.727273
14.909091
def _find_matcher(self, alias): """ Finds a matcher based on the given alias or raises an error if no matcher could be found. """ matcher = lookup(alias) if not matcher: msg = 'Matcher "%s" not found' % alias # Try to find similarly named matchers to ...
[ "def", "_find_matcher", "(", "self", ",", "alias", ")", ":", "matcher", "=", "lookup", "(", "alias", ")", "if", "not", "matcher", ":", "msg", "=", "'Matcher \"%s\" not found'", "%", "alias", "# Try to find similarly named matchers to help the user", "similar", "=", ...
36.631579
17.789474
def detect(self, G): """Detect a single core-periphery pair. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> lrc = cp.LowRankCore() >>> lrc.detect(G) ...
[ "def", "detect", "(", "self", ",", "G", ")", ":", "self", ".", "c_", ",", "self", ".", "x_", "=", "self", ".", "_low_rank_core", "(", "G", ")", "self", ".", "Q_", "=", "self", ".", "_score", "(", "G", ",", "self", ".", "c_", ",", "self", ".",...
20.142857
21.47619
def makeLys(segID, N, CA, C, O, geo): '''Creates a Lysine residue''' ##R-Group CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle CB_CG_length=geo.CB_CG_length CA_CB_CG_angle=geo.CA_CB_CG_angle N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle ...
[ "def", "makeLys", "(", "segID", ",", "N", ",", "CA", ",", "C", ",", "O", ",", "geo", ")", ":", "##R-Group", "CA_CB_length", "=", "geo", ".", "CA_CB_length", "C_CA_CB_angle", "=", "geo", ".", "C_CA_CB_angle", "N_C_CA_CB_diangle", "=", "geo", ".", "N_C_CA_...
36.23913
21.586957
def move_item_into_viewport(self, item): """Causes the `item` to be moved into the viewport The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item` is not a `StateView`, the parental `StateView` is moved into the viewport. :param Sta...
[ "def", "move_item_into_viewport", "(", "self", ",", "item", ")", ":", "if", "not", "item", ":", "return", "HORIZONTAL", "=", "0", "VERTICAL", "=", "1", "if", "not", "isinstance", "(", "item", ",", "Item", ")", ":", "state_v", "=", "item", ".", "parent"...
54.348837
32.186047
def create(self, name, serviceId, timezone, description, enabled): """ Create a connector for the organization in the Watson IoT Platform. The connector must reference the target service that the Watson IoT Platform will store the IoT data in. Parameters: - name (string) - N...
[ "def", "create", "(", "self", ",", "name", ",", "serviceId", ",", "timezone", ",", "description", ",", "enabled", ")", ":", "connector", "=", "{", "\"name\"", ":", "name", ",", "\"description\"", ":", "description", ",", "\"serviceId\"", ":", "serviceId", ...
36.785714
18.714286
def get_id(date=None, project: str = 'sip', instance_id: int = None) -> str: """Get a SBI Identifier. Args: date (str or datetime.datetime, optional): UTC date of the SBI project (str, optional ): Project Name instance_id (int, optional): SBI instance ...
[ "def", "get_id", "(", "date", "=", "None", ",", "project", ":", "str", "=", "'sip'", ",", "instance_id", ":", "int", "=", "None", ")", "->", "str", ":", "if", "date", "is", "None", ":", "date", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ...
30.478261
19.565217
def is_group_valid(self, groupID): """ Check if this group ID is valid. """ cur = self.conn.cursor() cur.execute('SELECT * FROM groups WHERE id=? LIMIT 1', [groupID]) results = cur.fetchall() cur.close() logging.debug('is_group_valid(groupID={}) => {}'.fo...
[ "def", "is_group_valid", "(", "self", ",", "groupID", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT * FROM groups WHERE id=? LIMIT 1'", ",", "[", "groupID", "]", ")", "results", "=", "cur", ".", ...
35.363636
17.363636
def clean_title(self, title): """Clean title with the use of og:site_name in this case try to get rid of site name and use TITLE_SPLITTERS to reformat title """ # check if we have the site name in opengraph data if "site_name" in self.article.opengraph.keys(): ...
[ "def", "clean_title", "(", "self", ",", "title", ")", ":", "# check if we have the site name in opengraph data", "if", "\"site_name\"", "in", "self", ".", "article", ".", "opengraph", ".", "keys", "(", ")", ":", "site_name", "=", "self", ".", "article", ".", "...
33.75
15.4
def processWhileRunning(self): """ Run tasks until stopService is called. """ work = self.step() for result, more in work: yield result if not self.running: break if more: delay = 0.1 else: ...
[ "def", "processWhileRunning", "(", "self", ")", ":", "work", "=", "self", ".", "step", "(", ")", "for", "result", ",", "more", "in", "work", ":", "yield", "result", "if", "not", "self", ".", "running", ":", "break", "if", "more", ":", "delay", "=", ...
27.785714
12.214286
def _get_aux_specs(self): """Get and pre-process all of the non-core specifications.""" # Drop the "core" specifications, which are handled separately. specs = self._specs_in.copy() [specs.pop(core) for core in self._CORE_SPEC_NAMES] specs[_REGIONS_STR] = self._get_regions() ...
[ "def", "_get_aux_specs", "(", "self", ")", ":", "# Drop the \"core\" specifications, which are handled separately.", "specs", "=", "self", ".", "_specs_in", ".", "copy", "(", ")", "[", "specs", ".", "pop", "(", "core", ")", "for", "core", "in", "self", ".", "_...
43
20.25
def evaluate(ref_intervals_hier, ref_labels_hier, est_intervals_hier, est_labels_hier, **kwargs): '''Compute all hierarchical structure metrics for the given reference and estimated annotations. Examples -------- A toy example with two two-layer annotations >>> ref_i = [[[0, 30], ...
[ "def", "evaluate", "(", "ref_intervals_hier", ",", "ref_labels_hier", ",", "est_intervals_hier", ",", "est_labels_hier", ",", "*", "*", "kwargs", ")", ":", "# First, find the maximum length of the reference", "_", ",", "t_end", "=", "_hierarchy_bounds", "(", "ref_interv...
41.868852
21.737705
def set_attrs(self, **attrs): """Set the given attributes on *all* commands in collection.""" commands = tuple(self.values()) for name, value in attrs.items(): for command in commands: setattr(command, name, value)
[ "def", "set_attrs", "(", "self", ",", "*", "*", "attrs", ")", ":", "commands", "=", "tuple", "(", "self", ".", "values", "(", ")", ")", "for", "name", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "for", "command", "in", "commands", "...
43.5
3.666667
def to_hex(x): """ Converts input to the hex string :param x: :return: """ if isinstance(x, bytearray): x = bytes(x) elif isinstance(x, (list, tuple)): x = bytes(bytearray(x)) if isinstance(x, basestring): return base64.b16encode(x).decode('ascii') else: ...
[ "def", "to_hex", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "bytearray", ")", ":", "x", "=", "bytes", "(", "x", ")", "elif", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "x", "=", "bytes", "(", "bytearray",...
25.5
13.357143
def write_collection_from_tmpfile(self, collection_id, tmpfi, parent_sha, auth_info, commit_msg=''): """Given a collection_id, temporary filename of content, branch and auth_info """ return self.write_doc_from_tmpfile(collection_id, tmpfi, ...
[ "def", "write_collection_from_tmpfile", "(", "self", ",", "collection_id", ",", "tmpfi", ",", "parent_sha", ",", "auth_info", ",", "commit_msg", "=", "''", ")", ":", "return", "self", ".", "write_doc_from_tmpfile", "(", "collection_id", ",", "tmpfi", ",", "paren...
60
18.222222
def my_psd(x,NFFT=2**10,Fs=1): """ A local version of NumPy's PSD function that returns the plot arrays. A mlab.psd wrapper function that returns two ndarrays; makes no attempt to auto plot anything. Parameters ---------- x : ndarray input signal NFFT : a power of two, e.g., 2**10 = 10...
[ "def", "my_psd", "(", "x", ",", "NFFT", "=", "2", "**", "10", ",", "Fs", "=", "1", ")", ":", "Px", ",", "f", "=", "pylab", ".", "mlab", ".", "psd", "(", "x", ",", "NFFT", ",", "Fs", ")", "return", "Px", ".", "flatten", "(", ")", ",", "f" ...
27.138889
18.416667
def send_message(self, message, room_id, **kwargs): """ Send a message to a given room """ return SendMessage(settings=self.settings, **kwargs).call( message=message, room_id=room_id, **kwargs )
[ "def", "send_message", "(", "self", ",", "message", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "SendMessage", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(", "message", "=", "message", ...
29.111111
12.666667
def add_subgroups(self, subgroups): """ Add a list of SubGroupDefinition objects to this composite. Note that in contrast to :meth:`BaseTrack`, which takes a single dictionary indicating the particular subgroups for the track, this method takes a list of :class:`SubGroupDefiniti...
[ "def", "add_subgroups", "(", "self", ",", "subgroups", ")", ":", "if", "subgroups", "is", "None", ":", "subgroups", "=", "{", "}", "_subgroups", "=", "{", "}", "for", "sg", "in", "subgroups", ":", "assert", "isinstance", "(", "sg", ",", "SubGroupDefiniti...
36.789474
17
def containerFor(self, entry): """ Returns a container for the inputed entry widget. :param entry | <XOrbQueryEntryWidget> :return <XOrbQueryContainer> || None """ try: index = self._compoundStack.index(entry) excep...
[ "def", "containerFor", "(", "self", ",", "entry", ")", ":", "try", ":", "index", "=", "self", ".", "_compoundStack", ".", "index", "(", "entry", ")", "except", "ValueError", ":", "return", "None", "return", "self", ".", "widget", "(", "index", "+", "1"...
28.142857
15.142857
def class_name(self): """str: class name of the key or None if not available.""" if not self._registry_key and self._registry: self._GetKeyFromRegistry() if not self._registry_key: return None return self._registry_key.class_name
[ "def", "class_name", "(", "self", ")", ":", "if", "not", "self", ".", "_registry_key", "and", "self", ".", "_registry", ":", "self", ".", "_GetKeyFromRegistry", "(", ")", "if", "not", "self", ".", "_registry_key", ":", "return", "None", "return", "self", ...
27.888889
16.555556
def _transform_col(self, x, i): """Encode one categorical column into sparse matrix with one-hot-encoding. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: X (scipy.sparse.coo_matrix): sparse matrix encoding a categorica...
[ "def", "_transform_col", "(", "self", ",", "x", ",", "i", ")", ":", "labels", "=", "self", ".", "label_encoder", ".", "_transform_col", "(", "x", ",", "i", ")", "label_max", "=", "self", ".", "label_encoder", ".", "label_maxes", "[", "i", "]", "# build...
37.076923
22.730769
def get_subdomain_ops_at_txid(txid, proxy=None, hostport=None): """ Get the list of subdomain operations added by a txid Returns the list of operations ([{...}]) on success Returns {'error': ...} on failure """ assert proxy or hostport, 'Need proxy or hostport' if proxy is None: prox...
[ "def", "get_subdomain_ops_at_txid", "(", "txid", ",", "proxy", "=", "None", ",", "hostport", "=", "None", ")", ":", "assert", "proxy", "or", "hostport", ",", "'Need proxy or hostport'", "if", "proxy", "is", "None", ":", "proxy", "=", "connect_hostport", "(", ...
32.971831
23.985915
def debug(message, *args, **kwargs): """ debug output goes to stderr so you can still redirect the stdout to a file or another program. Controlled by the JUT_DEBUG environment variable being present """ if 'end' in kwargs: end = kwargs['end'] else: end = '\n' if DEBUG: ...
[ "def", "debug", "(", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'end'", "in", "kwargs", ":", "end", "=", "kwargs", "[", "'end'", "]", "else", ":", "end", "=", "'\\n'", "if", "DEBUG", ":", "if", "len", "(", "args", ")...
24.15
20.55
def process_hv_plots(widgets, plots): """ Temporary fix to patch HoloViews plot comms """ bokeh_plots = [] for plot in plots: if hasattr(plot, '_update_callbacks'): for subplot in plot.traverse(lambda x: x): subplot.comm = widgets.server_comm for c...
[ "def", "process_hv_plots", "(", "widgets", ",", "plots", ")", ":", "bokeh_plots", "=", "[", "]", "for", "plot", "in", "plots", ":", "if", "hasattr", "(", "plot", ",", "'_update_callbacks'", ")", ":", "for", "subplot", "in", "plot", ".", "traverse", "(", ...
35.466667
10.266667
def xml(self, url, method='get', params=None, data=None): """ 请求并返回xml :type url: str :param url: API :type method: str :param method: HTTP METHOD :type params: dict :param params: query :type data: dict ...
[ "def", "xml", "(", "self", ",", "url", ",", "method", "=", "'get'", ",", "params", "=", "None", ",", "data", "=", "None", ")", ":", "r", "=", "self", ".", "req", "(", "url", ",", "method", ",", "params", ",", "data", ")", "# this is required for av...
25.409091
17.863636
def get_next_types(self, n=None): """Gets the next set of ``Types`` in this list. The specified amount must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Type`` elements requested which must be less than or equal to ``av...
[ "def", "get_next_types", "(", "self", ",", "n", "=", "None", ")", ":", "if", "n", ">", "self", ".", "available", "(", ")", ":", "# !!! This is not quite as specified (see method docs) !!!", "raise", "IllegalState", "(", "'not enough elements available in this list'", ...
40.482759
20.965517
def cg(output, show, verbose, classname, methodname, descriptor, accessflag, no_isolated, apk): """ Create a call graph and export it into a graph format. classnames are found in the type "Lfoo/bar/bla;". Example: \b $ androguard cg ...
[ "def", "cg", "(", "output", ",", "show", ",", "verbose", ",", "classname", ",", "methodname", ",", "descriptor", ",", "accessflag", ",", "no_isolated", ",", "apk", ")", ":", "androcg_main", "(", "verbose", "=", "verbose", ",", "APK", "=", "apk", ",", "...
22.285714
17.642857
def process_event(event_filter, callback, timeout_callback, timeout, args, start_time=None): """ Start to watch one event. :param event_filter: :param callback: :param timeout_callback: :param timeout: :param args: :param start_time:...
[ "def", "process_event", "(", "event_filter", ",", "callback", ",", "timeout_callback", ",", "timeout", ",", "args", ",", "start_time", "=", "None", ")", ":", "try", ":", "events", "=", "event_filter", ".", "get_all_entries", "(", ")", "if", "events", ":", ...
28.058824
17.058824
def dirsWavFeatureExtraction(dirNames, mt_win, mt_step, st_win, st_step, compute_beat=False): ''' Same as dirWavFeatureExtraction, but instead of a single dir it takes a list of paths as input and returns a list of feature matrices. EXAMPLE: [features, classNames] = a.dirsWavFeatureExtrac...
[ "def", "dirsWavFeatureExtraction", "(", "dirNames", ",", "mt_win", ",", "mt_step", ",", "st_win", ",", "st_step", ",", "compute_beat", "=", "False", ")", ":", "# feature extraction for each class:", "features", "=", "[", "]", "classNames", "=", "[", "]", "fileNa...
47.7
29.033333
def user_parse(data): """Parse information from the provider.""" yield 'id', data.get('uuid') yield 'username', data.get('username') yield 'last_name', data.get('display_name') links = data.get('links', {}) yield 'picture', links.get('avatar', {}).get('href') yiel...
[ "def", "user_parse", "(", "data", ")", ":", "yield", "'id'", ",", "data", ".", "get", "(", "'uuid'", ")", "yield", "'username'", ",", "data", ".", "get", "(", "'username'", ")", "yield", "'last_name'", ",", "data", ".", "get", "(", "'display_name'", ")...
44.5
9.75
def _jobresult(self, jobid, json=True, headers=None): """Poll the async job result. To be run via in a Thread, the result is put within the result list which is a hack. """ failures = 0 total_time = self.job_timeout or 2**30 remaining = timedelta(seconds=total_t...
[ "def", "_jobresult", "(", "self", ",", "jobid", ",", "json", "=", "True", ",", "headers", "=", "None", ")", ":", "failures", "=", "0", "total_time", "=", "self", ".", "job_timeout", "or", "2", "**", "30", "remaining", "=", "timedelta", "(", "seconds", ...
38.382716
19.098765
def reduced_formula(self): """ Returns a reduced formula string with appended charge. """ reduced_formula = super().reduced_formula charge = self._charge / self.get_reduced_composition_and_factor()[1] if charge > 0: if abs(charge) == 1: chg_str...
[ "def", "reduced_formula", "(", "self", ")", ":", "reduced_formula", "=", "super", "(", ")", ".", "reduced_formula", "charge", "=", "self", ".", "_charge", "/", "self", ".", "get_reduced_composition_and_factor", "(", ")", "[", "1", "]", "if", "charge", ">", ...
37.1
16.7
def addCity(self, fileName): """Add a JSON file and read the users. :param fileName: path to the JSON file. This file has to have a list of users, called users. :type fileName: str. """ with open(fileName) as data_file: data = load(data_file) for u in...
[ "def", "addCity", "(", "self", ",", "fileName", ")", ":", "with", "open", "(", "fileName", ")", "as", "data_file", ":", "data", "=", "load", "(", "data_file", ")", "for", "u", "in", "data", "[", "\"users\"", "]", ":", "if", "not", "any", "(", "d", ...
36.083333
13.5
def _as_label(self, index_or_label): """Convert index to label.""" if isinstance(index_or_label, str): return index_or_label if isinstance(index_or_label, numbers.Integral): return self.labels[index_or_label] else: raise ValueError(str(index_or_label) ...
[ "def", "_as_label", "(", "self", ",", "index_or_label", ")", ":", "if", "isinstance", "(", "index_or_label", ",", "str", ")", ":", "return", "index_or_label", "if", "isinstance", "(", "index_or_label", ",", "numbers", ".", "Integral", ")", ":", "return", "se...
42.75
12.625
def snip_line(line, max_width, split_at): """Shorten a line to a maximum length.""" if len(line) < max_width: return line return line[:split_at] + " … " \ + line[-(max_width - split_at - 3):]
[ "def", "snip_line", "(", "line", ",", "max_width", ",", "split_at", ")", ":", "if", "len", "(", "line", ")", "<", "max_width", ":", "return", "line", "return", "line", "[", ":", "split_at", "]", "+", "\" … \" \\", "+", "line", "[", "-", "(", "max_wid...
35.666667
6.833333
def release(self, force=False): """Release an exclusive lock on this integration task. Unless forcing, if we are not the current owners of the lock a Locked exception will be raised. """ D = self.__class__ collection = self.get_collection() identity = self.Lock() query = D.id == self if not ...
[ "def", "release", "(", "self", ",", "force", "=", "False", ")", ":", "D", "=", "self", ".", "__class__", "collection", "=", "self", ".", "get_collection", "(", ")", "identity", "=", "self", ".", "Lock", "(", ")", "query", "=", "D", ".", "id", "==",...
28.444444
24.62963
def list_firewall_rules(self, retrieve_all=True, **_params): """Fetches a list of all firewall rules for a project.""" # Pass filters in "params" argument to do_request return self.list('firewall_rules', self.firewall_rules_path, retrieve_all, **_params)
[ "def", "list_firewall_rules", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "# Pass filters in \"params\" argument to do_request", "return", "self", ".", "list", "(", "'firewall_rules'", ",", "self", ".", "firewall_rules_path", "...
49.833333
19
def find_datasets(self, dataset_name=None, **kwargs): """Finds and returns all datasets from the database which matches the requirement. In some case, the data in a dataset can be stored separately for better management. Parameters ---------- dataset_name : str The n...
[ "def", "find_datasets", "(", "self", ",", "dataset_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_fill_project_info", "(", "kwargs", ")", "if", "dataset_name", "is", "None", ":", "raise", "Exception", "(", "\"dataset_name is None, please...
37.405405
24.351351
def process(self, request, item): """Process a PayPal direct payment.""" warn_untested() from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = self.cleaned_data params['creditcardtype'] = self.fields['acct'].card_type params['expdate'] = self...
[ "def", "process", "(", "self", ",", "request", ",", "item", ")", ":", "warn_untested", "(", ")", "from", "paypal", ".", "pro", ".", "helpers", "import", "PayPalWPP", "wpp", "=", "PayPalWPP", "(", "request", ")", "params", "=", "self", ".", "cleaned_data"...
35.454545
16.545455
def is_device_virtual(self): """Returns if the device is physical or virtual. """ for ip in self.obj_dict: drvr_obj = self.obj_dict.get(ip).get('drvr_obj') ret = drvr_obj.is_device_virtual() # No way to pin a device as of now, so return the first # TODO(pa...
[ "def", "is_device_virtual", "(", "self", ")", ":", "for", "ip", "in", "self", ".", "obj_dict", ":", "drvr_obj", "=", "self", ".", "obj_dict", ".", "get", "(", "ip", ")", ".", "get", "(", "'drvr_obj'", ")", "ret", "=", "drvr_obj", ".", "is_device_virtua...
42.875
12.875
def update(old_template=None, old_version=None, new_template=None, new_version=None, enter_parameters=False): """Updates the temple project to the latest template Proceeeds in the following steps: 1. Ensure we are inside the project repository 2. Obtain the latest version of the package tem...
[ "def", "update", "(", "old_template", "=", "None", ",", "old_version", "=", "None", ",", "new_template", "=", "None", ",", "new_version", "=", "None", ",", "enter_parameters", "=", "False", ")", ":", "update_branch", "=", "temple", ".", "constants", ".", "...
47.49697
24.515152
def total_surface_energy(self): """ Total surface energy of the Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl) """ tot_surface_energy = 0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hk...
[ "def", "total_surface_energy", "(", "self", ")", ":", "tot_surface_energy", "=", "0", "for", "hkl", "in", "self", ".", "miller_energy_dict", ".", "keys", "(", ")", ":", "tot_surface_energy", "+=", "self", ".", "miller_energy_dict", "[", "hkl", "]", "*", "sel...
34.166667
14
def case(institute_id, case_name): """Return a variant.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) if case_obj is None: return abort(404) return Response(json_util.dumps(case_obj), mimetype='application/json')
[ "def", "case", "(", "institute_id", ",", "case_name", ")", ":", "institute_obj", ",", "case_obj", "=", "institute_and_case", "(", "store", ",", "institute_id", ",", "case_name", ")", "if", "case_obj", "is", "None", ":", "return", "abort", "(", "404", ")", ...
44.166667
18.666667
def deprecated_arg_names(arg_mapping): """ Decorator which marks a functions keyword arguments as deprecated. It will result in a warning being emitted when the deprecated keyword argument is used, and the function being called with the new argument. Parameters ---------- arg_mapping : dict...
[ "def", "deprecated_arg_names", "(", "arg_mapping", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "func_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "simplefilter", "(", "'...
39.65625
15.53125
def iter_entry_points(cls, target): """Yields the name, entry_point pairs of binary targets in this PythonArtifact.""" for name, binary_target in target.provided_binaries.items(): concrete_target = binary_target if not isinstance(concrete_target, PythonBinary) or concrete_target.entry_point is None:...
[ "def", "iter_entry_points", "(", "cls", ",", "target", ")", ":", "for", "name", ",", "binary_target", "in", "target", ".", "provided_binaries", ".", "items", "(", ")", ":", "concrete_target", "=", "binary_target", "if", "not", "isinstance", "(", "concrete_targ...
62.625
18.875
def is_topk(self, topk=10, reverse=False): """ Create an SArray indicating which elements are in the top k. Entries are '1' if the corresponding element in the current SArray is a part of the top k elements, and '0' if that corresponding element is not. Order is descending by de...
[ "def", "is_topk", "(", "self", ",", "topk", "=", "10", ",", "reverse", "=", "False", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "topk_index", "(", "topk", ",", "reverse", ...
30.038462
23.346154
def runserver(ctx, conf, port, foreground): """Run the fnExchange server""" config = read_config(conf) debug = config['conf'].get('debug', False) click.echo('Debug mode {0}.'.format('on' if debug else 'off')) port = port or config['conf']['server']['port'] app_settings = { 'debug': de...
[ "def", "runserver", "(", "ctx", ",", "conf", ",", "port", ",", "foreground", ")", ":", "config", "=", "read_config", "(", "conf", ")", "debug", "=", "config", "[", "'conf'", "]", ".", "get", "(", "'debug'", ",", "False", ")", "click", ".", "echo", ...
33.863636
21.545455
def get_segmentation(recording, annotations, internal_id=None): """ Parameters ---------- recording : A HandwrittenData object annotations : list of strings internal_id : string An identifier for the dataset, e.g. 'user1/200922-947-111.ink'. Returns ------- tuple : s...
[ "def", "get_segmentation", "(", "recording", ",", "annotations", ",", "internal_id", "=", "None", ")", ":", "global", "missing_stroke_segmentation", ",", "double_segmentation", "segmentation", "=", "[", "]", "symbol_stream", "=", "[", "]", "needed", "=", "list", ...
36.309524
17.404762
def _freq_parser(self, freq): """Parse timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() valid_keywords = [ "day...
[ "def", "_freq_parser", "(", "self", ",", "freq", ")", ":", "freq", "=", "freq", ".", "lower", "(", ")", ".", "strip", "(", ")", "valid_keywords", "=", "[", "\"days\"", ",", "\"day\"", ",", "\"d\"", ",", "\"hours\"", ",", "\"hour\"", ",", "\"h\"", ","...
33.056604
16.754717
def fix_repeat_dt(dt_list, offset_s=0.001): """Add some small offset to remove duplicate times Needed for xarray interp, which expects monotonically increasing times """ idx = (np.diff(dt_list) == timedelta(0)) while np.any(idx): dt_list[idx.nonzero()[0] + 1] += timedelta(seconds=offset_s) ...
[ "def", "fix_repeat_dt", "(", "dt_list", ",", "offset_s", "=", "0.001", ")", ":", "idx", "=", "(", "np", ".", "diff", "(", "dt_list", ")", "==", "timedelta", "(", "0", ")", ")", "while", "np", ".", "any", "(", "idx", ")", ":", "dt_list", "[", "idx...
42
13
def frombinary(path, ext='bin', conf='conf.json', dtype=None, shape=None, skip=0, index=None, labels=None, engine=None, credentials=None): """ Load series data from flat binary files. Parameters ---------- path : string URI or local filesystem path Directory to load from, can be a URI strin...
[ "def", "frombinary", "(", "path", ",", "ext", "=", "'bin'", ",", "conf", "=", "'conf.json'", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "skip", "=", "0", ",", "index", "=", "None", ",", "labels", "=", "None", ",", "engine", "=", "...
35.067416
23.224719
def write(self, obj, value, merge=False): """ Returns object: full copy of new obj """ full = deepcopy(obj) frag = full parts, last = self.parts[:-1], self.parts[-1] for part in parts: if isinstance(frag, dict): frag = frag...
[ "def", "write", "(", "self", ",", "obj", ",", "value", ",", "merge", "=", "False", ")", ":", "full", "=", "deepcopy", "(", "obj", ")", "frag", "=", "full", "parts", ",", "last", "=", "self", ".", "parts", "[", ":", "-", "1", "]", ",", "self", ...
27.296296
12.259259
def use(self, url, name='mytable'): '''Changes the data provider >>> yql.use('http://myserver.com/mytables.xml') ''' self.yql_table_url = url self.yql_table_name = name return {'table url': url, 'table name': name}
[ "def", "use", "(", "self", ",", "url", ",", "name", "=", "'mytable'", ")", ":", "self", ".", "yql_table_url", "=", "url", "self", ".", "yql_table_name", "=", "name", "return", "{", "'table url'", ":", "url", ",", "'table name'", ":", "name", "}" ]
36.571429
11.428571
def default_index(func): """Decorator assuring the wrapped method may only run if we are the default repository index. This is as we rely on git commands that operate on that index only. """ @wraps(func) def check_default_index(self, *args, **kwargs): if self._file_path != self._index_path(...
[ "def", "default_index", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "check_default_index", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_file_path", "!=", "self", ".", "_index_path", "(", ")"...
39.142857
19.142857
def min(self): """Minimum value.""" if self._prop.fmin is None: return -_INF return self._prop.fmin(self._obj)
[ "def", "min", "(", "self", ")", ":", "if", "self", ".", "_prop", ".", "fmin", "is", "None", ":", "return", "-", "_INF", "return", "self", ".", "_prop", ".", "fmin", "(", "self", ".", "_obj", ")" ]
28.4
9.6
def execute(api): """Executes operation. Args: api: The base API object Returns: A response body object """ try: return api.execute() except Exception as exception: now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') _print_error('%s: Exception %s: %s' % (now, ...
[ "def", "execute", "(", "api", ")", ":", "try", ":", "return", "api", ".", "execute", "(", ")", "except", "Exception", "as", "exception", ":", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S.%f'", ")", "_print_error...
27.588235
20.235294
def read_sensor(self, device_id, sensor_uri): """Return sensor value based on sensor_uri.""" url = MINUT_DEVICES_URL + "/{device_id}/{sensor_uri}".format( device_id=device_id, sensor_uri=sensor_uri) res = self._request(url, request_type='GET', data={'limit': 1}) if not res.ge...
[ "def", "read_sensor", "(", "self", ",", "device_id", ",", "sensor_uri", ")", ":", "url", "=", "MINUT_DEVICES_URL", "+", "\"/{device_id}/{sensor_uri}\"", ".", "format", "(", "device_id", "=", "device_id", ",", "sensor_uri", "=", "sensor_uri", ")", "res", "=", "...
49.875
14.125
def connect( host="localhost", port=1113, discovery_host=None, discovery_port=2113, username=None, password=None, loop=None, name=None, selector=select_random, ) -> Client: """ Create a new client. Examples: Since the Client is an async context manager, we ca...
[ "def", "connect", "(", "host", "=", "\"localhost\"", ",", "port", "=", "1113", ",", "discovery_host", "=", "None", ",", "discovery_port", "=", "2113", ",", "username", "=", "None", ",", "password", "=", "None", ",", "loop", "=", "None", ",", "name", "=...
41.425743
27.693069
def main( argv ): """main program loop""" global output_dir try: opts, args = getopt.getopt( sys.argv[1:], \ "ht:o:p:", \ ["help", "title=", "output=", "prefix="] ) except getopt.GetoptError: usage() sy...
[ "def", "main", "(", "argv", ")", ":", "global", "output_dir", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "\"ht:o:p:\"", ",", "[", "\"help\"", ",", "\"title=\"", ",", "\"output=\"",...
24.245614
20.368421
def replace( self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void, ): """Creates a customized copy of the Parameter.""" if name is _void: name = self._name if kind is _void: kind = self._...
[ "def", "replace", "(", "self", ",", "name", "=", "_void", ",", "kind", "=", "_void", ",", "annotation", "=", "_void", ",", "default", "=", "_void", ",", "_partial_kwarg", "=", "_void", ",", ")", ":", "if", "name", "is", "_void", ":", "name", "=", "...
21.90625
19.3125
def Get(self,key): """Get alert by providing name, ID, or other unique key. If key is not unique and finds multiple matches only the first will be returned """ for alert in self.alerts: if alert.id == key: return(alert) elif alert.name == key: return(alert)
[ "def", "Get", "(", "self", ",", "key", ")", ":", "for", "alert", "in", "self", ".", "alerts", ":", "if", "alert", ".", "id", "==", "key", ":", "return", "(", "alert", ")", "elif", "alert", ".", "name", "==", "key", ":", "return", "(", "alert", ...
26.8
16.5
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['day'] = self._day json_dict['mon'] = self._mon json_dict['year'] = self._year return json.dumps(json_dict)
[ "def", "to_json", "(", "self", ")", ":", "json_dict", "=", "self", ".", "to_json_basic", "(", ")", "json_dict", "[", "'day'", "]", "=", "self", ".", "_day", "json_dict", "[", "'mon'", "]", "=", "self", ".", "_mon", "json_dict", "[", "'year'", "]", "=...
27.333333
6.222222
def singularize(plural): """Convert plural word to its singular form. Args: plural: A word in its plural form. Returns: The word in its singular form. """ if plural in UNCOUNTABLES: return plural for i in IRREGULAR: if i[1] == plural: return i[0] ...
[ "def", "singularize", "(", "plural", ")", ":", "if", "plural", "in", "UNCOUNTABLES", ":", "return", "plural", "for", "i", "in", "IRREGULAR", ":", "if", "i", "[", "1", "]", "==", "plural", ":", "return", "i", "[", "0", "]", "for", "i", "in", "SINGUL...
25.529412
13.823529
def _get_general_coverage(data, itype): """Retrieve coverage information from new shared SV bins. """ work_bam = dd.get_align_bam(data) or dd.get_work_bam(data) return [{"bam": work_bam, "file": tz.get_in(["depth", "bins", "target"], data), "cnntype": "target", "itype": itype, "sample": dd....
[ "def", "_get_general_coverage", "(", "data", ",", "itype", ")", ":", "work_bam", "=", "dd", ".", "get_align_bam", "(", "data", ")", "or", "dd", ".", "get_work_bam", "(", "data", ")", "return", "[", "{", "\"bam\"", ":", "work_bam", ",", "\"file\"", ":", ...
64.375
26.125
def _connect(self): """ Connect to the EC2 cloud provider. :return: :py:class:`boto.ec2.connection.EC2Connection` :raises: Generic exception on error """ # check for existing connection if self._ec2_connection: return self._ec2_connection try...
[ "def", "_connect", "(", "self", ")", ":", "# check for existing connection", "if", "self", ".", "_ec2_connection", ":", "return", "self", ".", "_ec2_connection", "try", ":", "log", ".", "debug", "(", "\"Connecting to EC2 endpoint %s\"", ",", "self", ".", "_ec2host...
37.784314
16.921569
def rename(self, old, new): """Rename the old schema/identifier to the new schema/identifier and update references. If the new schema/identifier is already present, that is an error. If the schema/identifier key is absent, we only debug log and return, assuming it's a temp table...
[ "def", "rename", "(", "self", ",", "old", ",", "new", ")", ":", "old_key", "=", "_make_key", "(", "old", ")", "new_key", "=", "_make_key", "(", "new", ")", "logger", ".", "debug", "(", "'Renaming relation {!s} to {!s}'", ".", "format", "(", "old_key", ",...
37.933333
20.833333
def send_capabilties_request(self, vehicle, name, m): '''An alias for send_capabilities_request. The word "capabilities" was misspelled in previous versions of this code. This is simply an alias to send_capabilities_request using the legacy name. ''' return self.send_capabilitie...
[ "def", "send_capabilties_request", "(", "self", ",", "vehicle", ",", "name", ",", "m", ")", ":", "return", "self", ".", "send_capabilities_request", "(", "vehicle", ",", "name", ",", "m", ")" ]
48.714286
28.428571
def get_collection(self, session, query, api_key): """ Fetch a collection of resources of a specified type. :param session: SQLAlchemy session :param query: Dict of query args :param api_type: The type of the model """ model = self._fetch_model(api_key) i...
[ "def", "get_collection", "(", "self", ",", "session", ",", "query", ",", "api_key", ")", ":", "model", "=", "self", ".", "_fetch_model", "(", "api_key", ")", "include", "=", "self", ".", "_parse_include", "(", "query", ".", "get", "(", "'include'", ",", ...
32.15625
19.53125
def parse_args(): '''Parse command line arguments''' parser = argparse.ArgumentParser( description='Morphology feature plotter', epilog='Note: Makes plots of various features and superimposes\ input distributions. Plots are saved to PDF file.', formatter_class=argparse.ArgumentDe...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Morphology feature plotter'", ",", "epilog", "=", "'Note: Makes plots of various features and superimposes\\\n input distributions. Plots are saved to PDF file.'"...
38.684211
16.578947
def _gccalc(lon, lat, azimuth, maxdist=None): """ Original javascript on http://williams.best.vwh.net/gccalc.htm Translated into python by Thomas Lecocq This function is a black box, because trigonometry is difficult """ glat1 = lat * np.pi / 180. glon1 = lon * np.pi / 180. s = maxd...
[ "def", "_gccalc", "(", "lon", ",", "lat", ",", "azimuth", ",", "maxdist", "=", "None", ")", ":", "glat1", "=", "lat", "*", "np", ".", "pi", "/", "180.", "glon1", "=", "lon", "*", "np", ".", "pi", "/", "180.", "s", "=", "maxdist", "/", "1.852243...
27.681818
18.439394
def stop(self): ''' Stop the fuzzing session ''' self.logger.info('Stopping client fuzzer') self._target_control_thread.stop() self.target.signal_mutated() super(ClientFuzzer, self).stop()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "'Stopping client fuzzer'", ")", "self", ".", "_target_control_thread", ".", "stop", "(", ")", "self", ".", "target", ".", "signal_mutated", "(", ")", "super", "(", "ClientFuzze...
29.625
13.375
def handle_fobj(backend, f, **kwargs): """ Handle a file-like object. Called by `get()` when provided a file-like. This function will prefer the backend's `handle_fobj()` if one is provided. Otherwise, it will write the data to a temporary file and call `handle_path()`. """ if not is_binary...
[ "def", "handle_fobj", "(", "backend", ",", "f", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_binary", "(", "f", ")", ":", "raise", "AssertionError", "(", "'File must be opened in binary mode.'", ")", "if", "callable", "(", "getattr", "(", "backend", ...
35.71875
19.65625