text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_roles_for_permission(permission, brain_or_object): """Return the roles of the permission that is granted on the object Code extracted from `IRoleManager.rolesOfPermission` :param permission: The permission to get the roles :param brain_or_object: Catalog brain or object :returns: List of r...
[ "def", "get_roles_for_permission", "(", "permission", ",", "brain_or_object", ")", ":", "obj", "=", "api", ".", "get_object", "(", "brain_or_object", ")", "valid_roles", "=", "get_valid_roles_for", "(", "obj", ")", "for", "item", "in", "obj", ".", "ac_inherited_...
45.363636
0.000981
def get_vector(self, l_motor: float, r_motor: float) -> typing.Tuple[float, float]: """ Given motor values, retrieves the vector of (distance, speed) for your robot :param l_motor: Left motor value (-1 to 1); -1 is forward :param r_motor: Right motor value (-1 ...
[ "def", "get_vector", "(", "self", ",", "l_motor", ":", "float", ",", "r_motor", ":", "float", ")", "->", "typing", ".", "Tuple", "[", "float", ",", "float", "]", ":", "if", "self", ".", "deadzone", ":", "l_motor", "=", "self", ".", "deadzone", "(", ...
33.826087
0.00875
def overloaded_constants(type_, __doc__=None): """A factory for transformers that apply functions to literals. Parameters ---------- type_ : type The type to overload. __doc__ : str, optional Docstring for the generated transformer. Returns ------- transformer : subclas...
[ "def", "overloaded_constants", "(", "type_", ",", "__doc__", "=", "None", ")", ":", "typename", "=", "type_", ".", "__name__", "if", "typename", ".", "endswith", "(", "'x'", ")", ":", "typename", "+=", "'es'", "elif", "not", "typename", ".", "endswith", ...
25.03125
0.001202
def data_to_string(self): """Returns a UTF8 string with the QR Code's data""" # FIX-ME: if we don't add the BOM_UTF8 char, QtQR doesn't decode # correctly; but if we add it, mobile apps don't.- # Apparently is a zbar bug. if self.data_type == 'text': return BOM_UTF8 +...
[ "def", "data_to_string", "(", "self", ")", ":", "# FIX-ME: if we don't add the BOM_UTF8 char, QtQR doesn't decode", "# correctly; but if we add it, mobile apps don't.-", "# Apparently is a zbar bug.", "if", "self", ".", "data_type", "==", "'text'", ":", "return", "BOM_UTF8", "+",...
53.888889
0.008114
def get_region(region_name, **kw_params): """ Find and return a :class:`boto.regioninfo.RegionInfo` object given a region name. :type: str :param: The name of the region. :rtype: :class:`boto.regioninfo.RegionInfo` :return: The RegionInfo object for the given region or None if ...
[ "def", "get_region", "(", "region_name", ",", "*", "*", "kw_params", ")", ":", "for", "region", "in", "regions", "(", "*", "*", "kw_params", ")", ":", "if", "region", ".", "name", "==", "region_name", ":", "return", "region", "return", "None" ]
29.375
0.002062
def to_netcdf(self, path=None, mode='w', format=None, group=None, engine=None, encoding=None, unlimited_dims=None, compute=True): """Write dataset contents to a netCDF file. Parameters ---------- path : str, Path or file-like object, optional ...
[ "def", "to_netcdf", "(", "self", ",", "path", "=", "None", ",", "mode", "=", "'w'", ",", "format", "=", "None", ",", "group", "=", "None", ",", "engine", "=", "None", ",", "encoding", "=", "None", ",", "unlimited_dims", "=", "None", ",", "compute", ...
53.232877
0.001011
def modify(self, **params): """https://developers.coinbase.com/api/v2#update-current-user""" data = self.api_client.update_current_user(**params) self.update(data) return data
[ "def", "modify", "(", "self", ",", "*", "*", "params", ")", ":", "data", "=", "self", ".", "api_client", ".", "update_current_user", "(", "*", "*", "params", ")", "self", ".", "update", "(", "data", ")", "return", "data" ]
40.6
0.009662
def ucase(inchar, lenout=None): """ Convert the characters in a string to uppercase. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ucase_c.html :param inchar: Input string. :type inchar: str :param lenout: Optional Maximum length of output string. :type lenout: int :return: O...
[ "def", "ucase", "(", "inchar", ",", "lenout", "=", "None", ")", ":", "if", "lenout", "is", "None", ":", "lenout", "=", "len", "(", "inchar", ")", "+", "1", "inchar", "=", "stypes", ".", "stringToCharP", "(", "inchar", ")", "outchar", "=", "stypes", ...
31.1
0.00156
def effective_n(x): """ Returns estimate of the effective sample size of a set of traces. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, an...
[ "def", "effective_n", "(", "x", ")", ":", "if", "np", ".", "shape", "(", "x", ")", "<", "(", "2", ",", ")", ":", "raise", "ValueError", "(", "'Calculation of effective sample size requires multiple chains of the same length.'", ")", "try", ":", "m", ",", "n", ...
30.392857
0.015367
def cancel_reason(self, cancel_reason): """ Sets the cancel_reason of this OrderFulfillmentPickupDetails. A description of why the pickup was canceled. Max length is 100 characters. :param cancel_reason: The cancel_reason of this OrderFulfillmentPickupDetails. :type: str ...
[ "def", "cancel_reason", "(", "self", ",", "cancel_reason", ")", ":", "if", "cancel_reason", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `cancel_reason`, must not be `None`\"", ")", "if", "len", "(", "cancel_reason", ")", ">", "100", ":", "r...
40.733333
0.0096
def size(self): """ Returns the number of connections cached by the pool. """ return sum(q.qsize() for q in self._connections.values()) + len(self._fairies)
[ "def", "size", "(", "self", ")", ":", "return", "sum", "(", "q", ".", "qsize", "(", ")", "for", "q", "in", "self", ".", "_connections", ".", "values", "(", ")", ")", "+", "len", "(", "self", ".", "_fairies", ")" ]
56.666667
0.017442
def _matches(self, entities=None, extensions=None, regex_search=False): """ Checks whether the file matches all of the passed entities and extensions. Args: entities (dict): A dictionary of entity names -> regex patterns. extensions (str, list): One or more file ...
[ "def", "_matches", "(", "self", ",", "entities", "=", "None", ",", "extensions", "=", "None", ",", "regex_search", "=", "False", ")", ":", "if", "extensions", "is", "not", "None", ":", "extensions", "=", "map", "(", "re", ".", "escape", ",", "listify",...
34.7
0.001121
def copyTo(self, screen): """ Creates a new point with the same offset on the target screen as this point has on the current screen """ from .RegionMatching import Screen if not isinstance(screen, Screen): screen = RegionMatching.Screen(screen) return screen.getTopLef...
[ "def", "copyTo", "(", "self", ",", "screen", ")", ":", "from", ".", "RegionMatching", "import", "Screen", "if", "not", "isinstance", "(", "screen", ",", "Screen", ")", ":", "screen", "=", "RegionMatching", ".", "Screen", "(", "screen", ")", "return", "sc...
53
0.01061
def make_shape(self): """ Make shape object """ # In DS9, ellipse can also represents an elliptical annulus # For elliptical annulus angle is optional. if self.region_type == 'ellipse': self.coord[2:] = [x * 2 for x in self.coord[2:]] if len(self.c...
[ "def", "make_shape", "(", "self", ")", ":", "# In DS9, ellipse can also represents an elliptical annulus", "# For elliptical annulus angle is optional.", "if", "self", ".", "region_type", "==", "'ellipse'", ":", "self", ".", "coord", "[", "2", ":", "]", "=", "[", "x",...
38.0625
0.002402
def get_metadata(): """ Get metadata of symbols, like their tags, id on write-math.com, LaTeX command and unicode code point. Returns ------- dict """ misc_path = pkg_resources.resource_filename('hwrt', 'misc/') wm_symbols = os.path.join(misc_path, 'wm_symbols.csv') wm_tags = os...
[ "def", "get_metadata", "(", ")", ":", "misc_path", "=", "pkg_resources", ".", "resource_filename", "(", "'hwrt'", ",", "'misc/'", ")", "wm_symbols", "=", "os", ".", "path", ".", "join", "(", "misc_path", ",", "'wm_symbols.csv'", ")", "wm_tags", "=", "os", ...
34.3125
0.001773
def generate(self, file, validatedata = None, inputdata=None, user = None): """Convert the template into instantiated metadata, validating the data in the process and returning errors otherwise. inputdata is a dictionary-compatible structure, such as the relevant postdata. Return (success, metadata, parameters...
[ "def", "generate", "(", "self", ",", "file", ",", "validatedata", "=", "None", ",", "inputdata", "=", "None", ",", "user", "=", "None", ")", ":", "metadata", "=", "{", "}", "if", "not", "validatedata", ":", "assert", "inputdata", "errors", ",", "parame...
45.931034
0.011765
def update_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Update DCNM OUT partition service node IP address and result. """ res = fw_const.DCNM_OUT_PART_UPDATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: ret = self._update_partition...
[ "def", "update_dcnm_out_part", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "res", "=", "fw_const", ".", "DCNM_OUT_PART_UPDATE_SUCCESS", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "...
47.5
0.002294
def _extract_table_root(d, current, pc): """ Extract data from the root level of a paleoData table. :param dict d: paleoData table :param dict current: Current root data :param str pc: paleoData or chronData :return dict current: Current root data """ logger_ts.info("enter extract_table_...
[ "def", "_extract_table_root", "(", "d", ",", "current", ",", "pc", ")", ":", "logger_ts", ".", "info", "(", "\"enter extract_table_root\"", ")", "try", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", "...
33.375
0.001821
def datasets_list_files(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """List dataset files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_list_files(owner_slug,...
[ "def", "datasets_list_files", "(", "self", ",", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retu...
47.047619
0.001984
def keypair_setup(): """Creates keypair if necessary, saves private key locally, returns contents of private key file.""" os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION) keypair_name = u.get_keypair_name() keypair = u.get_keypair_dict().get(keypair_name, None) keypair_fn = u.get_keypair_fn() if keypair:...
[ "def", "keypair_setup", "(", ")", ":", "os", ".", "system", "(", "'mkdir -p '", "+", "u", ".", "PRIVATE_KEY_LOCATION", ")", "keypair_name", "=", "u", ".", "get_keypair_name", "(", ")", "keypair", "=", "u", ".", "get_keypair_dict", "(", ")", ".", "get", "...
39.862069
0.009291
def final_mass_from_initial(mass1, mass2, spin1x=0., spin1y=0., spin1z=0., spin2x=0., spin2y=0., spin2z=0., approximant='SEOBNRv4'): """Estimates the final mass from the given initial parameters. This uses the fits used by the EOBNR models for converting ...
[ "def", "final_mass_from_initial", "(", "mass1", ",", "mass2", ",", "spin1x", "=", "0.", ",", "spin1y", "=", "0.", ",", "spin1z", "=", "0.", ",", "spin2x", "=", "0.", ",", "spin2y", "=", "0.", ",", "spin2z", "=", "0.", ",", "approximant", "=", "'SEOBN...
40.842105
0.000629
def read_fastq(filename): """ return a stream of FASTQ entries, handling gzipped and empty files """ if not filename: return itertools.cycle((None,)) if filename == "-": filename_fh = sys.stdin elif filename.endswith('gz'): if is_python3: filename_fh = gzip.op...
[ "def", "read_fastq", "(", "filename", ")", ":", "if", "not", "filename", ":", "return", "itertools", ".", "cycle", "(", "(", "None", ",", ")", ")", "if", "filename", "==", "\"-\"", ":", "filename_fh", "=", "sys", ".", "stdin", "elif", "filename", ".", ...
31.1875
0.001946
def _sort_shared_logical_disks(logical_disks): """Sort the logical disks based on the following conditions. When the share_physical_disks is True make sure we create the volume which needs more disks first. This avoids the situation of insufficient disks for some logical volume request. For exampl...
[ "def", "_sort_shared_logical_disks", "(", "logical_disks", ")", ":", "is_shared", "=", "(", "lambda", "x", ":", "True", "if", "(", "'share_physical_disks'", "in", "x", "and", "x", "[", "'share_physical_disks'", "]", ")", "else", "False", ")", "num_of_disks", "...
44.385542
0.000266
def _combine_hash_arrays(arrays, num_items): """ Parameters ---------- arrays : generator num_items : int Should be the same as CPython's tupleobject.c """ try: first = next(arrays) except StopIteration: return np.array([], dtype=np.uint64) arrays = itertools.ch...
[ "def", "_combine_hash_arrays", "(", "arrays", ",", "num_items", ")", ":", "try", ":", "first", "=", "next", "(", "arrays", ")", "except", "StopIteration", ":", "return", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "np", ".", "uint64", ")", ...
25.423077
0.001458
def build_filters_and_sizers(self, ppoi_value, create_on_demand): """Build the filters and sizers for a field.""" name = self.name if not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary( name, ...
[ "def", "build_filters_and_sizers", "(", "self", ",", "ppoi_value", ",", "create_on_demand", ")", ":", "name", "=", "self", ".", "name", "if", "not", "name", "and", "self", ".", "field", ".", "placeholder_image_name", ":", "name", "=", "self", ".", "field", ...
33.307692
0.002245
def loadCurve(data, groups, thresholds, absvals, fs, xlabels): """Accepts a data set from a whole test, averages reps and re-creates the progress plot as the same as it was during live plotting. Number of thresholds must match the size of the channel dimension""" xlims = (xlabels[0], xl...
[ "def", "loadCurve", "(", "data", ",", "groups", ",", "thresholds", ",", "absvals", ",", "fs", ",", "xlabels", ")", ":", "xlims", "=", "(", "xlabels", "[", "0", "]", ",", "xlabels", "[", "-", "1", "]", ")", "pw", "=", "ProgressWidget", "(", "groups"...
42.272727
0.01367
def create_contentkey_authorization_policy_options(access_token, key_delivery_type="2", \ name="HLS Open Authorization Policy", key_restriction_type="0"): '''Create Media Service Content Key Authorization Policy Options. Args: access_token (str): A valid Azure authentication token. key_delivery...
[ "def", "create_contentkey_authorization_policy_options", "(", "access_token", ",", "key_delivery_type", "=", "\"2\"", ",", "name", "=", "\"HLS Open Authorization Policy\"", ",", "key_restriction_type", "=", "\"0\"", ")", ":", "path", "=", "'/ContentKeyAuthorizationPolicyOptio...
39.423077
0.01619
def resultsperpage(self, value): """ Set the number of results that will be retrieved by the request. :param value: 'resultsperpage' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object ...
[ "def", "resultsperpage", "(", "self", ",", "value", ")", ":", "instance", "=", "copy", "(", "self", ")", "instance", ".", "_filters", ".", "append", "(", "{", "'resultsperpage'", ":", "value", "}", ")", "return", "instance" ]
29.866667
0.010823
def parse(self): """ Return the list of string of all the decorators found """ self._parse(self.method) return list(set([deco for deco in self.decos if deco]))
[ "def", "parse", "(", "self", ")", ":", "self", ".", "_parse", "(", "self", ".", "method", ")", "return", "list", "(", "set", "(", "[", "deco", "for", "deco", "in", "self", ".", "decos", "if", "deco", "]", ")", ")" ]
32.333333
0.01005
def _render_objects(self, items, attributes=None, datatype='object'): """Renders an HTML table with the specified list of objects. Args: items: the iterable collection of objects to render. attributes: the optional list of properties or keys to render. datatype: the type of data; one of 'obje...
[ "def", "_render_objects", "(", "self", ",", "items", ",", "attributes", "=", "None", ",", "datatype", "=", "'object'", ")", ":", "if", "not", "items", ":", "return", "if", "datatype", "==", "'chartdata'", ":", "if", "not", "attributes", ":", "attributes", ...
37.611111
0.012476
def strip_masked(fasta, min_len, print_masked): """ remove masked regions from fasta file as long as they are longer than min_len """ for seq in parse_fasta(fasta): nm, masked = parse_masked(seq, min_len) nm = ['%s removed_masked >=%s' % (seq[0], min_len), ''.join(nm)] yield ...
[ "def", "strip_masked", "(", "fasta", ",", "min_len", ",", "print_masked", ")", ":", "for", "seq", "in", "parse_fasta", "(", "fasta", ")", ":", "nm", ",", "masked", "=", "parse_masked", "(", "seq", ",", "min_len", ")", "nm", "=", "[", "'%s removed_masked ...
39.461538
0.001905
def ndd_prefix_for_region(region_code, strip_non_digits): """Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set strip_non_digits to True to strip symbols like "~" (which indicates a wait for a dialling tone) from th...
[ "def", "ndd_prefix_for_region", "(", "region_code", ",", "strip_non_digits", ")", ":", "if", "region_code", "is", "None", ":", "return", "None", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code", ".", "upper", "(", ")", ",", "None"...
43.909091
0.000675
def auth_in_stage1(self,stanza): """Handle the first stage (<iq type='get'/>) of legacy ("plain" or "digest") authentication. [server only]""" self.lock.acquire() try: if "plain" not in self.auth_methods and "digest" not in self.auth_methods: iq=stanz...
[ "def", "auth_in_stage1", "(", "self", ",", "stanza", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "if", "\"plain\"", "not", "in", "self", ".", "auth_methods", "and", "\"digest\"", "not", "in", "self", ".", "auth_methods", ":", "...
35.458333
0.017162
def update_gradients_diag(self, dL_dKdiag, X): """derivative of the diagonal of the covariance matrix with respect to the parameters.""" self.variance.gradient = np.sum(dL_dKdiag) self.period.gradient = 0 self.lengthscale.gradient = 0
[ "def", "update_gradients_diag", "(", "self", ",", "dL_dKdiag", ",", "X", ")", ":", "self", ".", "variance", ".", "gradient", "=", "np", ".", "sum", "(", "dL_dKdiag", ")", "self", ".", "period", ".", "gradient", "=", "0", "self", ".", "lengthscale", "."...
52.4
0.011278
def denormalized(self): """ THE INTERNAL STRUCTURE FOR THE COLUMN METADATA IS VERY DIFFERENT FROM THE DENORMALIZED PERSPECITVE. THIS PROVIDES THAT PERSPECTIVE FOR QUERIES """ with self.locker: self._update_meta() output = [ { ...
[ "def", "denormalized", "(", "self", ")", ":", "with", "self", ".", "locker", ":", "self", ".", "_update_meta", "(", ")", "output", "=", "[", "{", "\"table\"", ":", "c", ".", "es_index", ",", "\"name\"", ":", "untype_path", "(", "c", ".", "name", ")",...
36.969697
0.002396
def erract(op, lenout, action=None): """ Retrieve or set the default error action. spiceypy sets the default error action to "report" on init. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/erract_c.html :param op: peration, "GET" or "SET". :type op: str :param lenout: Length of l...
[ "def", "erract", "(", "op", ",", "lenout", ",", "action", "=", "None", ")", ":", "if", "action", "is", "None", ":", "action", "=", "\"\"", "lenout", "=", "ctypes", ".", "c_int", "(", "lenout", ")", "op", "=", "stypes", ".", "stringToCharP", "(", "o...
32.958333
0.001229
def get_nickname(userid): """Return a Future for a nickname from an account.""" account = yield get_account(userid) if not account: nickname = 'Unregistered' else: nickname = account.nickname or account.email raise ndb.Return(nickname)
[ "def", "get_nickname", "(", "userid", ")", ":", "account", "=", "yield", "get_account", "(", "userid", ")", "if", "not", "account", ":", "nickname", "=", "'Unregistered'", "else", ":", "nickname", "=", "account", ".", "nickname", "or", "account", ".", "ema...
30.75
0.023715
def delete(self, **params): """Return a deferred.""" d = self.request('delete', self.instance_url(), params) return d.addCallback(self.refresh_from).addCallback(lambda _: self)
[ "def", "delete", "(", "self", ",", "*", "*", "params", ")", ":", "d", "=", "self", ".", "request", "(", "'delete'", ",", "self", ".", "instance_url", "(", ")", ",", "params", ")", "return", "d", ".", "addCallback", "(", "self", ".", "refresh_from", ...
49.25
0.01
def diff_with_target(self, binary_im): """ Creates a color image to visualize the overlap between two images. Nonzero pixels that match in both images are green. Nonzero pixels of this image that aren't in the other image are yellow Nonzero pixels of the other image that aren't in this i...
[ "def", "diff_with_target", "(", "self", ",", "binary_im", ")", ":", "red", "=", "np", ".", "array", "(", "[", "BINARY_IM_MAX_VAL", ",", "0", ",", "0", "]", ")", "yellow", "=", "np", ".", "array", "(", "[", "BINARY_IM_MAX_VAL", ",", "BINARY_IM_MAX_VAL", ...
47.185185
0.001538
def _advapi32_interpret_dsa_key_blob(bit_size, public_blob, private_blob): """ Takes a CryptoAPI DSS private key blob and converts it into the ASN.1 structures for the public and private keys :param bit_size: The integer bit size of the key :param public_blob: A byte string of the ...
[ "def", "_advapi32_interpret_dsa_key_blob", "(", "bit_size", ",", "public_blob", ",", "private_blob", ")", ":", "len1", "=", "20", "len2", "=", "bit_size", "//", "8", "q_offset", "=", "len2", "g_offset", "=", "q_offset", "+", "len1", "x_offset", "=", "g_offset"...
28.677966
0.000571
def objects_for_push_notification(notification): """Decode a push notification with the given body XML. Returns a dictionary containing the constituent objects of the push notification. The kind of push notification is given in the ``"type"`` member of the returned dictionary. """ notification...
[ "def", "objects_for_push_notification", "(", "notification", ")", ":", "notification_el", "=", "ElementTree", ".", "fromstring", "(", "notification", ")", "objects", "=", "{", "'type'", ":", "notification_el", ".", "tag", "}", "for", "child_el", "in", "notificatio...
36.866667
0.001764
def userstream_user(self, delegate, stall_warnings=None, with_='followings', replies=None): """ Streams messages for a single user. https://dev.twitter.com/docs/api/1.1/get/user The ``stringify_friend_ids`` parameter is always set to ``'true'`` for consi...
[ "def", "userstream_user", "(", "self", ",", "delegate", ",", "stall_warnings", "=", "None", ",", "with_", "=", "'followings'", ",", "replies", "=", "None", ")", ":", "params", "=", "{", "'stringify_friend_ids'", ":", "'true'", "}", "set_bool_param", "(", "pa...
44.488372
0.001535
def plotSkymapCatalog(lon,lat,**kwargs): """ Plot a catalog of coordinates on a full-sky map. """ fig = plt.figure() ax = plt.subplot(111,projection=projection) drawSkymapCatalog(ax,lon,lat,**kwargs)
[ "def", "plotSkymapCatalog", "(", "lon", ",", "lat", ",", "*", "*", "kwargs", ")", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "plt", ".", "subplot", "(", "111", ",", "projection", "=", "projection", ")", "drawSkymapCatalog", "(", "ax"...
31
0.03139
def readKerningElement(self, kerningElement, instanceObject): """ Read the kerning element. :: Make kerning at the location and with the masters specified at the instance level. <kerning/> """ kerningLocation = self.locationFromElement(kerningElement) ...
[ "def", "readKerningElement", "(", "self", ",", "kerningElement", ",", "instanceObject", ")", ":", "kerningLocation", "=", "self", ".", "locationFromElement", "(", "kerningElement", ")", "instanceObject", ".", "addKerning", "(", "kerningLocation", ")" ]
32.636364
0.00813
def project_activity(index, start, end): """Compute the metrics for the project activity section of the enriched github pull requests index. Returns a dictionary containing a "metric" key. This key contains the metrics for this section. :param index: index object :param start: start date to ge...
[ "def", "project_activity", "(", "index", ",", "start", ",", "end", ")", ":", "results", "=", "{", "\"metrics\"", ":", "[", "SubmittedPRs", "(", "index", ",", "start", ",", "end", ")", ",", "ClosedPRs", "(", "index", ",", "start", ",", "end", ")", "]"...
30.052632
0.001698
def is_valid_article_slug(article, language, slug): """Validates given slug depending on settings. """ from ..models import Title qs = Title.objects.filter(slug=slug, language=language) if article.pk: qs = qs.exclude(Q(language=language) & Q(article=article)) qs = qs.exclude(articl...
[ "def", "is_valid_article_slug", "(", "article", ",", "language", ",", "slug", ")", ":", "from", ".", ".", "models", "import", "Title", "qs", "=", "Title", ".", "objects", ".", "filter", "(", "slug", "=", "slug", ",", "language", "=", "language", ")", "...
26.133333
0.002463
def recommend_for_record(self, record_id, depth=4, num_reco=10): """Calculate recommendations for record.""" data = calc_scores_for_node(self._graph, record_id, depth, num_reco) return data.Node.tolist(), data.Score.tolist()
[ "def", "recommend_for_record", "(", "self", ",", "record_id", ",", "depth", "=", "4", ",", "num_reco", "=", "10", ")", ":", "data", "=", "calc_scores_for_node", "(", "self", ".", "_graph", ",", "record_id", ",", "depth", ",", "num_reco", ")", "return", "...
61.25
0.008065
def vm_state(vm_=None): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_state <vm name> ''' with _get_x...
[ "def", "vm_state", "(", "vm_", "=", "None", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "info", "=", "{", "}", "if", "vm_", ":", "info", "[", "vm_", "]", "=", "_get_record_by_label", "(", "xapi", ",", "'VM'", ",", "vm_", ")"...
25.608696
0.001637
def quantile(self, prob=None, combine_method="interpolate", weights_column=None): """ Compute quantiles. :param List[float] prob: list of probabilities for which quantiles should be computed. :param str combine_method: for even samples this setting determines how to combine quantiles. T...
[ "def", "quantile", "(", "self", ",", "prob", "=", "None", ",", "combine_method", "=", "\"interpolate\"", ",", "weights_column", "=", "None", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "return", "self", "if", "prob", "is", "None", ":", "...
61
0.009415
def register_next_step_handler_by_chat_id(self, chat_id, callback, *args, **kwargs): """ Registers a callback function to be notified when new message arrives after `message`. Warning: In case `callback` as lambda function, saving next step handlers will not work. :param chat_id: T...
[ "def", "register_next_step_handler_by_chat_id", "(", "self", ",", "chat_id", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "chat_id", "in", "self", ".", "next_step_handlers", ".", "keys", "(", ")", ":", "self", ".", "next_step...
49.944444
0.008734
def flow(self, n, k, error=False, imaginary='nan'): r""" Calculate `v_n\{k\}`, the estimate of flow coefficient `v_n` from the `k`-particle cumulant. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate sta...
[ "def", "flow", "(", "self", ",", "n", ",", "k", ",", "error", "=", "False", ",", "imaginary", "=", "'nan'", ")", ":", "cnk", "=", "self", ".", "cumulant", "(", "n", ",", "k", ",", "error", "=", "error", ")", "if", "error", ":", "cnk", ",", "c...
30.930233
0.001458
def _FormatNotes(self, event): """Formats the notes. Args: event (EventObject): event. Returns: str: formatted notes field. """ inode = event.inode if inode is None: inode = '-' notes = getattr(event, 'notes', '') if not notes: display_name = getattr(event, '...
[ "def", "_FormatNotes", "(", "self", ",", "event", ")", ":", "inode", "=", "event", ".", "inode", "if", "inode", "is", "None", ":", "inode", "=", "'-'", "notes", "=", "getattr", "(", "event", ",", "'notes'", ",", "''", ")", "if", "not", "notes", ":"...
23.777778
0.008989
def dump_tracing_state(self, context): """ A debug tool to dump all threads tracing state """ _logger.x_debug("Dumping all threads Tracing state: (%s)" % context) _logger.x_debug(" self.tracing_enabled=%s" % self.tracing_enabled) _logger.x_debug(" self.execution_started=%s...
[ "def", "dump_tracing_state", "(", "self", ",", "context", ")", ":", "_logger", ".", "x_debug", "(", "\"Dumping all threads Tracing state: (%s)\"", "%", "context", ")", "_logger", ".", "x_debug", "(", "\" self.tracing_enabled=%s\"", "%", "self", ".", "tracing_enable...
61.322581
0.008286
def get_dict_for_forms(self): """ Build a dictionnary where searchable_fields are next to their model to be use in modelform_factory dico = { "str(model)" : { "model" : Model, "fields" = [] #searchable_fields which are attribut...
[ "def", "get_dict_for_forms", "(", "self", ")", ":", "magic_dico", "=", "field_to_dict", "(", "self", ".", "searchable_fields", ")", "dico", "=", "{", "}", "def", "dict_from_fields_r", "(", "mini_dict", ",", "dico", ",", "model", ")", ":", "\"\"\"\n ...
34.95
0.002088
def crawl(plugin): '''Performs a breadth-first crawl of all possible routes from the starting path. Will only visit a URL once, even if it is referenced multiple times in a plugin. Requires user interaction in between each fetch. ''' # TODO: use OrderedSet? paths_visited = set() paths_to...
[ "def", "crawl", "(", "plugin", ")", ":", "# TODO: use OrderedSet?", "paths_visited", "=", "set", "(", ")", "paths_to_visit", "=", "set", "(", "item", ".", "get_path", "(", ")", "for", "item", "in", "once", "(", "plugin", ")", ")", "while", "paths_to_visit"...
36.772727
0.001205
def dump_table_as_insert_sql(engine: Engine, table_name: str, fileobj: TextIO, wheredict: Dict[str, Any] = None, include_ddl: bool = False, multirow: bool = False) -> None: ...
[ "def", "dump_table_as_insert_sql", "(", "engine", ":", "Engine", ",", "table_name", ":", "str", ",", "fileobj", ":", "TextIO", ",", "wheredict", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "include_ddl", ":", "bool", "=", "False", ",", ...
40.611111
0.000267
def set_atoms(self, a): """Assign an atoms object.""" for c in self.calcs: if hasattr(c, "set_atoms"): c.set_atoms(a)
[ "def", "set_atoms", "(", "self", ",", "a", ")", ":", "for", "c", "in", "self", ".", "calcs", ":", "if", "hasattr", "(", "c", ",", "\"set_atoms\"", ")", ":", "c", ".", "set_atoms", "(", "a", ")" ]
31.4
0.012422
def _find_valid_name(self, initial_name): '''Finds a non-colliding name by optional postfixing''' return vaex.utils.find_valid_name(initial_name, used=self.get_column_names(hidden=True))
[ "def", "_find_valid_name", "(", "self", ",", "initial_name", ")", ":", "return", "vaex", ".", "utils", ".", "find_valid_name", "(", "initial_name", ",", "used", "=", "self", ".", "get_column_names", "(", "hidden", "=", "True", ")", ")" ]
66.666667
0.014851
def points_to_barycentric(triangles, points, method='cramer'): """ Find the barycentric coordinates of points relative to triangles. The Cramer's rule solution implements: http://blackpawn.com/texts/pointinpoly The cross product solution impl...
[ "def", "points_to_barycentric", "(", "triangles", ",", "points", ",", "method", "=", "'cramer'", ")", ":", "def", "method_cross", "(", ")", ":", "n", "=", "np", ".", "cross", "(", "edge_vectors", "[", ":", ",", "0", "]", ",", "edge_vectors", "[", ":", ...
37.743243
0.000349
def validate_arguments_type_of_function(param_type=None): """ Decorator to validate the <type> of arguments in the calling function are of the `param_type` class. if `param_type` is None, uses `param_type` as the class where it is used. Note: Use this decorator on the functions of the class. "...
[ "def", "validate_arguments_type_of_function", "(", "param_type", "=", "None", ")", ":", "def", "inner", "(", "function", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "type_", "=", "param_type", "or", "type...
31.625
0.000959
def with_legacy_dict(self, legacy_dict_object): """Configure a source that consumes the dict that where used on Lexicon 2.x""" warnings.warn(DeprecationWarning('Legacy configuration object has been used ' 'to load the ConfigResolver.')) return self.with_c...
[ "def", "with_legacy_dict", "(", "self", ",", "legacy_dict_object", ")", ":", "warnings", ".", "warn", "(", "DeprecationWarning", "(", "'Legacy configuration object has been used '", "'to load the ConfigResolver.'", ")", ")", "return", "self", ".", "with_config_source", "(...
74.4
0.013298
def isin(comps, values): """ Compute the isin boolean array Parameters ---------- comps : array-like values : array-like Returns ------- boolean array same length as comps """ if not is_list_like(comps): raise TypeError("only list-like objects are allowed to be pas...
[ "def", "isin", "(", "comps", ",", "values", ")", ":", "if", "not", "is_list_like", "(", "comps", ")", ":", "raise", "TypeError", "(", "\"only list-like objects are allowed to be passed\"", "\" to isin(), you passed a [{comps_type}]\"", ".", "format", "(", "comps_type", ...
33.322581
0.002351
def set_(key, value, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN): ''' Set a key on the memcached server, overwriting the value if it exists. CLI Example: .. code-block:: bash salt '*' memcache...
[ "def", "set_", "(", "key", ",", "value", ",", "host", "=", "DEFAULT_HOST", ",", "port", "=", "DEFAULT_PORT", ",", "time", "=", "DEFAULT_TIME", ",", "min_compress_len", "=", "DEFAULT_MIN_COMPRESS_LEN", ")", ":", "if", "not", "isinstance", "(", "time", ",", ...
31.227273
0.001412
def request(self, method, parameters, header): ''' Grooveshark API request ''' data = json.dumps({ 'parameters': parameters, 'method': method, 'header': header}) request = urllib.Request( 'https://grooveshark.com/more.php?%s' % (met...
[ "def", "request", "(", "self", ",", "method", ",", "parameters", ",", "header", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "'parameters'", ":", "parameters", ",", "'method'", ":", "method", ",", "'header'", ":", "header", "}", ")", "request...
41.35
0.002364
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2): """ save image """ data = data.asnumpy().transpose((0, 2, 3, 1)) datanp = np.clip( (data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8) x_dim = min(8, batch_size) y_dim = int(math.cei...
[ "def", "save_image", "(", "data", ",", "epoch", ",", "image_size", ",", "batch_size", ",", "output_dir", ",", "padding", "=", "2", ")", ":", "data", "=", "data", ".", "asnumpy", "(", ")", ".", "transpose", "(", "(", "0", ",", "2", ",", "3", ",", ...
44.913043
0.001896
def _validate_config(self): """ Validate configuration file. :raises: RuntimeError """ # while set().issubset() is easier, we want to tell the user the names # of any invalid keys bad_keys = [] for k in self._config.keys(): if k not in self._ex...
[ "def", "_validate_config", "(", "self", ")", ":", "# while set().issubset() is easier, we want to tell the user the names", "# of any invalid keys", "bad_keys", "=", "[", "]", "for", "k", "in", "self", ".", "_config", ".", "keys", "(", ")", ":", "if", "k", "not", ...
46.4
0.00149
def jhk_to_vmag(jmag,hmag,kmag): '''Converts given J, H, Ks mags to a V magnitude value. Parameters ---------- jmag,hmag,kmag : float 2MASS J, H, Ks mags of the object. Returns ------- float The converted V band magnitude. ''' return convert_constants(jmag,hmag,...
[ "def", "jhk_to_vmag", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "VJHK", ",", "VJH", ",", "VJK", ",", "VHK", ",", "VJ", ",", "VH", ",", "VK", ")" ]
20.238095
0.011236
def DeSelectByIndex(cls, index): ''' 通过索引,取消选择下拉框选项, @param index: 下拉框 索引 ''' try: Select(cls._element()).deselect_by_index(int(index)) except: return False
[ "def", "DeSelectByIndex", "(", "cls", ",", "index", ")", ":", "try", ":", "Select", "(", "cls", ".", "_element", "(", ")", ")", ".", "deselect_by_index", "(", "int", "(", "index", ")", ")", "except", ":", "return", "False" ]
27.625
0.013158
def _get_url(self, url): """ Returns normalized url. If schema is not given, would fall to filesystem (``file:///``) schema. """ url = str(url) if url != 'default' and not '://' in url: url = ':///'.join(('file', url)) return url
[ "def", "_get_url", "(", "self", ",", "url", ")", ":", "url", "=", "str", "(", "url", ")", "if", "url", "!=", "'default'", "and", "not", "'://'", "in", "url", ":", "url", "=", "':///'", ".", "join", "(", "(", "'file'", ",", "url", ")", ")", "ret...
32.111111
0.010101
def _get_zset(self, name, operation, create=False): """ Get (and maybe create) a sorted set by name. """ return self._get_by_type(name, operation, create, b'zset', SortedSet(), return_default=False)
[ "def", "_get_zset", "(", "self", ",", "name", ",", "operation", ",", "create", "=", "False", ")", ":", "return", "self", ".", "_get_by_type", "(", "name", ",", "operation", ",", "create", ",", "b'zset'", ",", "SortedSet", "(", ")", ",", "return_default",...
45.2
0.013043
def transform_using_this_method(original_sample): """ This function implements a log transformation on the data. """ # Copy the original sample new_sample = original_sample.copy() new_data = new_sample.data # Our transformation goes here new_data['Y2-A'] = log(new_data['Y2-A']) new_data = n...
[ "def", "transform_using_this_method", "(", "original_sample", ")", ":", "# Copy the original sample", "new_sample", "=", "original_sample", ".", "copy", "(", ")", "new_data", "=", "new_sample", ".", "data", "# Our transformation goes here", "new_data", "[", "'Y2-A'", "]...
36.909091
0.002404
def python_date_format(self, long_format=None, time_only=False): """This convert bika domain date format msgstrs to Python strftime format strings, by the same rules as ulocalized_time. XXX i18nl10n.py may change, and that is where this code is taken from. """ # get msgid ...
[ "def", "python_date_format", "(", "self", ",", "long_format", "=", "None", ",", "time_only", "=", "False", ")", ":", "# get msgid", "msgid", "=", "long_format", "and", "'date_format_long'", "or", "'date_format_short'", "if", "time_only", ":", "msgid", "=", "'tim...
47.033333
0.001389
def __click_dropdown_link_text(self, link_text, link_css): """ When a link may be hidden under a dropdown menu, use this. """ soup = self.get_beautiful_soup() drop_down_list = soup.select('[class*=dropdown]') for item in soup.select('[class*=HeaderMenu]'): drop_down_list.appe...
[ "def", "__click_dropdown_link_text", "(", "self", ",", "link_text", ",", "link_css", ")", ":", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "drop_down_list", "=", "soup", ".", "select", "(", "'[class*=dropdown]'", ")", "for", "item", "in", "soup",...
49.310345
0.001372
def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0): """ Get the right value from the scikit-tree """ # Regression if mode == 'regressor': return scikit_value[0] * scaling # Binary classification if n_classes == 2: # Decision tree ...
[ "def", "_get_value", "(", "scikit_value", ",", "mode", "=", "'regressor'", ",", "scaling", "=", "1.0", ",", "n_classes", "=", "2", ",", "tree_index", "=", "0", ")", ":", "# Regression", "if", "mode", "==", "'regressor'", ":", "return", "scikit_value", "[",...
30.444444
0.011792
def _init_class(self, cls, peg_rule, position, position_end=None, inherits=None, root=False, rule_type=RULE_MATCH): """ Setup meta-class special attributes, namespaces etc. This is called both for textX created classes as well as user classes. """ cls._tx_meta...
[ "def", "_init_class", "(", "self", ",", "cls", ",", "peg_rule", ",", "position", ",", "position_end", "=", "None", ",", "inherits", "=", "None", ",", "root", "=", "False", ",", "rule_type", "=", "RULE_MATCH", ")", ":", "cls", ".", "_tx_metamodel", "=", ...
34.228571
0.002435
def server_languages_and_locales(self): """ Show the available languages and locales """ response = self._post(self.apiurl + "/v2/server/languages_and_locales", data={'apikey': self.apikey}) return self._raise_or_extract(response)
[ "def", "server_languages_and_locales", "(", "self", ")", ":", "response", "=", "self", ".", "_post", "(", "self", ".", "apiurl", "+", "\"/v2/server/languages_and_locales\"", ",", "data", "=", "{", "'apikey'", ":", "self", ".", "apikey", "}", ")", "return", "...
37.857143
0.01107
def inspect_partitions(bucket): """Discover the partitions on a bucket via introspection. For large buckets which lack s3 inventories, salactus will attempt to process objects in parallel on the bucket by breaking the bucket into a separate keyspace partitions. It does this with a heurestic that at...
[ "def", "inspect_partitions", "(", "bucket", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "\"%(asctime)s: %(name)s:%(levelname)s %(message)s\"", ")", "logging", ".", "getLogger", "(", "'botocore'", ")", "."...
31.090909
0.000567
def sync_awards(**kwargs): """ Iterates over registered recipes and possibly creates awards. """ badges = kwargs.get('badges') excluded = kwargs.get('exclude_badges') disable_signals = kwargs.get('disable_signals') batch_size = kwargs.get('batch_size', None) db_read = kwargs.get('db_read...
[ "def", "sync_awards", "(", "*", "*", "kwargs", ")", ":", "badges", "=", "kwargs", ".", "get", "(", "'badges'", ")", "excluded", "=", "kwargs", ".", "get", "(", "'exclude_badges'", ")", "disable_signals", "=", "kwargs", ".", "get", "(", "'disable_signals'",...
29.6
0.001309
def configure_logger(simple_name, log_dest=None, detail_level=DEFAULT_LOG_DETAIL_LEVEL, log_filename=DEFAULT_LOG_FILENAME, connection=None, propagate=False): # pylint: disable=line-too-long """ Configure the pywbem loggers and optionally activat...
[ "def", "configure_logger", "(", "simple_name", ",", "log_dest", "=", "None", ",", "detail_level", "=", "DEFAULT_LOG_DETAIL_LEVEL", ",", "log_filename", "=", "DEFAULT_LOG_FILENAME", ",", "connection", "=", "None", ",", "propagate", "=", "False", ")", ":", "# pylint...
40.271739
0.000263
def _determine_base_url(document, page_url): """Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the ...
[ "def", "_determine_base_url", "(", "document", ",", "page_url", ")", ":", "for", "base", "in", "document", ".", "findall", "(", "\".//base\"", ")", ":", "href", "=", "base", ".", "get", "(", "\"href\"", ")", "if", "href", "is", "not", "None", ":", "ret...
40.647059
0.001414
def parse_qualifier_declaration(self, tup_tree): """ Parse QUALIFIER.DECLARATION element. :: <!ELEMENT QUALIFIER.DECLARATION (SCOPE?, (VALUE | VALUE.ARRAY)?)> <!ATTLIST QUALIFIER.DECLARATION %CIMName; %CIMType; #REQUIRED ...
[ "def", "parse_qualifier_declaration", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'QUALIFIER.DECLARATION'", ",", "(", "'NAME'", ",", "'TYPE'", ")", ",", "(", "'ISARRAY'", ",", "'ARRAYSIZE'", ",", "'OVERRIDABLE'", "...
39.765625
0.000767
def middleware(self, *args, **kwargs): """Decorate and register middleware :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: captures the keyword arguments passed in :type kwargs: dict(Any) :return: The middleware functi...
[ "def", "middleware", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'priority'", ",", "5", ")", "kwargs", ".", "setdefault", "(", "'relative'", ",", "None", ")", "kwargs", ".", "setdefault", "(", ...
39.791667
0.002045
def _process_streams(cls, streams): """ Processes a list of streams promoting Parameterized objects and methods to Param based streams. """ parameterizeds = defaultdict(set) valid, invalid = [], [] for s in streams: if isinstance(s, Stream): ...
[ "def", "_process_streams", "(", "cls", ",", "streams", ")", ":", "parameterizeds", "=", "defaultdict", "(", "set", ")", "valid", ",", "invalid", "=", "[", "]", ",", "[", "]", "for", "s", "in", "streams", ":", "if", "isinstance", "(", "s", ",", "Strea...
41.888889
0.001296
def p_ioport_head(self, p): 'ioport_head : sigtypes portname' p[0] = self.create_ioport(p[1], p[2], lineno=p.lineno(2)) p.set_lineno(0, p.lineno(1))
[ "def", "p_ioport_head", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "create_ioport", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "2", ")", ")", "p", ".", "set_lin...
42.25
0.011628
def switchport(self, **kwargs): """Set interface switchport status. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc) name (str): Name of interface. (1/0/5, 1/0/10, etc) enabled (bool): Is the interface enabled? (True...
[ "def", "switchport", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "enabled", "=", "kwargs", ".", "pop",...
43.612903
0.000723
def build_fred(self): '''Build a flat recurrent encoder-decoder dialogue model''' encoder = Encoder(data=self.dataset, config=self.model_config) decoder = Decoder(data=self.dataset, config=self.model_config, encoder=encoder) return EncoderDecoder(config=self.model_config, encod...
[ "def", "build_fred", "(", "self", ")", ":", "encoder", "=", "Encoder", "(", "data", "=", "self", ".", "dataset", ",", "config", "=", "self", ".", "model_config", ")", "decoder", "=", "Decoder", "(", "data", "=", "self", ".", "dataset", ",", "config", ...
56.875
0.012987
def main(): """main function""" parser = argparse.ArgumentParser( description='Github within the Command Line') group = parser.add_mutually_exclusive_group() group.add_argument('-n', '--url', type=str, help="Get repos from the user profile's URL") group.add_argument('-...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Github within the Command Line'", ")", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "group", ".", "add_argument", "(", "'-n'", ",...
30.276382
0.001286
def list_runners(*args): ''' List the runners loaded on the minion .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' sys.list_runners Runner names can be specified as globs. .. versionadded:: 2015.5.0 .. code-block:: bash salt '*' sys.list_runn...
[ "def", "list_runners", "(", "*", "args", ")", ":", "run_", "=", "salt", ".", "runner", ".", "Runner", "(", "__opts__", ")", "runners", "=", "set", "(", ")", "if", "not", "args", ":", "for", "func", "in", "run_", ".", "functions", ":", "runners", "....
22.605263
0.001116
def _make_request(self, uri, method, body, headers={}): """ Wraps the response and content returned by :mod:`httplib2` into a :class:`~webunit2.response.HttpResponse` object. ``uri``: Absolute URI to the resource. ``method``: Any supported HTTP methods de...
[ "def", "_make_request", "(", "self", ",", "uri", ",", "method", ",", "body", ",", "headers", "=", "{", "}", ")", ":", "response", ",", "content", "=", "self", ".", "_httpobj", ".", "request", "(", "uri", ",", "method", "=", "method", ",", "body", "...
37.272727
0.002378
def teardown_cluster(config_file, yes, workers_only, override_cluster_name): """Destroys all nodes of a Ray cluster described by a config json.""" config = yaml.load(open(config_file).read()) if override_cluster_name is not None: config["cluster_name"] = override_cluster_name validate_config(co...
[ "def", "teardown_cluster", "(", "config_file", ",", "yes", ",", "workers_only", ",", "override_cluster_name", ")", ":", "config", "=", "yaml", ".", "load", "(", "open", "(", "config_file", ")", ".", "read", "(", ")", ")", "if", "override_cluster_name", "is",...
32.5
0.000679
def waittillguinotexist(self, window_name, object_name='', guiTimeOut=30): """ Wait till a window does not exist. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object n...
[ "def", "waittillguinotexist", "(", "self", ",", "window_name", ",", "object_name", "=", "''", ",", "guiTimeOut", "=", "30", ")", ":", "timeout", "=", "0", "while", "timeout", "<", "guiTimeOut", ":", "if", "not", "self", ".", "guiexist", "(", "window_name",...
36.36
0.002144
def make_translations(unique_name, node): ''' Compute and store the title that should be displayed when linking to a given unique_name, eg in python when linking to test_greeter_greet() we want to display Test.Greeter.greet ''' introspectable = not node.attrib.get('introspectable') == '0' ...
[ "def", "make_translations", "(", "unique_name", ",", "node", ")", ":", "introspectable", "=", "not", "node", ".", "attrib", ".", "get", "(", "'introspectable'", ")", "==", "'0'", "if", "node", ".", "tag", "==", "core_ns", "(", "'member'", ")", ":", "__TR...
48.877193
0.001759
def console_output(msg, logging_msg=None): """Use instead of print, to clear the status information before printing""" assert isinstance(msg, bytes) assert isinstance(logging_msg, bytes) or logging_msg is None from polysh import remote_dispatcher remote_dispatcher.log(logging_msg or msg) if re...
[ "def", "console_output", "(", "msg", ",", "logging_msg", "=", "None", ")", ":", "assert", "isinstance", "(", "msg", ",", "bytes", ")", "assert", "isinstance", "(", "logging_msg", ",", "bytes", ")", "or", "logging_msg", "is", "None", "from", "polysh", "impo...
37.764706
0.00152
def time(self, intervals=1, *args, _show_progress=True, _print=True, _collect_garbage=False, **kwargs): """ Measures the execution time of :prop:_callables for @intervals @intervals: #int number of intervals to measure the execution time of the function for ...
[ "def", "time", "(", "self", ",", "intervals", "=", "1", ",", "*", "args", ",", "_show_progress", "=", "True", ",", "_print", "=", "True", ",", "_collect_garbage", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "reset", "(", ")", "sel...
46.538462
0.001619
def cleanup(self): "Purpose: Frees the GL resources for a render model" if self.m_glVertBuffer != 0: glDeleteBuffers(1, (self.m_glIndexBuffer,)) glDeleteVertexArrays( 1, (self.m_glVertArray,) ) glDeleteBuffers(1, (self.m_glVertBuffer,)) self.m_glInde...
[ "def", "cleanup", "(", "self", ")", ":", "if", "self", ".", "m_glVertBuffer", "!=", "0", ":", "glDeleteBuffers", "(", "1", ",", "(", "self", ".", "m_glIndexBuffer", ",", ")", ")", "glDeleteVertexArrays", "(", "1", ",", "(", "self", ".", "m_glVertArray", ...
44
0.009901
def array(events, slots, objective_function=None, solver=None, **kwargs): """Compute a schedule in array form Parameters ---------- events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances objective_function : ...
[ "def", "array", "(", "events", ",", "slots", ",", "objective_function", "=", "None", ",", "solver", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "conv", ".", "solution_to_array", "(", "solution", "(", "events", ",", "slots", ",", "objective_...
27.486486
0.00095
def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True): """Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The m...
[ "def", "score", "(", "self", ",", "X", ",", "eval_metric", "=", "'acc'", ",", "num_batch", "=", "None", ",", "batch_end_callback", "=", "None", ",", "reset", "=", "True", ")", ":", "# setup metric", "if", "not", "isinstance", "(", "eval_metric", ",", "me...
38.24
0.00204
def crypto_scalarmult_ed25519(n, p): """ Computes and returns the scalar product of a *clamped* integer ``n`` and the given group element on the edwards25519 curve. The scalar is clamped, as done in the public key generation case, by setting to zero the bits in position [0, 1, 2, 255] and setting ...
[ "def", "crypto_scalarmult_ed25519", "(", "n", ",", "p", ")", ":", "ensure", "(", "isinstance", "(", "n", ",", "bytes", ")", "and", "len", "(", "n", ")", "==", "crypto_scalarmult_ed25519_SCALARBYTES", ",", "'Input must be a {} long bytes sequence'", ".", "format", ...
40.447368
0.000635
def set_expr(self, ctx): """ Returns the MUF needed to do an assign on the lvalue. (=) Returned MUF expects a value to be on the stack. """ if self.readonly: raise MuvError( "Cannot assign value to constant '%s'." % self.varname, positi...
[ "def", "set_expr", "(", "self", ",", "ctx", ")", ":", "if", "self", ".", "readonly", ":", "raise", "MuvError", "(", "\"Cannot assign value to constant '%s'.\"", "%", "self", ".", "varname", ",", "position", "=", "self", ".", "position", ")", "if", "self", ...
37.945455
0.000934
def __add_bootstrap_tour_step(self, message, selector=None, name=None, title=None, alignment=None, duration=None): """ Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of t...
[ "def", "__add_bootstrap_tour_step", "(", "self", ",", "message", ",", "selector", "=", "None", ",", "name", "=", "None", ",", "title", "=", "None", ",", "alignment", "=", "None", ",", "duration", "=", "None", ")", ":", "if", "selector", "!=", "\"html\"",...
42.857143
0.001956