text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def show_error(msg): """ Displays error message. """ sys.stdout.flush() sys.stderr.write("\n{0!s}: {1}".format(colored.red("Error"), msg + '\n'))
[ "def", "show_error", "(", "msg", ")", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "write", "(", "\"\\n{0!s}: {1}\"", ".", "format", "(", "colored", ".", "red", "(", "\"Error\"", ")", ",", "msg", "+", "'\\n'", ")", ...
26.666667
14.666667
def recv_into(self, buffer, nbytes=None, flags=None): """ Receive data on the connection and copy it directly into the provided buffer, rather than creating a new string. :param buffer: The buffer to copy into. :param nbytes: (optional) The maximum number of bytes to read into t...
[ "def", "recv_into", "(", "self", ",", "buffer", ",", "nbytes", "=", "None", ",", "flags", "=", "None", ")", ":", "if", "nbytes", "is", "None", ":", "nbytes", "=", "len", "(", "buffer", ")", "else", ":", "nbytes", "=", "min", "(", "nbytes", ",", "...
45.722222
23
def read(self, timeout=None): ''' Read from the transport. If no data is available, should return None. If timeout>0, will only block for `timeout` seconds. ''' # If currently locked, another greenlet is trying to read, so yield # control and then return none. Required if...
[ "def", "read", "(", "self", ",", "timeout", "=", "None", ")", ":", "# If currently locked, another greenlet is trying to read, so yield", "# control and then return none. Required if a Connection is configured", "# to be synchronous, a sync callback is trying to read, and there's", "# anot...
48.269231
23.961538
def get_editor_cmd_from_environment(): """ Gets and editor command from environment variables. It first tries $VISUAL, then $EDITOR, following the same order git uses when it looks up edits. If neither is available, it returns None. """ result = os.getenv(ENV_VISUAL) if (not result): ...
[ "def", "get_editor_cmd_from_environment", "(", ")", ":", "result", "=", "os", ".", "getenv", "(", "ENV_VISUAL", ")", "if", "(", "not", "result", ")", ":", "result", "=", "os", ".", "getenv", "(", "ENV_EDITOR", ")", "return", "result" ]
32.727273
15.636364
def update(self, serviceId, serviceName, credentials, description): """ Updates the service with the specified id. if description is empty, the existing description will be removed. Parameters: - serviceId (String), Service Id which is a UUID - serviceName (string...
[ "def", "update", "(", "self", ",", "serviceId", ",", "serviceName", ",", "credentials", ",", "description", ")", ":", "url", "=", "\"api/v0002/s2s/services/%s\"", "%", "(", "serviceId", ")", "serviceBody", "=", "{", "}", "serviceBody", "[", "\"name\"", "]", ...
35.56
17.08
def get_initial_state(self, source_length: mx.sym.Symbol, source_seq_len: int) -> AttentionState: """ Returns initial attention state. Dynamic source encoding is initialized with zeros. :param source_length: Source length. Shape: (batch_size,). :param source_seq_len: Maximum length of s...
[ "def", "get_initial_state", "(", "self", ",", "source_length", ":", "mx", ".", "sym", ".", "Symbol", ",", "source_seq_len", ":", "int", ")", "->", "AttentionState", ":", "dynamic_source", "=", "mx", ".", "sym", ".", "reshape", "(", "mx", ".", "sym", ".",...
65.363636
37.909091
def show_help(fd=sys.stdout): ''' Convenience wrapper around binwalk.core.module.Modules.help. @fd - An object with a write method (e.g., sys.stdout, sys.stderr, etc). Returns None. ''' with Modules() as m: fd.write(m.help())
[ "def", "show_help", "(", "fd", "=", "sys", ".", "stdout", ")", ":", "with", "Modules", "(", ")", "as", "m", ":", "fd", ".", "write", "(", "m", ".", "help", "(", ")", ")" ]
25
27
def _new_theme_part(cls, package): """ Create and return a default theme part suitable for use with a notes master. """ partname = package.next_partname('/ppt/theme/theme%d.xml') content_type = CT.OFC_THEME theme = CT_OfficeStyleSheet.new_default() return ...
[ "def", "_new_theme_part", "(", "cls", ",", "package", ")", ":", "partname", "=", "package", ".", "next_partname", "(", "'/ppt/theme/theme%d.xml'", ")", "content_type", "=", "CT", ".", "OFC_THEME", "theme", "=", "CT_OfficeStyleSheet", ".", "new_default", "(", ")"...
39.888889
14.333333
def pop(self, idx=None): """ Remove an item from the array. By default this will be the last item by index, but any index can be specified. """ if idx is not None: return self.database.run_script( 'array_remove', keys=[self.key], ...
[ "def", "pop", "(", "self", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "not", "None", ":", "return", "self", ".", "database", ".", "run_script", "(", "'array_remove'", ",", "keys", "=", "[", "self", ".", "key", "]", ",", "args", "=", "[...
31.533333
11.666667
def parse_tag_info_chrs(self, f, convChr=True): """ Parse HOMER tagdirectory taginfo.txt file to extract chromosome coverage. """ parsed_data_total = OrderedDict() parsed_data_uniq = OrderedDict() remove = ["hap", "random", "chrUn", "cmd", "EBV", "GL", "NT_"] for l in f['f']: ...
[ "def", "parse_tag_info_chrs", "(", "self", ",", "f", ",", "convChr", "=", "True", ")", ":", "parsed_data_total", "=", "OrderedDict", "(", ")", "parsed_data_uniq", "=", "OrderedDict", "(", ")", "remove", "=", "[", "\"hap\"", ",", "\"random\"", ",", "\"chrUn\"...
34.875
12.083333
def normframe(I: np.ndarray, Clim: tuple) -> np.ndarray: """ inputs: ------- I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image """ Vmin = Clim[0] Vmax = Clim[1] # stretch to [0,1] ...
[ "def", "normframe", "(", "I", ":", "np", ".", "ndarray", ",", "Clim", ":", "tuple", ")", "->", "np", ".", "ndarray", ":", "Vmin", "=", "Clim", "[", "0", "]", "Vmax", "=", "Clim", "[", "1", "]", "# stretch to [0,1]", "return", "(", "I", ".", "asty...
31.666667
23.833333
def CreatePermission(self, user_link, permission, options=None): """Creates a permission for a user. :param str user_link: The link to the user entity. :param dict permission: The Azure Cosmos user permission to create. :param dict options: The reques...
[ "def", "CreatePermission", "(", "self", ",", "user_link", ",", "permission", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "path", ",", "user_id", "=", "self", ".", "_GetUserIdWithPathForPermission", "...
29.923077
16.076923
def spawn(func, *args, **kwargs): """Spawn a new fiber. A new :class:`Fiber` is created with main function *func* and positional arguments *args*. The keyword arguments are passed to the :class:`Fiber` constructor, not to the main function. The fiber is then scheduled to start by calling its :meth:...
[ "def", "spawn", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fiber", "=", "Fiber", "(", "func", ",", "args", ",", "*", "*", "kwargs", ")", "fiber", ".", "start", "(", ")", "return", "fiber" ]
34.615385
19.846154
def delete_function(self, name): """ Deletes the specified Cloud Function. :param name: The name of the function. :type name: str :return: None """ response = self.get_conn().projects().locations().functions().delete( name=name).execute(num_retries=se...
[ "def", "delete_function", "(", "self", ",", "name", ")", ":", "response", "=", "self", ".", "get_conn", "(", ")", ".", "projects", "(", ")", ".", "locations", "(", ")", ".", "functions", "(", ")", ".", "delete", "(", "name", "=", "name", ")", ".", ...
36.833333
15.666667
def _connect(self): """ Returns an aggregator connection. """ with self._lock: if self._aggregator: try: return self._pool_connect(self._aggregator) except PoolConnectionException: self._aggregator = None if...
[ "def", "_connect", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_aggregator", ":", "try", ":", "return", "self", ".", "_pool_connect", "(", "self", ".", "_aggregator", ")", "except", "PoolConnectionException", ":", "self", ...
36.441176
16.294118
def run(logdir, run_name, wave_name, wave_constructor): """Generate wave data of the given form. The provided function `wave_constructor` should accept a scalar tensor of type float32, representing the frequency (in Hz) at which to construct a wave, and return a tensor of shape [1, _samples(), `n`] represent...
[ "def", "run", "(", "logdir", ",", "run_name", ",", "wave_name", ",", "wave_constructor", ")", ":", "tf", ".", "compat", ".", "v1", ".", "reset_default_graph", "(", ")", "tf", ".", "compat", ".", "v1", ".", "set_random_seed", "(", "0", ")", "# On each ste...
39.988235
20.635294
def _datetime_to_epoch(self, dt): """Convert the datetime to unix epoch (properly).""" if dt: td = (dt - datetime.datetime.fromtimestamp(0, tzutc())) # don't use total_seconds(), that's only available in 2.7 total_secs = int((td.microseconds + ...
[ "def", "_datetime_to_epoch", "(", "self", ",", "dt", ")", ":", "if", "dt", ":", "td", "=", "(", "dt", "-", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "0", ",", "tzutc", "(", ")", ")", ")", "# don't use total_seconds(), that's only available in 2...
42.090909
16.818182
def request_ligodotorg(url, debug=False): """Request the given URL using LIGO.ORG SAML authentication. This requires an active Kerberos ticket for the user, to get one: $ kinit albert.einstein@LIGO.ORG Parameters ---------- url : `str` URL path for request debug : `bool`, optional...
[ "def", "request_ligodotorg", "(", "url", ",", "debug", "=", "False", ")", ":", "# set debug to 1 to see all HTTP(s) traffic", "debug", "=", "int", "(", "debug", ")", "# need an instance of HTTPS handler to do HTTPS", "httpsHandler", "=", "urllib2", ".", "HTTPSHandler", ...
32.596774
21.387097
def prepare_inputs(self, times=None, weather=None): """ Prepare the solar position, irradiance, and weather inputs to the model. Parameters ---------- times : None or DatetimeIndex, default None Times at which to evaluate the model. Can be None if ...
[ "def", "prepare_inputs", "(", "self", ",", "times", "=", "None", ",", "weather", "=", "None", ")", ":", "if", "weather", "is", "not", "None", ":", "self", ".", "weather", "=", "weather", "if", "self", ".", "weather", "is", "None", ":", "self", ".", ...
42.290323
18.16129
def get_analysis_type(self, instance): """Returns the string used in slots to differentiate amongst analysis types """ if IDuplicateAnalysis.providedBy(instance): return 'd' elif IReferenceAnalysis.providedBy(instance): return instance.getReferenceType() ...
[ "def", "get_analysis_type", "(", "self", ",", "instance", ")", ":", "if", "IDuplicateAnalysis", ".", "providedBy", "(", "instance", ")", ":", "return", "'d'", "elif", "IReferenceAnalysis", ".", "providedBy", "(", "instance", ")", ":", "return", "instance", "."...
36.636364
11.545455
def _calibrate(self, data): """Visible/IR channel calibration.""" lut = self.prologue['ImageCalibration'][self.chid] if abs(lut).max() > 16777216: lut = lut.astype(np.float64) else: lut = lut.astype(np.float32) lut /= 1000 lut[0] = np.nan #...
[ "def", "_calibrate", "(", "self", ",", "data", ")", ":", "lut", "=", "self", ".", "prologue", "[", "'ImageCalibration'", "]", "[", "self", ".", "chid", "]", "if", "abs", "(", "lut", ")", ".", "max", "(", ")", ">", "16777216", ":", "lut", "=", "lu...
39.466667
13.8
def render(self, context): """ Build the filepath by appending the extension. """ module_path = self.path.resolve(context) if not settings.SYSTEMJS_ENABLED: if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS: name, ext = posixpath.splitext(module_path) ...
[ "def", "render", "(", "self", ",", "context", ")", ":", "module_path", "=", "self", ".", "path", ".", "resolve", "(", "context", ")", "if", "not", "settings", ".", "SYSTEMJS_ENABLED", ":", "if", "settings", ".", "SYSTEMJS_DEFAULT_JS_EXTENSIONS", ":", "name",...
39.333333
14.3
def _get_dns_cname(name, link=False): """ Looks for associated domain zone, nameservers and linked record name until no more linked record name was found for the given fully qualified record name or the CNAME lookup was disabled, and then returns the parameters as a tuple. """ ...
[ "def", "_get_dns_cname", "(", "name", ",", "link", "=", "False", ")", ":", "resolver", "=", "dns", ".", "resolver", ".", "Resolver", "(", ")", "resolver", ".", "lifetime", "=", "1", "domain", "=", "dns", ".", "resolver", ".", "zone_for_name", "(", "nam...
46
18.5625
def ra(self,*args,**kwargs): """ NAME: ra PURPOSE: return the right ascension INPUT: t - (optional) time at which to get ra obs=[X,Y,Z] - (optional) position of observer (in kpc) (default=Object-wide default) ...
[ "def", "ra", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_check_roSet", "(", "self", ",", "kwargs", ",", "'ra'", ")", "radec", "=", "self", ".", "_radec", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "radec", ...
34.863636
16.5
def deleteRole(self, roleID): """ deletes a role by ID """ url = self._url + "/%s/delete" % roleID params = { "f" : "json" } return self._post(url=url, param_dict=params, proxy_url=self._proxy_...
[ "def", "deleteRole", "(", "self", ",", "roleID", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/%s/delete\"", "%", "roleID", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "return", "self", ".", "_post", "(", "url", "=", "url", ",", "param_d...
28.461538
14.153846
def value_to_python(self, value): """ Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. """ if not isins...
[ "def", "value_to_python", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "bytes", ")", ":", "raise", "tldap", ".", "exceptions", ".", "ValidationError", "(", "\"should be a bytes\"", ")", "length", "=", "len", "(", "valu...
35.230769
21.923077
def _set_mld(self, v, load=False): """ Setter method for mld, mapped from YANG variable /mld_snooping/ipv6/mld (container) If this variable is read-only (config: false) in the source YANG file, then _set_mld is considered as a private method. Backends looking to populate this variable should do ...
[ "def", "_set_mld", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", "...
75.954545
35.545455
def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1, log=False): ''' Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: ...
[ "def", "solve_dual_entropic", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "batch_size", ",", "numItermax", "=", "10000", ",", "lr", "=", "1", ",", "log", "=", "False", ")", ":", "opt_alpha", ",", "opt_beta", "=", "sgd_entropic_regularization", "(", ...
27.304348
23.543478
def port_profile_global_port_profile_static_mac_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile_global = ET.SubElement(config, "port-profile-global", xmlns="urn:brocade.com:mgmt:brocade-port-profile") port_profile = ET.SubElement(por...
[ "def", "port_profile_global_port_profile_static_mac_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "port_profile_global", "=", "ET", ".", "SubElement", "(", "config", ",", "\"port-profile-glob...
49.714286
19.928571
def addprojectmember(self, project_id, user_id, access_level): """Adds a project member to a project :param project_id: project id :param user_id: user id :param access_level: access level, see gitlab help to know more :return: True if success """ # if isinstance...
[ "def", "addprojectmember", "(", "self", ",", "project_id", ",", "user_id", ",", "access_level", ")", ":", "# if isinstance(access_level, basestring):", "if", "access_level", ".", "lower", "(", ")", "==", "'master'", ":", "access_level", "=", "40", "elif", "access_...
35.571429
19.357143
def _make_socket(cls, ip, port): """Bind to a new socket. If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment, these will be used for socket connectivity. """ bound_socket = bind_sockets(port, address=ip)[0] ip, port = bound_socket.getsockname() if not ip or ip == '0.0.0....
[ "def", "_make_socket", "(", "cls", ",", "ip", ",", "port", ")", ":", "bound_socket", "=", "bind_sockets", "(", "port", ",", "address", "=", "ip", ")", "[", "0", "]", "ip", ",", "port", "=", "bound_socket", ".", "getsockname", "(", ")", "if", "not", ...
30.769231
16.076923
def create_session(self, session_request, protocol): """CreateSession. [Preview API] Creates a session, a wrapper around a feed that can store additional metadata on the packages published to it. :param :class:`<SessionRequest> <azure.devops.v5_0.provenance.models.SessionRequest>` session_reques...
[ "def", "create_session", "(", "self", ",", "session_request", ",", "protocol", ")", ":", "route_values", "=", "{", "}", "if", "protocol", "is", "not", "None", ":", "route_values", "[", "'protocol'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "...
64.588235
29.882353
def load_module(self, filename): '''Load a benchmark module from file''' if not isinstance(filename, string_types): return filename basename = os.path.splitext(os.path.basename(filename))[0] basename = basename.replace('.bench', '') modulename = 'benchmarks.{0}'.forma...
[ "def", "load_module", "(", "self", ",", "filename", ")", ":", "if", "not", "isinstance", "(", "filename", ",", "string_types", ")", ":", "return", "filename", "basename", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", ...
46.625
11.875
def write_fmt(fp, fmt, *args): """ Writes data to ``fp`` according to ``fmt``. """ fmt = str(">" + fmt) fmt_size = struct.calcsize(fmt) written = write_bytes(fp, struct.pack(fmt, *args)) assert written == fmt_size, 'written=%d, expected=%d' % ( written, fmt_size ) return writ...
[ "def", "write_fmt", "(", "fp", ",", "fmt", ",", "*", "args", ")", ":", "fmt", "=", "str", "(", "\">\"", "+", "fmt", ")", "fmt_size", "=", "struct", ".", "calcsize", "(", "fmt", ")", "written", "=", "write_bytes", "(", "fp", ",", "struct", ".", "p...
28.454545
13.181818
def ci2ls(ci): ''' Convert from a community index vector to a 2D python list of modules The list is a pure python list, not requiring numpy. Parameters ---------- ci : Nx1 np.ndarray the community index vector zeroindexed : bool If True, ci uses zero-indexing (lowest value i...
[ "def", "ci2ls", "(", "ci", ")", ":", "if", "not", "np", ".", "size", "(", "ci", ")", ":", "return", "ci", "# list is empty", "_", ",", "ci", "=", "np", ".", "unique", "(", "ci", ",", "return_inverse", "=", "True", ")", "ci", "+=", "1", "nr_indice...
26.413793
21.448276
def out_of_date(self): """Check if our local latest sha matches the remote latest sha""" try: latest_remote_sha = self.pr_commits(self.pull_request.refresh(True))[-1].sha print("Latest remote sha: {}".format(latest_remote_sha)) try: print("Ratelimit re...
[ "def", "out_of_date", "(", "self", ")", ":", "try", ":", "latest_remote_sha", "=", "self", ".", "pr_commits", "(", "self", ".", "pull_request", ".", "refresh", "(", "True", ")", ")", "[", "-", "1", "]", ".", "sha", "print", "(", "\"Latest remote sha: {}\...
46.75
22.5
def _recursive_gh_get(href, items): """Recursively get list of GitHub objects. See https://developer.github.com/v3/guides/traversing-with-pagination/ """ response = _request('GET', href) response.raise_for_status() items.extend(response.json()) if "link" not in response.headers: ret...
[ "def", "_recursive_gh_get", "(", "href", ",", "items", ")", ":", "response", "=", "_request", "(", "'GET'", ",", "href", ")", "response", ".", "raise_for_status", "(", ")", "items", ".", "extend", "(", "response", ".", "json", "(", ")", ")", "if", "\"l...
35.214286
13
def layout(self, rect=None, width=0, height=0, fontsize=11): """Re-layout a reflowable document.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") val = _fitz.Document_layout(self, rect, width, height, fontsize) self._...
[ "def", "layout", "(", "self", ",", "rect", "=", "None", ",", "width", "=", "0", ",", "height", "=", "0", ",", "fontsize", "=", "11", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"oper...
33.727273
23.727273
def get_msms_annotations_parallelize(self, sc, representatives_only=True, force_rerun=False): """Run MSMS on structures and store calculations. Annotations are stored in the protein structure's chain sequence at: ``<chain_prop>.seq_record.letter_annotations['*-msms']`` Args: ...
[ "def", "get_msms_annotations_parallelize", "(", "self", ",", "sc", ",", "representatives_only", "=", "True", ",", "force_rerun", "=", "False", ")", ":", "genes_rdd", "=", "sc", ".", "parallelize", "(", "self", ".", "genes", ")", "def", "get_msms_annotation", "...
44.380952
29.619048
def deactivate_user(self, user): """Deactivates a specified user. Returns `True` if a change was made. :param user: The user to deactivate """ if user.active: user.active = False return True return False
[ "def", "deactivate_user", "(", "self", ",", "user", ")", ":", "if", "user", ".", "active", ":", "user", ".", "active", "=", "False", "return", "True", "return", "False" ]
28.888889
12.666667
def Save_Generic(obj, SaveName=None, Path='./', Mode='npz', compressed=False, Print=True): """ Save a ToFu object under file name SaveName, in folder Path ToFu provides built-in saving and loading functions for ToFu objects. There is now only one saving mode: - 'npz': saves a dict ...
[ "def", "Save_Generic", "(", "obj", ",", "SaveName", "=", "None", ",", "Path", "=", "'./'", ",", "Mode", "=", "'npz'", ",", "compressed", "=", "False", ",", "Print", "=", "True", ")", ":", "assert", "type", "(", "obj", ".", "__class__", ")", "is", "...
36.039216
18.27451
def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any m...
[ "def", "callproc", "(", "self", ",", "procname", ",", "args", "=", "(", ")", ")", ":", "conn", "=", "self", ".", "_get_db", "(", ")", "if", "args", ":", "fmt", "=", "'@_{0}_%d=%s'", ".", "format", "(", "procname", ")", "self", ".", "_query", "(", ...
45.146341
23.609756
def validate_basic_smoother_resid(): """Compare residuals.""" x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82()) plt.figure() for span in smoother.DEFAULT_SPANS: my_smoother = smoother.perform_smooth(x, y, span) _friedman_smooth, resids = run_friedman_smoot...
[ "def", "validate_basic_smoother_resid", "(", ")", ":", "x", ",", "y", "=", "sort_data", "(", "*", "smoother_friedman82", ".", "build_sample_smoother_problem_friedman82", "(", ")", ")", "plt", ".", "figure", "(", ")", "for", "span", "in", "smoother", ".", "DEFA...
52
22.545455
def notify_rejection(analysisrequest): """ Notifies via email that a given Analysis Request has been rejected. The notification is sent to the Client contacts assigned to the Analysis Request. :param analysisrequest: Analysis Request to which the notification refers :returns: true if success ...
[ "def", "notify_rejection", "(", "analysisrequest", ")", ":", "# We do this imports here to avoid circular dependencies until we deal", "# better with this notify_rejection thing.", "from", "bika", ".", "lims", ".", "browser", ".", "analysisrequest", ".", "reject", "import", "An...
38
18.285714
def deleteJID(self, bare_jid): """ Delete all data associated with a JID. This includes the list of active/inactive devices, all sessions with that JID and all information about trusted keys. """ yield self.runInactiveDeviceCleanup() self.__sessions_cache.pop(bare_jid, ...
[ "def", "deleteJID", "(", "self", ",", "bare_jid", ")", ":", "yield", "self", ".", "runInactiveDeviceCleanup", "(", ")", "self", ".", "__sessions_cache", ".", "pop", "(", "bare_jid", ",", "None", ")", "self", ".", "__devices_cache", ".", "pop", "(", "bare_j...
35.230769
19.692308
def setLength(self, vehID, length): """setLength(string, double) -> None Sets the length in m for the given vehicle. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_LENGTH, vehID, length)
[ "def", "setLength", "(", "self", ",", "vehID", ",", "length", ")", ":", "self", ".", "_connection", ".", "_sendDoubleCmd", "(", "tc", ".", "CMD_SET_VEHICLE_VARIABLE", ",", "tc", ".", "VAR_LENGTH", ",", "vehID", ",", "length", ")" ]
35.857143
12.285714
def run(self): """ run all configured stages """ self.sanity_check() # TODO - check for devel # if not self.version: # raise Exception("no version") # XXX check attr exist if not self.release_environment: raise Exception("no instance name") time_start = t...
[ "def", "run", "(", "self", ")", ":", "self", ".", "sanity_check", "(", ")", "# TODO - check for devel", "# if not self.version:", "# raise Exception(\"no version\")", "# XXX check attr exist", "if", "not", "self", ".", "release_environment", ":", "raise", ...
31.135593
18.983051
def showRemoveColumnDialog(self, triggered): """Display the dialog to remove column(s) from the model. This method is also a slot. Args: triggered (bool): If the corresponding button was activated, the dialog will be created and shown. """ if trigge...
[ "def", "showRemoveColumnDialog", "(", "self", ",", "triggered", ")", ":", "if", "triggered", ":", "model", "=", "self", ".", "tableView", ".", "model", "(", ")", "if", "model", "is", "not", "None", ":", "columns", "=", "model", ".", "dataFrameColumns", "...
36
17.222222
def send_file(self, filename, mimetype=None, restricted=True, checksum=None, trusted=False, chunk_size=None, as_attachment=False): """Send the file to the client.""" try: fp = self.open(mode='rb') except Exception as e: raise StorageErr...
[ "def", "send_file", "(", "self", ",", "filename", ",", "mimetype", "=", "None", ",", "restricted", "=", "True", ",", "checksum", "=", "None", ",", "trusted", "=", "False", ",", "chunk_size", "=", "None", ",", "as_attachment", "=", "False", ")", ":", "t...
34.090909
14.151515
def setValue(self, value): """ Sets the value that will be used for this query instance. :param value <variant> """ self.__value = projex.text.decoded(value) if isinstance(value, (str, unicode)) else value
[ "def", "setValue", "(", "self", ",", "value", ")", ":", "self", ".", "__value", "=", "projex", ".", "text", ".", "decoded", "(", "value", ")", "if", "isinstance", "(", "value", ",", "(", "str", ",", "unicode", ")", ")", "else", "value" ]
37
18.428571
def cls_sets(cls, wanted_cls, registered=True): """ Return a list of all `wanted_cls` attributes in this class, where `wanted_cls` is the desired attribute type. """ sets = [] for attr in dir(cls): if attr.startswith('_'): continue val = getattr(cls, attr, None) ...
[ "def", "cls_sets", "(", "cls", ",", "wanted_cls", ",", "registered", "=", "True", ")", ":", "sets", "=", "[", "]", "for", "attr", "in", "dir", "(", "cls", ")", ":", "if", "attr", ".", "startswith", "(", "'_'", ")", ":", "continue", "val", "=", "g...
33
14.266667
def ipop(self, index): '''Pop a value at *index* from the :class:`TS`. Return ``None`` if index is not out of bound.''' backend = self.backend res = backend.structure(self).ipop(index) return backend.execute(res, lambda r: self._load_get_data(r, index...
[ "def", "ipop", "(", "self", ",", "index", ")", ":", "backend", "=", "self", ".", "backend", "res", "=", "backend", ".", "structure", "(", "self", ")", ".", "ipop", "(", "index", ")", "return", "backend", ".", "execute", "(", "res", ",", "lambda", "...
46
17.428571
def _lca(intervals_hier, frame_size): '''Compute the (sparse) least-common-ancestor (LCA) matrix for a hierarchical segmentation. For any pair of frames ``(s, t)``, the LCA is the deepest level in the hierarchy such that ``(s, t)`` are contained within a single segment at that level. Parameter...
[ "def", "_lca", "(", "intervals_hier", ",", "frame_size", ")", ":", "frame_size", "=", "float", "(", "frame_size", ")", "# Figure out how many frames we need", "n_start", ",", "n_end", "=", "_hierarchy_bounds", "(", "intervals_hier", ")", "n", "=", "int", "(", "(...
31.930233
22.488372
def setup_new_conf(self): # pylint: disable=too-many-branches """Setup the new configuration received from Arbiter This function calls the base satellite treatment and manages the configuration needed for a simple satellite daemon that executes some actions (eg. poller or reactionner): ...
[ "def", "setup_new_conf", "(", "self", ")", ":", "# pylint: disable=too-many-branches", "# Execute the base class treatment...", "super", "(", "Satellite", ",", "self", ")", ".", "setup_new_conf", "(", ")", "# ...then our own specific treatment!", "with", "self", ".", "con...
43.407407
22.537037
def _handle_exec_callback(self, msg): """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback`` Parameters ---------- msg : raw message send by the kernel containing an `user_expressions` and having a 'silent_exec_callback' kind. Notes ...
[ "def", "_handle_exec_callback", "(", "self", ",", "msg", ")", ":", "user_exp", "=", "msg", "[", "'content'", "]", ".", "get", "(", "'user_expressions'", ")", "if", "not", "user_exp", ":", "return", "for", "expression", "in", "user_exp", ":", "if", "express...
39.8
23.24
def get_weather_name(self, ip): ''' Get weather_name ''' rec = self.get_all(ip) return rec and rec.weather_name
[ "def", "get_weather_name", "(", "self", ",", "ip", ")", ":", "rec", "=", "self", ".", "get_all", "(", "ip", ")", "return", "rec", "and", "rec", ".", "weather_name" ]
33
7
def _8bit_oper(op1, op2=None, reversed_=False): """ Returns pop sequence for 8 bits operands 1st operand in H, 2nd operand in A (accumulator) For some operations (like comparisons), you can swap operands extraction by setting reversed = True """ output = [] if op2 is not None and reversed_...
[ "def", "_8bit_oper", "(", "op1", ",", "op2", "=", "None", ",", "reversed_", "=", "False", ")", ":", "output", "=", "[", "]", "if", "op2", "is", "not", "None", "and", "reversed_", ":", "tmp", "=", "op1", "op1", "=", "op2", "op2", "=", "tmp", "op",...
24.647059
19.519608
def parse_command_line(self, argv=None): """override to allow old '-pylab' flag with deprecation warning""" argv = sys.argv[1:] if argv is None else argv if '-pylab' in argv: # deprecated `-pylab` given, # warn and transform into current syntax argv = argv[:...
[ "def", "parse_command_line", "(", "self", ",", "argv", "=", "None", ")", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "argv", "is", "None", "else", "argv", "if", "'-pylab'", "in", "argv", ":", "# deprecated `-pylab` given,", "# warn an...
40.636364
15.363636
def i2c_master_write_read(self, i2c_address, data, length): """Make an I2C write/read access. First an I2C write access is issued. No stop condition will be generated. Instead the read access begins with a repeated start. This method is useful for accessing most addressable I2C devices...
[ "def", "i2c_master_write_read", "(", "self", ",", "i2c_address", ",", "data", ",", "length", ")", ":", "self", ".", "i2c_master_write", "(", "i2c_address", ",", "data", ",", "I2C_NO_STOP", ")", "return", "self", ".", "i2c_master_read", "(", "i2c_address", ",",...
40.466667
24.2
def _linux_broken_devpts_openpty(): """ #462: On broken Linux hosts with mismatched configuration (e.g. old /etc/fstab template installed), /dev/pts may be mounted without the gid= mount option, causing new slave devices to be created with the group ID of the calling process. This upsets glibc, whos...
[ "def", "_linux_broken_devpts_openpty", "(", ")", ":", "master_fd", "=", "None", "try", ":", "# Opening /dev/ptmx causes a PTY pair to be allocated, and the", "# corresponding slave /dev/pts/* device to be created, owned by UID/GID", "# matching this process.", "master_fd", "=", "os", ...
52.225
22.425
def to_kirbidir(self, directory_path): """ Converts all credential object in the CCACHE object to the kirbi file format used by mimikatz. The kirbi file format supports one credential per file, so prepare for a lot of files being generated. directory_path: str the directory to write the kirbi files to """ ...
[ "def", "to_kirbidir", "(", "self", ",", "directory_path", ")", ":", "kf_abs", "=", "os", ".", "path", ".", "abspath", "(", "directory_path", ")", "for", "cred", "in", "self", ".", "credentials", ":", "kirbi", ",", "filename", "=", "cred", ".", "to_kirbi"...
41.285714
16.857143
def menu_callback(self, m): '''called on menu selection''' if m.returnkey.startswith('# '): cmd = m.returnkey[2:] if m.handler is not None: if m.handler_result is None: return cmd += m.handler_result self.mpstate.fun...
[ "def", "menu_callback", "(", "self", ",", "m", ")", ":", "if", "m", ".", "returnkey", ".", "startswith", "(", "'# '", ")", ":", "cmd", "=", "m", ".", "returnkey", "[", "2", ":", "]", "if", "m", ".", "handler", "is", "not", "None", ":", "if", "m...
38.727273
6
def caller_locals(): """Get the local variables in the caller's frame.""" import inspect frame = inspect.currentframe() try: return frame.f_back.f_back.f_locals finally: del frame
[ "def", "caller_locals", "(", ")", ":", "import", "inspect", "frame", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "return", "frame", ".", "f_back", ".", "f_back", ".", "f_locals", "finally", ":", "del", "frame" ]
26
16.75
def _insert_file(cursor, file, media_type): """Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file. """ resource_hash = _get_file_sha1(file) cursor.execute("SELECT fileid FROM files WHERE sha1 = %s", (resource_hash...
[ "def", "_insert_file", "(", "cursor", ",", "file", ",", "media_type", ")", ":", "resource_hash", "=", "_get_file_sha1", "(", "file", ")", "cursor", ".", "execute", "(", "\"SELECT fileid FROM files WHERE sha1 = %s\"", ",", "(", "resource_hash", ",", ")", ")", "tr...
39.764706
11.294118
def write_to_local(self, filepath_from, filepath_to, mtime_dt=None): """Open a remote file and write it locally.""" self.__log.debug("Writing R[%s] -> L[%s]." % (filepath_from, filepath_to)) with SftpFile(self, filepath_from, 'r') as sf_fr...
[ "def", "write_to_local", "(", "self", ",", "filepath_from", ",", "filepath_to", ",", "mtime_dt", "=", "None", ")", ":", "self", ".", "__log", ".", "debug", "(", "\"Writing R[%s] -> L[%s].\"", "%", "(", "filepath_from", ",", "filepath_to", ")", ")", "with", "...
38.05
21.65
def chi2comb_cdf(q, chi2s, gcoef, lim=1000, atol=1e-4): r"""Function distribution of combination of chi-squared distributions. Parameters ---------- q : float Value point at which distribution function is to be evaluated. chi2s : ChiSquared Chi-squared distributions. gcoef : flo...
[ "def", "chi2comb_cdf", "(", "q", ",", "chi2s", ",", "gcoef", ",", "lim", "=", "1000", ",", "atol", "=", "1e-4", ")", ":", "int_type", "=", "\"i\"", "if", "array", "(", "int_type", ",", "[", "0", "]", ")", ".", "itemsize", "!=", "ffi", ".", "sizeo...
32.629032
21.225806
def save_xml(self, doc, element): '''Save this target component into an xml.dom.Element object.''' element.setAttributeNS(RTS_NS, RTS_NS_S + 'componentId', self.component_id) element.setAttributeNS(RTS_NS, RTS_NS_S + 'instanceName', s...
[ "def", "save_xml", "(", "self", ",", "doc", ",", "element", ")", ":", "element", ".", "setAttributeNS", "(", "RTS_NS", ",", "RTS_NS_S", "+", "'componentId'", ",", "self", ".", "component_id", ")", "element", ".", "setAttributeNS", "(", "RTS_NS", ",", "RTS_...
56.909091
19.454545
def _require_backsearch(self): """ Determine whether a backsearch should be performed on prior peaks """ if self.peak_num == self.n_peaks_i-1: # If we just return false, we may miss a chance to backsearch. # Update this? return False next_peak...
[ "def", "_require_backsearch", "(", "self", ")", ":", "if", "self", ".", "peak_num", "==", "self", ".", "n_peaks_i", "-", "1", ":", "# If we just return false, we may miss a chance to backsearch.", "# Update this?", "return", "False", "next_peak_ind", "=", "self", ".",...
31.866667
19.733333
def versions(self, rev=None, index=None): """:return: List of Versions for this Item""" raise NotImplementedError _revisions = [line.split()[0] for line in self.log.split('\n') if line] _versions = [Version(self.obj.repo.commit(r)) for r in _revisions if rev is None or r.startswith(rev)]...
[ "def", "versions", "(", "self", ",", "rev", "=", "None", ",", "index", "=", "None", ")", ":", "raise", "NotImplementedError", "_revisions", "=", "[", "line", ".", "split", "(", ")", "[", "0", "]", "for", "line", "in", "self", ".", "log", ".", "spli...
54.5
18.625
def gcp(V,E,K): """gcp -- model for minimizing the number of colors in a graph Parameters: - V: set/list of nodes in the graph - E: set/list of edges in the graph - K: upper bound on the number of colors Returns a model, ready to be solved. """ model = Model("gcp") x,y = ...
[ "def", "gcp", "(", "V", ",", "E", ",", "K", ")", ":", "model", "=", "Model", "(", "\"gcp\"", ")", "x", ",", "y", "=", "{", "}", ",", "{", "}", "for", "k", "in", "range", "(", "K", ")", ":", "y", "[", "k", "]", "=", "model", ".", "addVar...
31.038462
21.769231
def successful(self): """Return True if the job finished with a COMPLETED status, False if it finished with a CANCELLED or FAILED status. Raise an `AssertionError` if the job has not completed""" status = self.status assert status >= COMPLETED, "status is %s" % status ret...
[ "def", "successful", "(", "self", ")", ":", "status", "=", "self", ".", "status", "assert", "status", ">=", "COMPLETED", ",", "\"status is %s\"", "%", "status", "return", "(", "self", ".", "status", "==", "COMPLETED", ")" ]
49.142857
12.571429
def name(self) -> str: """The name of this application. This is taken from the :attr:`import_name` and is used for debugging purposes. """ if self.import_name == '__main__': path = Path(getattr(sys.modules['__main__'], '__file__', '__main__.py')) return p...
[ "def", "name", "(", "self", ")", "->", "str", ":", "if", "self", ".", "import_name", "==", "'__main__'", ":", "path", "=", "Path", "(", "getattr", "(", "sys", ".", "modules", "[", "'__main__'", "]", ",", "'__file__'", ",", "'__main__.py'", ")", ")", ...
35.1
16.4
def _kl_gumbel_gumbel(a, b, name=None): """Calculate the batched KL divergence KL(a || b) with a and b Gumbel. Args: a: instance of a Gumbel distribution object. b: instance of a Gumbel distribution object. name: (optional) Name to use for created operations. default is "kl_gumbel_gumbel". Ret...
[ "def", "_kl_gumbel_gumbel", "(", "a", ",", "b", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", "or", "\"kl_gumbel_gumbel\"", ")", ":", "# Consistent with", "# http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 64", ...
42.666667
18.458333
async def set_sampling_interval(self, interval): """ This method sends the desired sampling interval to Firmata. Note: Standard Firmata will ignore any interval less than 10 milliseconds :param interval: Integer value for desired sampling interval ...
[ "async", "def", "set_sampling_interval", "(", "self", ",", "interval", ")", ":", "data", "=", "[", "interval", "&", "0x7f", ",", "(", "interval", ">>", "7", ")", "&", "0x7f", "]", "await", "self", ".", "_send_sysex", "(", "PrivateConstants", ".", "SAMPLI...
38.615385
18
def pltvol(vrtces, plates): """ Compute the volume of a three-dimensional region bounded by a collection of triangular plates. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltvol_c.html :param vrtces: Array of vertices. :type vrtces: Nx3-Element Array of floats :param pl...
[ "def", "pltvol", "(", "vrtces", ",", "plates", ")", ":", "nv", "=", "ctypes", ".", "c_int", "(", "len", "(", "vrtces", ")", ")", "vrtces", "=", "stypes", ".", "toDoubleMatrix", "(", "vrtces", ")", "np", "=", "ctypes", ".", "c_int", "(", "len", "(",...
35.368421
12.947368
def run(files, temp_folder): "Check frosted errors in the code base." try: import frosted # NOQA except ImportError: return NO_FROSTED_MSG py_files = filter_python_files(files) cmd = 'frosted {0}'.format(' '.join(py_files)) return bash(cmd).value()
[ "def", "run", "(", "files", ",", "temp_folder", ")", ":", "try", ":", "import", "frosted", "# NOQA", "except", "ImportError", ":", "return", "NO_FROSTED_MSG", "py_files", "=", "filter_python_files", "(", "files", ")", "cmd", "=", "'frosted {0}'", ".", "format"...
25.545455
17.181818
def _find_longest_parent_path(path_set, path): """Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some fi...
[ "def", "_find_longest_parent_path", "(", "path_set", ",", "path", ")", ":", "# This could likely be more efficiently implemented with a trie", "# data-structure, but we don't want to add an extra dependency for that.", "while", "path", "not", "in", "path_set", ":", "if", "not", "...
40
23.153846
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ admin_metadata = self.get_admin_metadata() uuid = admin_metad...
[ "def", "get_item_abspath", "(", "self", ",", "identifier", ")", ":", "admin_metadata", "=", "self", ".", "get_admin_metadata", "(", ")", "uuid", "=", "admin_metadata", "[", "\"uuid\"", "]", "# Create directory for the specific dataset.", "dataset_cache_abspath", "=", ...
33.142857
17.457143
def remove_constants(source): '''Replaces Strings and Regexp literals in the source code with identifiers and *removes comments*. Identifier is of the format: PyJsStringConst(String const number)_ - for Strings PyJsRegExpConst(RegExp const number)_ - for RegExps Returns dict which rela...
[ "def", "remove_constants", "(", "source", ")", ":", "source", "=", "' '", "+", "source", "+", "'\\n'", "comments", "=", "[", "]", "inside_comment", ",", "single_comment", "=", "False", ",", "False", "inside_single", ",", "inside_double", "=", "False", ",", ...
40.583893
14.073826
def dt_from_header(date_str): """Try various RFC conversions to ``datetime`` or return ``None``. :param date_str: Date string. :type date_str: ``string`` :return: Date time. :rtype: :class:`datetime.datetime` or ``None`` """ convert_fns = ( dt_from_rfc8601, dt_from_rfc1123...
[ "def", "dt_from_header", "(", "date_str", ")", ":", "convert_fns", "=", "(", "dt_from_rfc8601", ",", "dt_from_rfc1123", ",", ")", "for", "convert_fn", "in", "convert_fns", ":", "try", ":", "return", "convert_fn", "(", "date_str", ")", "except", "ValueError", "...
22.9
18.05
def undo(self): """ Restore to last version """ log = getLogger('ocrd.workspace_backup.undo') backups = self.list() if backups: last_backup = backups[0] self.restore(last_backup.chksum, choose_first=True) else: log.info("No back...
[ "def", "undo", "(", "self", ")", ":", "log", "=", "getLogger", "(", "'ocrd.workspace_backup.undo'", ")", "backups", "=", "self", ".", "list", "(", ")", "if", "backups", ":", "last_backup", "=", "backups", "[", "0", "]", "self", ".", "restore", "(", "la...
30.272727
13.181818
def _create_err(self, errclass: str, *args) -> "Err": """ Create an error """ error = self._new_err(errclass, *args) self._add(error) return error
[ "def", "_create_err", "(", "self", ",", "errclass", ":", "str", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_new_err", "(", "errclass", ",", "*", "args", ")", "self", ".", "_add", "(", "error", ")", "return", "error" ]
26.857143
10.285714
def close(self): """ Close the current session """ self.active = False self.end = utcnow() self._model.save()
[ "def", "close", "(", "self", ")", ":", "self", ".", "active", "=", "False", "self", ".", "end", "=", "utcnow", "(", ")", "self", ".", "_model", ".", "save", "(", ")" ]
21.571429
10.142857
def write(self, title, data, output=None): ''' Add a data to the current opened section. :return: ''' if not isinstance(data, (dict, list, tuple)): data = {'raw-content': str(data)} output = output or self.__default_outputter if output != 'null': ...
[ "def", "write", "(", "self", ",", "title", ",", "data", ",", "output", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "(", "dict", ",", "list", ",", "tuple", ")", ")", ":", "data", "=", "{", "'raw-content'", ":", "str", "(", ...
35.269231
18.5
def setEditable(self, state): """ Sets whether or not the user can edit the items in the list by typing. :param state | <bool> """ self._editable = state if state: self.setEditTriggers(self.AllEditTriggers) else: ...
[ "def", "setEditable", "(", "self", ",", "state", ")", ":", "self", ".", "_editable", "=", "state", "if", "state", ":", "self", ".", "setEditTriggers", "(", "self", ".", "AllEditTriggers", ")", "else", ":", "self", ".", "setEditTriggers", "(", "self", "."...
29.583333
15.583333
def find_vote_inits(provider: Provider, deck: Deck) -> Iterable[Vote]: '''find vote_inits on this deck''' vote_ints = provider.listtransactions(deck_vote_tag(deck)) for txid in vote_ints: try: raw_vote = provider.getrawtransaction(txid) vote = parse_vote_info(read_tx_opretu...
[ "def", "find_vote_inits", "(", "provider", ":", "Provider", ",", "deck", ":", "Deck", ")", "->", "Iterable", "[", "Vote", "]", ":", "vote_ints", "=", "provider", ".", "listtransactions", "(", "deck_vote_tag", "(", "deck", ")", ")", "for", "txid", "in", "...
35.266667
19.666667
def _parse_meta(self, meta): """ Parse the _meta element from a dynamic host inventory output. """ for hostname, hostvars in meta.get('hostvars', {}).items(): for var_key, var_val in hostvars.items(): self._get_host(hostname)['hostvars'][var_key] = var_val
[ "def", "_parse_meta", "(", "self", ",", "meta", ")", ":", "for", "hostname", ",", "hostvars", "in", "meta", ".", "get", "(", "'hostvars'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "for", "var_key", ",", "var_val", "in", "hostvars", ".", "it...
44.285714
16
def notify_server_ready(self, language, config): """Notify language server availability to code editors.""" for index in range(self.get_stack_count()): editor = self.tabs.widget(index) if editor.language.lower() == language: editor.start_lsp_services(config)
[ "def", "notify_server_ready", "(", "self", ",", "language", ",", "config", ")", ":", "for", "index", "in", "range", "(", "self", ".", "get_stack_count", "(", ")", ")", ":", "editor", "=", "self", ".", "tabs", ".", "widget", "(", "index", ")", "if", "...
52.333333
7.833333
def standard_output_generation(self, groups, limit, points, out_of, check): ''' Generates the Terminal Output ''' if points < out_of: self.reasoning_routine(groups, check, priority_flag=limit) else: print("All tests passed!")
[ "def", "standard_output_generation", "(", "self", ",", "groups", ",", "limit", ",", "points", ",", "out_of", ",", "check", ")", ":", "if", "points", "<", "out_of", ":", "self", ".", "reasoning_routine", "(", "groups", ",", "check", ",", "priority_flag", "=...
35.25
21
def write(self): """ Writes the ``.sln`` file to disk. """ filters = { 'MSGUID': lambda x: ('{%s}' % x).upper(), 'relslnfile': lambda x: os.path.relpath(x, os.path.dirname(self.FileName)) } context = { 'sln': self } retu...
[ "def", "write", "(", "self", ")", ":", "filters", "=", "{", "'MSGUID'", ":", "lambda", "x", ":", "(", "'{%s}'", "%", "x", ")", ".", "upper", "(", ")", ",", "'relslnfile'", ":", "lambda", "x", ":", "os", ".", "path", ".", "relpath", "(", "x", ",...
31.75
20.75
def is_any_clicked(self): """Is any button clicked?""" for key in range(len(self.current_state.key_states)): if self.is_clicked(key): return True return False
[ "def", "is_any_clicked", "(", "self", ")", ":", "for", "key", "in", "range", "(", "len", "(", "self", ".", "current_state", ".", "key_states", ")", ")", ":", "if", "self", ".", "is_clicked", "(", "key", ")", ":", "return", "True", "return", "False" ]
34.166667
12.166667
def normalize(self): """ Reduce trivial AVM conjunctions to just the AVM. For example, in `[ ATTR1 [ ATTR2 val ] ]` the value of `ATTR1` could be a conjunction with the sub-AVM `[ ATTR2 val ]`. This method removes the conjunction so the sub-AVM nests directly (equivalent...
[ "def", "normalize", "(", "self", ")", ":", "for", "attr", "in", "self", ".", "_avm", ":", "val", "=", "self", ".", "_avm", "[", "attr", "]", "if", "isinstance", "(", "val", ",", "Conjunction", ")", ":", "val", ".", "normalize", "(", ")", "if", "l...
40.470588
15.294118
def source_lines(self, filename): """ Return a list for source lines of file `filename`. """ with self.filesystem.open(filename) as f: return f.readlines()
[ "def", "source_lines", "(", "self", ",", "filename", ")", ":", "with", "self", ".", "filesystem", ".", "open", "(", "filename", ")", "as", "f", ":", "return", "f", ".", "readlines", "(", ")" ]
32.333333
7
def _get_network_interface(name, resource_group): ''' Get a network interface. ''' public_ips = [] private_ips = [] netapi_versions = get_api_versions(kwargs={ 'resource_provider': 'Microsoft.Network', 'resource_type': 'publicIPAddresses' } ) netapi_version = neta...
[ "def", "_get_network_interface", "(", "name", ",", "resource_group", ")", ":", "public_ips", "=", "[", "]", "private_ips", "=", "[", "]", "netapi_versions", "=", "get_api_versions", "(", "kwargs", "=", "{", "'resource_provider'", ":", "'Microsoft.Network'", ",", ...
36.757576
18.636364
def combine_fields(dtypes): """Combines the fields in the list of given dtypes into a single dtype. Parameters ---------- dtypes : (list of) numpy.dtype(s) Either a numpy.dtype, or a list of numpy.dtypes. Returns ------- numpy.dtype A new dtype combining the fields in the l...
[ "def", "combine_fields", "(", "dtypes", ")", ":", "if", "not", "isinstance", "(", "dtypes", ",", "list", ")", ":", "dtypes", "=", "[", "dtypes", "]", "# Note: incase any of the dtypes have offsets, we won't include any fields", "# that have no names and are void", "new_dt...
30.75
18.25
def split(examples, ratio=0.8): """ Utility function that can be used within the parse() implementation of sub classes to split a list of example into two lists for training and testing. """ split = int(ratio * len(examples)) return examples[:split], examples[spli...
[ "def", "split", "(", "examples", ",", "ratio", "=", "0.8", ")", ":", "split", "=", "int", "(", "ratio", "*", "len", "(", "examples", ")", ")", "return", "examples", "[", ":", "split", "]", ",", "examples", "[", "split", ":", "]" ]
39.5
15
def uptodate(name, refresh=False, pkgs=None, **kwargs): ''' .. versionadded:: 2014.7.0 .. versionchanged:: 2018.3.0 Added support for the ``pkgin`` provider. Verify that the system is completely up to date. name The name has no functional value and is only used as a tracking ...
[ "def", "uptodate", "(", "name", ",", "refresh", "=", "False", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", "...
34.638889
26.101852
def parse_cell(line, world_size): """ Takes a string representing a CELL resource (as specified in Avida environment files) and a tuple representing the x and y dimensions of the world, and returns the name of the resource and a list of tuples representing the cells it's in. """ # Remove "CE...
[ "def", "parse_cell", "(", "line", ",", "world_size", ")", ":", "# Remove \"CELL \"", "line", "=", "line", "[", "4", ":", "]", "# Extract information", "sline", "=", "[", "i", ".", "strip", "(", ")", "for", "i", "in", "line", ".", "split", "(", "\":\"",...
31.6875
19.6875
def int_attribute(element, attribute, default=0): """ Returns the int value of an attribute, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param attribute: The name of the attribute to evaluate :type attribute: basestring :param de...
[ "def", "int_attribute", "(", "element", ",", "attribute", ",", "default", "=", "0", ")", ":", "attribute_value", "=", "element", ".", "get", "(", "attribute", ")", "if", "attribute_value", ":", "try", ":", "return", "int", "(", "attribute_value", ")", "exc...
27.086957
19.434783
def run(self): """Clean build, dist, pyc and egg from package and docs.""" super().run() call('rm -vrf ./build ./dist ./*.egg-info', shell=True) call('find . -name __pycache__ -type d | xargs rm -rf', shell=True) call('test -d docs && make -C docs/ clean', shell=True)
[ "def", "run", "(", "self", ")", ":", "super", "(", ")", ".", "run", "(", ")", "call", "(", "'rm -vrf ./build ./dist ./*.egg-info'", ",", "shell", "=", "True", ")", "call", "(", "'find . -name __pycache__ -type d | xargs rm -rf'", ",", "shell", "=", "True", ")"...
50.5
21