Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
10,100
def Scroll_up(self, n, dl = 0): self.Delay(dl) self.mouse.scroll(vertical = n)
鼠标滚轮向上n次
10,101
def update_portal(self, portal_obj): headers = { : self.user_agent(), } headers.update(self.headers()) r = requests.put( self.portals_url()++self.portal_id(), data=json.dumps(portal_obj), headers=headers...
Implements the Update device Portals API. This function is extremely dangerous. The portal object you pass in will completely overwrite the portal. http://docs.exosite.com/portals/#update-portal
10,102
def merge_single_qubit_gates_into_phased_x_z( circuit: circuits.Circuit, atol: float = 1e-8) -> None: def synth(qubit: ops.Qid, matrix: np.ndarray) -> List[ops.Operation]: out_gates = decompositions.single_qubit_matrix_to_phased_x_z( matrix, atol) return [gate(qubit...
Canonicalizes runs of single-qubit rotations in a circuit. Specifically, any run of non-parameterized circuits will be replaced by an optional PhasedX operation followed by an optional Z operation. Args: circuit: The circuit to rewrite. This value is mutated in-place. atol: Absolute tolera...
10,103
def transform(self): if self.dcmf1 is None or self.dcmf2 is None: return np.inf for field_name in self.field_weights: if (str(getattr(self.dcmf1, field_name, )) != str(getattr(self.dcmf2, field_name, ))): return False return ...
Check the field values in self.dcmf1 and self.dcmf2 and returns True if all the field values are the same, False otherwise. Returns ------- bool
10,104
def GetMetadataLegacy(client, token=None): if isinstance(client, rdfvalue.RDFURN): client_fd = aff4.FACTORY.Open(client, mode="r", token=token) else: client_fd = client metadata = ExportedMetadata() metadata.client_urn = client_fd.urn metadata.client_age = client_fd.urn.age metadata.hostname =...
Builds ExportedMetadata object for a given client id. Note: This is a legacy aff4-only implementation. TODO(user): deprecate as soon as REL_DB migration is done. Args: client: RDFURN of a client or VFSGRRClient object itself. token: Security token. Returns: ExportedMetadata object with metadata o...
10,105
def get_injuries_by_team(self, season, week, team_id): result = self._method_call("Injuries/{season}/{week}/{team_id}", "stats", season=season, week=week, team_id=team_id) return result
Injuries by week and team
10,106
def get_cluster(self, label): for cluster in self._clusters: if label == cluster[]: return self._get_connection(cluster) raise AttributeError( % label)
Returns a connection to a mongo-clusters. Args: label (string): the label of a cluster. Returns: A connection to the cluster labeld with label. Raises: AttributeError: there is no cluster with the given label in the config
10,107
def calcFontScaling(self): self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi self.fontSize = self.vertSize*(self.ypx/2.0) self.leftPos = self.axes.get_xlim()[0] self.rightPos = self.axes.get_xlim()[1]
Calculates the current font size and left position for the current window.
10,108
async def probe_message(self, _message, context): client_id = context.user_data await self.probe(client_id)
Handle a probe message. See :meth:`AbstractDeviceAdapter.probe`.
10,109
def issubset(self, other): return (set(self).issubset(set(other)) and set(self.iter_links()).issubset(set(other.iter_links())) and all(set(self[chip]).issubset(other[chip]) and all(self[chip][r] <= other[chip][r] for r in self[...
Test whether the resources available in this machine description are a (non-strict) subset of those available in another machine. .. note:: This test being False does not imply that the this machine is a superset of the other machine; machines may have disjoint reso...
10,110
def key_exists(self, namespace, key): return namespace in self.__data and key in self.__data[namespace]
Checks a namespace for the existence of a specific key Args: namespace (str): Namespace to check in key (str): Name of the key to check for Returns: `True` if key exists in the namespace, else `False`
10,111
def execute(self, shell = True): process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell) self.output, self.errors = process.communicate()
Executes the command setted into class Args: shell (boolean): Set True if command is a shell command. Default: True
10,112
def remove(item): if os.path.isdir(item): shutil.rmtree(item) else: os.remove(item)
Delete item, whether it's a file, a folder, or a folder full of other files and folders.
10,113
def scale_degree_to_bitmap(scale_degree, modulo=False, length=BITMAP_LENGTH): sign = 1 if scale_degree.startswith("*"): sign = -1 scale_degree = scale_degree.strip("*") edit_map = [0] * length sd_idx = scale_degree_to_semitone(scale_degree) if sd_idx < length or modulo: ...
Create a bitmap representation of a scale degree. Note that values in the bitmap may be negative, indicating that the semitone is to be removed. Parameters ---------- scale_degree : str Spelling of a relative scale degree, e.g. 'b3', '7', '#5' modulo : bool, default=True If a s...
10,114
def triplify(self, data, parent=None): if data is None: return if self.is_object: for res in self._triplify_object(data, parent): yield res elif self.is_array: for item in data: for res in self.items.triplify(item, par...
Recursively generate statements from the data supplied.
10,115
def randrange(seq): seq = seq.copy() choose = rng().choice remove = seq.remove for x in range(len(seq)): y = choose(seq) remove(y) yield y
Yields random values from @seq until @seq is empty
10,116
def next_partname(self, template): partnames = {part.partname for part in self.iter_parts()} for n in range(1, len(partnames) + 2): candidate_partname = template % n if candidate_partname not in partnames: return PackURI(candidate_partname)
Return a |PackURI| instance representing partname matching *template*. The returned part-name has the next available numeric suffix to distinguish it from other parts of its type. *template* is a printf (%)-style template string containing a single replacement item, a '%d' to be used to insert ...
10,117
def main(): parser = argparse.ArgumentParser(description="An interface to CarbonBlack environments") parser.add_argument(, , choices=auth.CredentialStore("response").get_profiles(), help=-t production\) parser.add_argument(, , type=str, help=production...
All VxStream related stuff may be removed in a future version
10,118
def edit_config_input_target_config_target_running_running(self, **kwargs): config = ET.Element("config") edit_config = ET.Element("edit_config") config = edit_config input = ET.SubElement(edit_config, "input") target = ET.SubElement(input, "target") config_targe...
Auto Generated Code
10,119
def checkCache(fnm, strip=0, upx=0): if ((not strip and not upx and not is_darwin and not is_win) or fnm.lower().endswith(".manifest")): return fnm if strip: strip = 1 else: strip = 0 if upx: upx = 1 else: upx = 0 ca...
Cache prevents preprocessing binary files again and again.
10,120
def reset_defaults(self): self.save_login.setChecked(False) self.save_password.setChecked(False) self.save_url.setChecked(False) set_setting(GEONODE_USER, ) set_setting(GEONODE_PASSWORD, ) set_setting(GEONODE_URL, ) self.login.setText() self.pas...
Reset login and password in QgsSettings.
10,121
def run_process(command, environ): log.info(, command, environ) env = dict(os.environ) env.update(environ) try: p = subprocess.Popen(args=command, env=env) except OSError as e: raise OSError( % (command, e)) log.debug(, p.pid) ret = p.wait() log.debug(, p.pid, ret) ...
Run the specified process and wait until it finishes. Use environ dict for environment variables.
10,122
def make_unique_script_attr(attributes): filtered_attr = [] script_list = [] for attr in attributes: if attr.Usage != TransactionAttributeUsage.Script: filtered_attr.append(attr) else: data = attr.Data if isinstance(data, UInt160): ...
Filter out duplicate `Script` TransactionAttributeUsage types. Args: attributes: a list of TransactionAttribute's Returns: list:
10,123
def _validate_indexers( self, indexers: Mapping, ) -> List[Tuple[Any, Union[slice, Variable]]]: from .dataarray import DataArray invalid = [k for k in indexers if k not in self.dims] if invalid: raise ValueError("dimensions %r do not exist" % invalid) ...
Here we make sure + indexer has a valid keys + indexer is in a valid data type + string indexers are cast to the appropriate date type if the associated index is a DatetimeIndex or CFTimeIndex
10,124
def rateServiceTypeInResult(discoveryResponse): if discoveryResponse is None: return 0 serviceType = discoveryResponse.service if serviceType.startswith("urn:dslforum-org:device"): return 11 if serviceType.startswith("urn:dslforum-org:service"): ...
Gives a quality rating for a given service type in a result, higher is better. Several UpnP devices reply to a discovery request with multiple responses with different service type announcements. To find the most specific one we need to be able rate the service types against each other. Usually...
10,125
async def create_link_secret(self, label: str) -> None: LOGGER.debug(, label) if not self.handle: LOGGER.debug(, self.name) raise WalletState(.format(self.name)) try: await anoncreds.prover_create_master_secret(self.handle, label) await...
Create link secret (a.k.a. master secret) used in proofs by HolderProver, if the current link secret does not already correspond to the input link secret label. Raise WalletState if wallet is closed, or any other IndyError causing failure to set link secret in wallet. :param label: lab...
10,126
def export_disks( self, standalone=True, dst_dir=None, compress=False, collect_only=False, with_threads=True, *args, **kwargs ): return self.provider.export_disks( standalone, dst_dir, compress, collect_only, with_threads, ...
Thin method that just uses the provider
10,127
def user_invite(self, username, email, roles): uri = data = { "username": username, "email": email, "roles": list(set(roles)) } post_body = json.dumps(data) resp, body = self.post(uri, body=post_body) self.expected_success(20...
Invite a user to the tenant.
10,128
def remove_tar_files(file_list): for f in file_list: if file_exists(f) and f.endswith(): os.remove(f)
Public function that removes temporary tar archive files in a local directory
10,129
def get_GET_array(request, var_name, fail_silently=True): vals = request.GET.getlist(var_name) if not vals: if fail_silently: return [] else: raise Exception, _("No array called in GET variables") % {: var_name} return vals
Returns the GET array's contents for the specified variable.
10,130
def get_stock_codes(self, cached=True, as_json=False): url = self.stocks_csv_url req = Request(url, None, self.headers) res_dict = {} if cached is not True or self.__CODECACHE__ is None: res = self.opener.open(req) if res is not None: ...
returns a dictionary with key as stock code and value as stock name. It also implements cache functionality and hits the server only if user insists or cache is empty :return: dict
10,131
def add_attachment(self, attachment): log = logging.getLogger(self.cls_logger + ) if not isinstance(attachment, SlackAttachment): msg = log.error(msg) raise ValueError(msg) self.attachments.append(attachment.attachment) log.debug(.format(a=at...
Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None
10,132
def create_channel(cls, address="spanner.googleapis.com:443", credentials=None): grpc_gcp_config = grpc_gcp.api_config_from_text_pb( pkg_resources.resource_string(__name__, _SPANNER_GRPC_CONFIG) ) options = [(grpc_gcp.API_CONFIG_CHANNEL_ARG, grpc_gcp_config)] return ...
Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If ...
10,133
def replace(self, record_id, fields, typecast=False): record_url = self.record_url(record_id) return self._put(record_url, json_data={"fields": fields, "typecast": typecast})
Replaces a record by its record id. All Fields are updated to match the new ``fields`` provided. If a field is not included in ``fields``, value will bet set to null. To update only selected fields, use :any:`update`. >>> record = airtable.match('Seat Number', '22A') >>> f...
10,134
def _get_all_headers(self, method, endpoint, request_bytes, custom_headers): headers = self._get_default_headers() headers.update(custom_headers) if self._api_context.token is not None: headers[self.HEADER_AUTHENTICATION] = self._api_context.token headers[self....
:type method: str :type endpoint: str :type request_bytes: bytes :type custom_headers: dict[str, str] :rtype: dict[str, str]
10,135
def add_user_role(self, user, role): self.project_service.set_auth(self._token_project) self.project_service.add_user_role(user, role)
Add role to given user. Args: user (string): User name. role (string): Role to assign. Raises: requests.HTTPError on failure.
10,136
def get_namespace(self, key): namespace = self.shared_namespaces.get(key) if namespace: return namespace ns = SharedNamespace(self.manager) self.shared_namespaces[key] = ns return ns
Returns a :class:`~bang.util.SharedNamespace` for the given :attr:`key`. These are used by :class:`~bang.deployers.deployer.Deployer` objects of the same ``deployer_class`` to coordinate control over multiple deployed instances of like resources. E.g. With 5 clones of an application ...
10,137
def _save_nb(nb_name): display(Javascript()) display(Javascript()) print(, end=) if _wait_for_save(nb_name): print("Saved .".format(nb_name)) else: logging.warning( "Could not save your notebook (timed out waiting for " "IPython save). Make sure your not...
Attempts to save notebook. If unsuccessful, shows a warning.
10,138
def transform(self, X, lenscale=None): r N, d = X.shape lenscale = self._check_dim(d, lenscale) return expit(cdist(X / lenscale, self.C / lenscale, ))
r""" Apply the sigmoid basis function to X. Parameters ---------- X: ndarray (N, d) array of observations where N is the number of samples, and d is the dimensionality of X. lenscale: float the length scale (scalar) of the RBFs to apply to X. ...
10,139
def _opt_to_args(cls, opt, val): no_value = ( "alloptions", "all-logs", "batch", "build", "debug", "experimental", "list-plugins", "list-presets", "list-profiles", "noreport", "quiet", "verify" ) count = ("verbose",) if opt in no_value: ...
Convert a named option and optional value to command line argument notation, correctly handling options that take no value or that have special representations (e.g. verify and verbose).
10,140
def control_valve_noise_g_2011(m, P1, P2, T1, rho, gamma, MW, Kv, d, Di, t_pipe, Fd, FL, FLP=None, FP=None, rho_pipe=7800.0, c_pipe=5000.0, P_air=101325.0, rho_air=1.2, c_air=343.0, An=-3.8, St...
r'''Calculates the sound made by a gas flowing through a control valve according to the standard IEC 60534-8-3 (2011) [1]_. Parameters ---------- m : float Mass flow rate of gas through the control valve, [kg/s] P1 : float Inlet pressure of the gas before valves and reducers [Pa] ...
10,141
def filter(self, func=None, **query): if callable(func): result = filter(func, self) result.insert(0, self.default_columns) return TableFu(result, **self.options) else: result = self for column, value in query.items(): ...
Tables can be filtered in one of two ways: - Simple keyword arguments return rows where values match *exactly* - Pass in a function and return rows where that function evaluates to True In either case, a new TableFu instance is returned
10,142
def getElements(self, zero_based=True, pared=False): points = self._points[:] elements = self._elements[:] offset = 0 if not zero_based: offset = 1 np = None if pared: np = NodePare() np.addPoints(points) np.parePo...
Get the elements of the mesh as a list of point index list. :param zero_based: use zero based index of points if true otherwise use 1-based index of points. :param pared: use the pared down list of points :return: A list of point index lists
10,143
def get_bond(iface): * path = os.path.join(_DEB_NETWORK_CONF_FILES, .format(iface)) return _read_file(path)
Return the content of a bond script CLI Example: .. code-block:: bash salt '*' ip.get_bond bond0
10,144
def update(self, date_expiry=values.unset, ttl=values.unset, mode=values.unset, status=values.unset, participants=values.unset): return self._proxy.update( date_expiry=date_expiry, ttl=ttl, mode=mode, status=status, participants...
Update the SessionInstance :param datetime date_expiry: The ISO 8601 date when the Session should expire :param unicode ttl: When the session will expire :param SessionInstance.Mode mode: The Mode of the Session :param SessionInstance.Status status: The new status of the resource ...
10,145
def dok15_s(k15): A, B = design(15) sbar = np.dot(B, k15) t = (sbar[0] + sbar[1] + sbar[2]) bulk = old_div(t, 3.) Kbar = np.dot(A, sbar) dels = k15 - Kbar dels, sbar = old_div(dels, t), old_div(sbar, t) So = sum(dels**2) sigma = np.sqrt(old_div(So, 9.)) retu...
calculates least-squares matrix for 15 measurements from Jelinek [1976]
10,146
def register(self, type): def _decorator(func): if isinstance(type, tuple): for t in type: self.func_registry[t] = func else: self.func_registry[type] = func return func return _decorator
Registers a custom formatting function with ub.repr2
10,147
def apply_rotation_scheme(self, backups_by_frequency, most_recent_backup): if not self.rotation_scheme: raise ValueError("Refusing to use empty rotation scheme! (all backups would be deleted)") for frequency, backups in backups_by_frequency.items(): if frequ...
Apply the user defined rotation scheme to the result of :func:`group_backups()`. :param backups_by_frequency: A :class:`dict` in the format generated by :func:`group_backups()`. :param most_recent_backup: The :class:`~datetime.datetime` of the most ...
10,148
def ExportMigrations(): from django.db.migrations.executor import MigrationExecutor if in connections and ( type(connections[]) == DatabaseWrapper): return for alias in connections.databases: executor =...
Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig.
10,149
def wake_lock_size(self): output = self.adb_shell(WAKE_LOCK_SIZE_CMD) if not output: return None return int(output.split("=")[1].strip())
Get the size of the current wake lock.
10,150
def increment_slug(s): slug_parts = s.split() try: slug_parts.append() return .join(slug_parts)
Generate next slug for a series. Some docstore types will use slugs (see above) as document ids. To support unique ids, we'll serialize them as follows: TestUserA/my-test TestUserA/my-test-2 TestUserA/my-test-3 ...
10,151
def main(): table_data = [ [, ], ] table = SingleTable(table_data) max_width = table.column_max_width(1) wrapped_string = .join(wrap(LONG_STRING, max_width)) table.table_data[0][1] = wrapped_string print(table.table)
Main function.
10,152
def get_tag(self, tagname, tagidx): return % (tagname, decode(getattr(self, tagname)[tagidx]))
:returns: the tag associated to the given tagname and tag index
10,153
def _GetBytes(partition_key): if isinstance(partition_key, six.string_types): return bytearray(partition_key, encoding=) else: raise ValueError("Unsupported " + str(type(partition_key)) + " for partitionKey.")
Gets the bytes representing the value of the partition key.
10,154
def print_version(ctx, value): if not value: return import pkg_resources version = None try: version = pkg_resources.get_distribution().version finally: del pkg_resources click.echo(version) ctx.exit()
Print the current version of sandman and exit.
10,155
def bust_self(self, obj): if self.func.__name__ in obj.__dict__: delattr(obj, self.func.__name__)
Remove the value that is being stored on `obj` for this :class:`.cached_property` object. :param obj: The instance on which to bust the cache.
10,156
def load_template_source(self, template_name, template_dirs=None): raise TemplateDoesNotExist(template_name)
Template loader that loads templates from zipped modules.
10,157
def has_ended(self): assessment_offered = self.get_assessment_offered() now = DateTime.utcnow() else: return False
Tests if this assessment has ended. return: (boolean) - ``true`` if the assessment has ended, ``false`` otherwise *compliance: mandatory -- This method must be implemented.*
10,158
def p_expr_number(p): "number : NUMBER" p[0] = node.number(p[1], lineno=p.lineno(1), lexpos=p.lexpos(1))
number : NUMBER
10,159
def config(self): if self._config: return self._config else: self._config = p_config.ProsperConfig(self.config_path) return self._config
uses "global config" for cfg
10,160
def _SnakeCaseToCamelCase(path_name): result = [] after_underscore = False for c in path_name: if c.isupper(): raise Error( .format(path_name)) if after_underscore: if c.islower(): result.append(c.upper()) after_underscore = False else: raise ...
Converts a path name from snake_case to camelCase.
10,161
def Rsky(self): return np.sqrt(self.position.x**2 + self.position.y**2)
Projected sky separation of stars
10,162
def bbox(self): if not hasattr(self, ): self._bbox = extract_bbox(self) return self._bbox
(left, top, right, bottom) tuple.
10,163
def do_array(self, parent=None, ident=0): log_debug("[array]", ident) _, classdesc = self._read_and_exec_opcode( ident=ident + 1, expect=( self.TC_CLASSDESC, self.TC_PROXYCLASSDESC, self.TC_NULL, se...
Handles a TC_ARRAY opcode :param parent: :param ident: Log indentation level :return: A list of deserialized objects
10,164
def users(self): result = self.db.read("", {"q": "ls"}) if result is None or result.json() is None: return [] users = [] for u in result.json(): usr = self(u["name"]) usr.metadata = u users.append(usr) return users
Returns the list of users in the database
10,165
def _default_commands(self): commands = [c() for c in find_commands(Command)] for ep in pkg_resources.iter_entry_points( group="enaml_native_command"): c = ep.load() if not issubclass(c, Command): print("Warning: entry point {} d...
Build the list of CLI commands by finding subclasses of the Command class Also allows commands to be installed using the "enaml_native_command" entry point. This entry point should return a Command subclass
10,166
def expand_branch_name(self, name): if not name: return self.default_revision unambiguous_name = prefix + name logger.debug("Branch name %r matches remote branch %r.", name, unambiguous_name) return unambiguous_name ...
Expand branch names to their unambiguous form. :param name: The name of a local or remote branch (a string). :returns: The unambiguous form of the branch name (a string). This internal method is used by methods like :func:`find_revision_id()` and :func:`find_revision_number()` to detec...
10,167
def forceValue(self, newVal, noteEdited=False): if newVal is None: newVal = "" self.choice.set(newVal) if noteEdited: self.widgetEdited(val=newVal, skipDups=False)
Force-set a parameter entry to the given value
10,168
def list_connections(self, status=None): if status is None: status = response, status_code = self.__pod__.Connection.get_v1_connection_list( sessionToken=self.__session__, status=status ).result() self.logger.debug( % (status_code, response))...
list connections
10,169
def get_forced_variation(self, experiment, user_id): forced_variations = experiment.forcedVariations if forced_variations and user_id in forced_variations: variation_key = forced_variations.get(user_id) variation = self.config.get_variation_from_key(experiment.key, variation_key) if vari...
Determine if a user is forced into a variation for the given experiment and return that variation. Args: experiment: Object representing the experiment for which user is to be bucketed. user_id: ID for the user. Returns: Variation in which the user with ID user_id is forced into. None if no ...
10,170
def _next_server(self): if self.options["dont_randomize"]: server = self._server_pool.pop(0) self._server_pool.append(server) else: shuffle(self._server_pool) s = None for server in self._server_pool: if self.options["max_reconnec...
Chooses next available server to connect.
10,171
def substring(ctx, full, start, length): full = next(string_arg(ctx, full), ) start = int(next(to_number(start))) length = int(next(to_number(length))) yield full[start-1:start-1+length]
Yields one string
10,172
def get_solvers(self, refresh=False, order_by=, **filters): def covers_op(prop, val): if not isinstance(prop, (list, tuple)) or not len(prop) == 2: raise ValueError("2-element list/tuple range required for LHS value") llo, lhi = min(pr...
Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_load'): Solver sorting key function (or :class:`Solver` attribute...
10,173
def atan(x): if isinstance(x, UncertainFunction): mcpts = np.arctan(x._mcpts) return UncertainFunction(mcpts) else: return np.arctan(x)
Inverse tangent
10,174
def run_cmd(cmd, echo=False, fail_silently=False, **kwargs): r out, err = None, None if echo: cmd_str = cmd if isinstance(cmd, string_types) else .join(cmd) kwargs[], kwargs[] = sys.stdout, sys.stderr print_message(.format(cmd_str)) else: out, err = get_temp_streams() ...
r"""Call given command with ``subprocess.call`` function. :param cmd: Command to run. :type cmd: tuple or str :param echo: If enabled show command to call and its output in STDOUT, otherwise hide all output. By default: False :param fail_silently: Do not raise exception on error. By def...
10,175
def from_json(cls, data): assert in data, assert in data, assert in data, collection = cls(Header.from_json(data[]), data[], [DateTime.from_json(dat) for dat in data[]]) if in data: collection._validated_a_period = data[] ...
Create a Data Collection from a dictionary. Args: { "header": A Ladybug Header, "values": An array of values, "datetimes": An array of datetimes, "validated_a_period": Boolean for whether header analysis_period is valid }
10,176
def ensure_directory(path): dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname)
Ensure directory exists for a given file path.
10,177
def extras_to_string(extras): if isinstance(extras, six.string_types): if extras.startswith("["): return extras else: extras = [extras] if not extras: return "" return "[{0}]".format(",".join(sorted(set(extras))))
Turn a list of extras into a string
10,178
def convert_body_to_unicode(resp): if type(resp) is not dict: return _convert_string_to_unicode(resp) else: body = resp.get() if body is not None: try: body[] = _convert_string_to_unicode( body[] ) ...
If the request or responses body is bytes, decode it to a string (for python3 support)
10,179
def process_word(word: str, to_lower: bool = False, append_case: Optional[str] = None) -> Tuple[str]: if all(x.isupper() for x in word) and len(word) > 1: uppercase = "<ALL_UPPER>" elif word[0].isupper(): uppercase = "<FIRST_UPPER>" else: uppercase = None if...
Converts word to a tuple of symbols, optionally converts it to lowercase and adds capitalization label. Args: word: input word to_lower: whether to lowercase append_case: whether to add case mark ('<FIRST_UPPER>' for first capital and '<ALL_UPPER>' for all caps) Returns...
10,180
def template_sunmoon(self, **kwargs): kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy[] = kwargs.get(, self.dataset(**kwargs)) kwargs_copy[] = kwargs.get( , self.component(**kwargs)) self._replace_none(kwargs_copy) ...
return the file name for sun or moon template files
10,181
def _preserve_settings(method: T.Callable) -> T.Callable: @functools.wraps(method) def _wrapper( old: "ObservableProperty", handler: T.Callable ) -> "ObservableProperty": new = method(old, handler) new.event = old.event new.observable = old.observable retu...
Decorator that ensures ObservableProperty-specific attributes are kept when using methods to change deleter, getter or setter.
10,182
def run(self): self.setup() if self.detach: self.econtext.detach() try: return self._run() finally: self.revert()
Set up the process environment in preparation for running an Ansible module. This monkey-patches the Ansible libraries in various places to prevent it from trying to kill the process on completion, and to prevent it from reading sys.stdin. :returns: Module result dictionary.
10,183
def path_to_text(self, path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = open(path, ) interpreter = PDFPageInterpreter(rsrcmgr, device) ...
Transform local PDF file to string. Args: path: path to PDF file. Returns: string.
10,184
def dropwhile(self, func=None): func = _make_callable(func) return Collection(dropwhile(func, self._items))
Return a new Collection with the first few items removed. Parameters: func : function(Node) -> Node Returns: A new Collection, discarding all items before the first item where bool(func(item)) == True
10,185
def apply_tfa_magseries(lcfile, timecol, magcol, errcol, templateinfo, mintemplatedist_arcmin=10.0, lcformat=, lcformatdir=None, ...
This applies the TFA correction to an LC given TFA template information. Parameters ---------- lcfile : str This is the light curve file to apply the TFA correction to. timecol,magcol,errcol : str These are the column keys in the lcdict for the LC file to apply the TFA correct...
10,186
def delete_expired_requests(): InclusionRequest.query.filter_by( InclusionRequest.expiry_date > datetime.utcnow()).delete() db.session.commit()
Delete expired inclusion requests.
10,187
def get_user(self, username="~"): url = self._build_url("users/%s/" % username, _prepend_namespace=False) response = self._get(url) check_response(response) return response
get info about user (if no user specified, use the one initiating request) :param username: str, name of user to get info about, default="~" :return: dict
10,188
def from_name(cls, name): result = cls.list({: 500}) webaccs = {} for webacc in result: webaccs[webacc[]] = webacc[] return webaccs.get(name)
Retrieve webacc id associated to a webacc name.
10,189
def switch_opt(default, shortname, help_msg): return ConfOpt(bool(default), True, shortname, dict(action=internal.Switch), True, help_msg, None)
Define a switchable ConfOpt. This creates a boolean option. If you use it in your CLI, it can be switched on and off by prepending + or - to its name: +opt / -opt. Args: default (bool): the default value of the swith option. shortname (str): short name of the option, no shortname will be u...
10,190
def set_working_dir(self, working_dir): yield from self.send(.format(working_dir)) self._working_dir = working_dir log.debug("Working directory set to {}".format(self._working_dir))
Sets the working directory for this hypervisor. :param working_dir: path to the working directory
10,191
def run(cls, raw_data): logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: logger.error( "{}.ImportError: Failed to load ...
description of run
10,192
def user_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users api_path = "/api/v2/users/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/users#show-user
10,193
def parse(cls, xml_path): parser = etree.XMLParser(target=cls.xml_parse()) return etree.parse(xml_path, parser)
Parses an xml_path with the inherited xml parser :param xml_path: :return:
10,194
def stop_plugins(watcher_plugin, health_plugin): logging.debug("Stopping health-check monitor...") health_plugin.stop() logging.debug("Stopping config change observer...") watcher_plugin.stop()
Stops all plugins.
10,195
def wind_speed_hub(self, weather_df): r if self.power_plant.hub_height in weather_df[]: wind_speed_hub = weather_df[][ self.power_plant.hub_height] elif self.wind_speed_model == : logging.debug( ) closest_height = weat...
r""" Calculates the wind speed at hub height. The method specified by the parameter `wind_speed_model` is used. Parameters ---------- weather_df : pandas.DataFrame DataFrame with time series for wind speed `wind_speed` in m/s and roughness length `roughn...
10,196
def decompose(self, noise=False, verbosity=0, logic=, **kwargs): matrix = self.get_dm(noise) est_scale = None if self._pruning_option == options.PRUNING_NONE: kp = len(matrix) - 1 ...
Use prune to remove links between distant points: prune is None: no pruning prune={int > 0}: prunes links beyond `prune` nearest neighbours prune='estimate': searches for the smallest value that retains a fully connected graph
10,197
def _find_classes_param(self): for attr in ["classes_"]: try: return getattr(self.estimator, attr) except AttributeError: continue raise YellowbrickTypeError( "could not find classes_ param on {}".format( self....
Searches the wrapped model for the classes_ parameter.
10,198
def stop(self): if self.__end.is_set(): return self.__end.set() self.__send_retry_requests_timer.cancel() self.__threadpool.stop() self.__crud_threadpool.stop() self.__amqplink.stop() self.__network_retry_thread.join() with se...
Stop the Client, disconnect from queue
10,199
def execute_action(self, agent, action): if action == : agent.location = loc_B agent.performance -= 1 elif action == : agent.location = loc_A agent.performance -= 1 elif action == : if self.status[agent.location] == : ...
Change agent's location and/or location's status; track performance. Score 10 for each dirt cleaned; -1 for each move.