Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
377,200 | def _requires_submission(self):
if self.dbcon_part is None:
return False
tables = get_table_list(self.dbcon_part)
nrows = 0
for table in tables:
if table == :
continue
nrows += get_number_of_rows(self.dbcon_part, table)
... | Returns True if the time since the last submission is greater than the submission interval.
If no submissions have ever been made, check if the database last modified time is greater than the
submission interval. |
377,201 | def name(self):
return next((self.names.get(x) for x in self._locales if x in
self.names), None) | Dict with locale codes as keys and localized name as value |
377,202 | def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0):
/etc/issuewb
error_count = 0
char = 0
cancel = 0
while True:
if error_count >= retry:
self.abort(timeout=timeout)
return Non... | Receive a stream via the XMODEM protocol.
>>> stream = file('/etc/issue', 'wb')
>>> print modem.recv(stream)
2342
Returns the number of bytes received on success or ``None`` in case of
failure. |
377,203 | def from_enum(gtype, enum_value):
pointer = vips_lib.vips_enum_nick(gtype, enum_value)
if pointer == ffi.NULL:
raise Error()
return _to_string(pointer) | Turn an int back into an enum string. |
377,204 | def colorscale(mag, cmin, cmax):
try:
x = float(mag-cmin)/(cmax-cmin)
except ZeroDivisionError:
x = 0.5
blue = min((max((4*(0.75-x), 0.)), 1.))
red = min((max((4*(x-0.25), 0.)), 1.))
green = min((max((4*abs(x-0.5)-1., 0.)), 1.))
return red, green, blue | Return a tuple of floats between 0 and 1 for R, G, and B.
From Python Cookbook (9.11?) |
377,205 | def update_variables(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if isinstance(result, tuple):
return self.process_register(result[0], result[1])
else:
return self.process_register(result)
return wrapper | Use this decorator on Step.action implementation.
Your action method should always return variables, or
both variables and output.
This decorator will update variables with output. |
377,206 | def info(dev):
**
if in dev:
qtype =
else:
qtype =
cmd = .format(qtype, dev)
udev_result = __salt__[](cmd, output_loglevel=)
if udev_result[] != 0:
raise CommandExecutionError(udev_result[])
return _parse_udevadm_info(udev_result[])[0] | Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0 |
377,207 | def neighbor_add(self, address, remote_as,
remote_port=DEFAULT_BGP_PORT,
enable_ipv4=DEFAULT_CAP_MBGP_IPV4,
enable_ipv6=DEFAULT_CAP_MBGP_IPV6,
enable_vpnv4=DEFAULT_CAP_MBGP_VPNV4,
enable_vpnv6=DEFAULT_CAP_MBGP_VPNV6... | This method registers a new neighbor. The BGP speaker tries to
establish a bgp session with the peer (accepts a connection
from the peer and also tries to connect to it).
``address`` specifies the IP address of the peer. It must be
the string representation of an IP address. Only IPv4 i... |
377,208 | def set_attributes(self, **kwargs):
kwargs = dict(kwargs)
for name,value in kwargs.items():
self.__getattr__(name)
try: self.setp(name,**value)
except TypeError:
try: self.setp(name,*value)
except (T... | Set a group of attributes (parameters and members). Calls
`setp` directly, so kwargs can include more than just the
parameter value (e.g., bounds, free, etc.). |
377,209 | def get_groups_of_account_apikey(self, account_id, api_key, **kwargs):
kwargs[] = True
if kwargs.get():
return self.get_groups_of_account_apikey_with_http_info(account_id, api_key, **kwargs)
else:
(data) = self.get_groups_of_account_apikey_with_http_info(acco... | Get groups of the API key. # noqa: E501
An endpoint for retrieving groups of the API key. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apiKey}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by de... |
377,210 | def __parse_aliases_line(self, raw_alias, raw_username):
alias = self.__encode(raw_alias)
username = self.__encode(raw_username)
return alias, username | Parse aliases lines |
377,211 | def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
logger.debug( % size)
for i in range(min_piece_size, max_piece_size):
if size / (2**i) < max_piece_count:
break
return 2**i | Calculates a good piece size for a size |
377,212 | def _lscmp(a, b):
return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b) | Compares two strings in a cryptographically save way:
Runtime is not affected by length of common prefix. |
377,213 | def _sam_to_grouped_umi_cl(data, umi_consensus, tx_out_file):
tmp_file = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]
jvm_opts = _get_fgbio_jvm_opts(data, os.path.dirname(tmp_file), 1)
cores, mem = _get_cores_memory(data)
bamsormadup = config_utils.get_program("bamsormadup", data)
cmd = (... | Mark duplicates on aligner output and convert to grouped UMIs by position.
Works with either a separate umi_file or UMI embedded in the read names. |
377,214 | def do_reparse(self, arg):
full = arg == "full"
from os import path
fullpath = path.abspath(self.tests[self.active].stagedir)
self.tests[self.active] = Analysis(fullpath, full) | Reparses the currently active unit test to get the latest test results loaded
to the console. |
377,215 | def quote(key, value):
if key in quoted_options and isinstance(value, string_types):
return "" % value
if key in quoted_bool_options and isinstance(value, bool):
return {True:,False:}[value]
return value | Certain options support string values. We want clients to be able to pass Python strings in
but we need them to be quoted in the output. Unfortunately some of those options also allow
numbers so we type check the value before wrapping it in quotes. |
377,216 | def com_google_fonts_check_smart_dropout(ttFont):
INSTRUCTIONS = b"\xb8\x01\xff\x85\xb0\x04\x8d"
if ("prep" in ttFont and
INSTRUCTIONS in ttFont["prep"].program.getBytecode()):
yield PASS, (" table contains instructions"
" enabling smart dropout control.")
else:
yield FAIL, (" ... | Font enables smart dropout control in "prep" table instructions?
B8 01 FF PUSHW 0x01FF
85 SCANCTRL (unconditinally turn on
dropout control mode)
B0 04 PUSHB 0x04
8D SCANTYPE (enable smart dropout control)
Smart dropout control means activating rules 1, 2 an... |
377,217 | def login(self, username, password, mode="demo"):
url = "https://trading212.com/it/login"
try:
logger.debug(f"visiting %s" % url)
self.browser.visit(url)
logger.debug(f"connected to %s" % url)
except selenium.common.exceptions.WebDriverException:
... | login function |
377,218 | def maxdiff_dtu_configurations(list_of_objects):
result = DtuConfiguration()
if len(list_of_objects) == 0:
return result
list_of_members = result.__dict__.keys()
for member in list_of_members:
tmp_array = np.array(
[tmp_dtu.__dict__[member] for tmp_dtu in list_o... | Return DtuConfiguration instance with maximum differences.
Parameters
----------
list_of_objects : python list
List of DtuConfiguration instances to be averaged.
Returns
-------
result : DtuConfiguration instance
Object with averaged values. |
377,219 | def _generate_sdss_object_name(
self):
self.log.info()
converter = unit_conversion(
log=self.log
)
for row in self.results:
raSex = converter.ra_decimal_to_sexegesimal(
ra=row["ra"],
delimit... | *generate sdss object names for the results*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: |
377,220 | def remove(self, observableElement):
if observableElement in self._observables:
self._observables.remove(observableElement) | remove an obsrvable element
:param str observableElement: the name of the observable element |
377,221 | def location_from_dictionary(d):
country = None
if in d and in d[]:
country = d[][]
if in d:
data = d[]
else:
data = d
if in data:
name = data[]
else:
name = None
if in data:
ID = int(data[])
else:
ID = None
if in dat... | Builds a *Location* object out of a data dictionary. Only certain
properties of the dictionary are used: if these properties are not
found or cannot be read, an error is issued.
:param d: a data dictionary
:type d: dict
:returns: a *Location* instance
:raises: *KeyError* if it is impossible to ... |
377,222 | def from_csv(cls, filename: str):
with open(filename, "r", encoding="utf-8") as f:
reader = csv.reader(f, delimiter=unicode2str(","),
quotechar=unicode2str("\""),
quoting=csv.QUOTE_MINIMAL)
entries = list()
... | Imports PDEntries from a csv.
Args:
filename: Filename to import from.
Returns:
List of Elements, List of PDEntries |
377,223 | def connect(self, ip_address, tsap_snap7, tsap_logo, tcpport=102):
logger.info("connecting to %s:%s tsap_snap7 %s tsap_logo %s" % (ip_address, tcpport,
tsap_snap7, tsap_logo))
self.set_param(snap7.snap7types... | Connect to a Siemens LOGO server. Howto setup Logo communication configuration see: http://snap7.sourceforge.net/logo.html
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1000)
:param tsap_logo: TSAP Logo Server (e.g. 20.00 = 0x2000) |
377,224 | def http_responder_factory(proto):
return GrowlerHTTPResponder(
proto,
request_factory=proto.http_application._request_class,
response_factory=proto.http_application._response_class,
) | The default factory function which creates a GrowlerHTTPResponder with
this object as the parent protocol, and the application's req/res
factory functions.
To change the default responder, overload this method with the same
to return your
own responder.
Params
-... |
377,225 | def segments_distance(segment1, segment2):
assert isinstance(segment1, LineSegment), \
"segment1 is not a LineSegment, but a %s" % type(segment1)
assert isinstance(segment2, LineSegment), \
"segment2 is not a LineSegment, but a %s" % type(segment2)
if len(get_segments_intersections(segm... | Calculate the distance between two line segments in the plane.
>>> a = LineSegment(Point(1,0), Point(2,0))
>>> b = LineSegment(Point(0,1), Point(0,2))
>>> "%0.2f" % segments_distance(a, b)
'1.41'
>>> c = LineSegment(Point(0,0), Point(5,5))
>>> d = LineSegment(Point(2,2), Point(4,4))
>>> e =... |
377,226 | def ip_to_array(ipaddress):
res = []
for i in ipaddress.split("."):
res.append(int(i))
assert len(res) == 4
return res | Convert a string representing an IPv4 address to 4 bytes. |
377,227 | def remove_internal_names(self):
self.visit(lambda n: setattr(n, , None), lambda n: not n.is_leaf) | Set the name of all non-leaf nodes in the subtree to None. |
377,228 | def _convert_to(maybe_device, convert_to):
if not convert_to or \
(convert_to == and maybe_device.startswith()) or \
maybe_device.startswith(.format(convert_to.upper())):
return maybe_device
if maybe_device.startswith():
blkid = __salt__[](maybe_device)
e... | Convert a device name, UUID or LABEL to a device name, UUID or
LABEL.
Return the fs_spec required for fstab. |
377,229 | def pull_log_dump(self, project_name, logstore_name, from_time, to_time, file_path, batch_size=None,
compress=None, encodings=None, shard_list=None, no_escape=None):
file_path = file_path.replace("{}", "{0}")
if "{0}" not in file_path:
file_path += "{0}"
... | dump all logs seperatedly line into file_path, file_path, the time parameters are log received time on server side.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type from_time: str... |
377,230 | def get_sensor_code_by_number(si, mtype, sensor_number, quiet=False):
try:
if in si[mtype][sensor_number]:
orientation = si[mtype][sensor_number][]
else:
orientation = ""
return "%s%s-%s-%s-%s" % (mtype,
orientation,
... | Given a sensor number, get the full sensor code (e.g. ACCX-UB1-L2C-M)
:param si: dict, sensor index json dictionary
:param mtype: str, sensor type
:param sensor_number: int, number of sensor
:param quiet: bool, if true then return None if not found
:return: str or None, sensor_code: a sensor code (... |
377,231 | def item_enclosure_length(self, item):
try:
return str(item.image.size)
except (AttributeError, ValueError, os.error):
pass
return | Try to obtain the size of the enclosure if it's present on the FS,
otherwise returns an hardcoded value.
Note: this method is only called if item_enclosure_url
has returned something. |
377,232 | def find_users(session, *usernames):
user_string = .join(usernames)
return _make_request(session, FIND_USERS_URL, user_string) | Find multiple users by name. |
377,233 | def sos_get_command_output(command, timeout=300, stderr=False,
chroot=None, chdir=None, env=None,
binary=False, sizelimit=None, poller=None):
def _child_prep_fn():
if (chroot):
os.chroot(chroot)
if (chdir):
... | Execute a command and return a dictionary of status and output,
optionally changing root or current working directory before
executing command. |
377,234 | def create_volume(self, volume, size, **kwargs):
data = {"size": size}
data.update(kwargs)
return self._request("POST", "volume/{0}".format(volume), data) | Create a volume and return a dictionary describing it.
:param volume: Name of the volume to be created.
:type volume: str
:param size: Size in bytes, or string representing the size of the
volume to be created.
:type size: int or str
:param \*\*kwargs: See t... |
377,235 | def _send_resource(self, environ, start_response, is_head_method):
path = environ["PATH_INFO"]
res = self._davProvider.get_resource_inst(path, environ)
if util.get_content_length(environ) != 0:
self._fail(
HTTP_MEDIATYPE_NOT_SUPPORTED,
"The s... | If-Range
If the entity is unchanged, send me the part(s) that I am missing;
otherwise, send me the entire new entity
If-Range: "737060cd8c284d8af7ad3082f209582d"
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.27 |
377,236 | def can_rename(self):
return len(self._paths) == 1 and (
self._paths[0].is_file() or
blobxfer.models.upload.LocalSourcePath.is_stdin(
str(self._paths[0]))
) | Check if source can be renamed
:param LocalSourcePath self: this
:rtype: bool
:return: if rename possible |
377,237 | def set_frame_parameters(self, profile_index: int, frame_parameters) -> None:
self.frame_parameters_changed_event.fire(profile_index, frame_parameters) | Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matches the record settings index, call set record frame parameters. |
377,238 | def _cleanup_workflow(config, task_id, args, **kwargs):
from lightflow.models import Workflow
if isinstance(args[0], Workflow):
if config.celery[] == 0:
AsyncResult(task_id).forget() | Cleanup the results of a workflow when it finished.
Connects to the postrun signal of Celery. If the signal was sent by a workflow,
remove the result from the result backend.
Args:
task_id (str): The id of the task.
args (tuple): The arguments the task was started with.
**kwargs: K... |
377,239 | def to_(self, data_pts):
data_pts = np.asarray(data_pts, dtype=np.float)
has_z = (data_pts.shape[-1] > 2)
if self.use_center:
data_pts = data_pts - self.viewer.data_off
ref_pt = [self.viewer._org_x, self.viewer._org_y]
if has_z:
ref_pt.... | Reverse of :meth:`from_`. |
377,240 | def info(self, exp_path=False, project_path=False, global_path=False,
config_path=False, complete=False, no_fix=False,
on_projects=False, on_globals=False, projectname=None,
return_dict=False, insert_id=True, only_keys=False,
archives=False, **kwargs):
... | Print information on the experiments
Parameters
----------
exp_path: bool
If True/set, print the filename of the experiment configuration
project_path: bool
If True/set, print the filename on the project configuration
global_path: bool
If True... |
377,241 | def squared_toroidal_dist(p1, p2, world_size=(60, 60)):
halfx = world_size[0]/2.0
if world_size[0] == world_size[1]:
halfy = halfx
else:
halfy = world_size[1]/2.0
deltax = p1[0] - p2[0]
if deltax < -halfx:
deltax += world_size[0]
elif deltax > halfx:
deltax ... | Separated out because sqrt has a lot of overhead |
377,242 | def _make_sprite_image(images, save_path):
if isinstance(images, np.ndarray):
images = nd.array(images, dtype=images.dtype, ctx=current_context())
elif not isinstance(images, (NDArray, np.ndarray)):
raise TypeError(
.format(str(type(images))))
assert isinstance(... | Given an NDArray as a batch images, make a sprite image out of it following the rule
defined in
https://www.tensorflow.org/programmers_guide/embedding
and save it in sprite.png under the path provided by the user. |
377,243 | def phase_fraction(im, normed=True):
r
if im.dtype == bool:
im = im.astype(int)
elif im.dtype != int:
raise Exception()
labels = sp.arange(0, sp.amax(im)+1)
results = sp.zeros_like(labels)
for i in labels:
results[i] = sp.sum(im == i)
if normed:
results = resu... | r"""
Calculates the number (or fraction) of each phase in an image
Parameters
----------
im : ND-array
An ND-array containing integer values
normed : Boolean
If ``True`` (default) the returned values are normalized by the total
number of voxels in image, otherwise the voxel ... |
377,244 | def calc_route_info(self, real_time=True, stop_at_bounds=False, time_delta=0):
route = self.get_route(1, time_delta)
results = route[]
route_time, route_distance = self._add_up_route(results, real_time=real_time, stop_at_bounds=stop_at_bounds)
self.log.info(, route_time, route_... | Calculate best route info. |
377,245 | def listdir(self, path=):
self._connect()
if self.sftp:
contents = self._sftp_listdir(path)
else:
contents = self._ftp_listdir(path)
self._close()
return contents | Gets an list of the contents of path in (s)FTP |
377,246 | def exclude(self, *args, **kwargs):
if in kwargs:
kwargs = self.get_filter_args_with_path(False, **kwargs)
return super(FileNodeManager, self).exclude(*args, **kwargs) | Works just like the default Manager's :func:`exclude` method, but
you can pass an additional keyword argument named ``path`` specifying
the full **path of the folder whose immediate child objects** you
want to exclude, e.g. ``"path/to/folder"``. |
377,247 | def get_kafka_brokers():
if not os.environ.get():
raise RuntimeError()
return [.format(parsedUrl.hostname, parsedUrl.port) for parsedUrl in
[urlparse(url) for url in os.environ.get().split()]] | Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects. |
377,248 | def create_from_fits(cls, fitsfile, norm_type=,
hdu_scan="SCANDATA",
hdu_energies="EBOUNDS",
irow=None):
if irow is not None:
tab_s = Table.read(fitsfile, hdu=hdu_scan)[irow]
else:
tab_s = Table.r... | Create a CastroData object from a tscube FITS file.
Parameters
----------
fitsfile : str
Name of the fits file
norm_type : str
Type of normalization to use. Valid options are:
* norm : Normalization w.r.t. to test source
* flux : Flux ... |
377,249 | def __upload(self, resource, bytes):
headers = {
: http_time(self.options.get(, self._DEFAULT_EXPIRE)),
: str(self._file_size),
: self.content_type
}
return Request(self._client, , resource,
domain=self._DEFAULT_DOMAI... | Performs a single chunk upload. |
377,250 | def start (self):
self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback) | Starts (Subscribes) the client. |
377,251 | def restore_repository_from_recycle_bin(self, repository_details, project, repository_id):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if repository_id is not None:
route_values[] = self._serialize.url(, repository_... | RestoreRepositoryFromRecycleBin.
[Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrecoverable.
:param :class:`<GitRecycleBinRepositoryDetails> <azure.devops.v5_1.git.models.GitRec... |
377,252 | def get(cls, resource_id=None, parent_id=None, grandparent_id=None):
if not resource_id:
return cls._get_all(parent_id, grandparent_id)
else:
return cls._get(resource_id, parent_id, grandparent_id) | Retrieves the required resources.
:param resource_id: The identifier for the specific resource
within the resource type.
:param parent_id: The identifier for the specific ancestor
resource within the resource type.
:p... |
377,253 | def sendstop(self):
if not self.is_started:
raise EasyProcessError(self, )
log.debug(, self.pid, self.cmd)
if self.popen:
if self.is_alive():
log.debug()
try:
try:
self.popen.terminate(... | Kill process (:meth:`subprocess.Popen.terminate`).
Do not wait for command to complete.
:rtype: self |
377,254 | def unmarshal(self, value, bind_client=None):
if not isinstance(value, self.type):
o = self.type()
if bind_client is not None and hasattr(o.__class__, ):
o.bind_client = bind_client
if isinstance(value, dict):
for (k, v) in v... | Cast the specified value to the entity type. |
377,255 | def create(self, ospf_process_id, vrf=None):
value = int(ospf_process_id)
if not 0 < value < 65536:
raise ValueError()
command = .format(ospf_process_id)
if vrf:
command += % vrf
return self.configure(command) | Creates a OSPF process in the specified VRF or the default VRF.
Args:
ospf_process_id (str): The OSPF process Id value
vrf (str): The VRF to apply this OSPF process to
Returns:
bool: True if the command completed successfully
Exception:
... |
377,256 | def propose_value(self, value, assume_leader=False):
if value is None:
raise ValueError("Not allowed to propose value None")
paxos = self.paxos_instance
paxos.leader = assume_leader
msg = paxos.propose_value(value)
if msg is None:
msg = paxos.prep... | Proposes a value to the network. |
377,257 | def move(self, remote_path_from, remote_path_to, overwrite=False):
urn_from = Urn(remote_path_from)
if not self.check(urn_from.path()):
raise RemoteResourceNotFound(urn_from.path())
urn_to = Urn(remote_path_to)
if not self.check(urn_to.parent()):
raise R... | Moves resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE
:param remote_path_from: the path to resource which will be moved,
:param remote_path_to: the path where resource will be moved.
:param overw... |
377,258 | def _get_config(self, path=None):
if not path and not self.option("config"):
raise Exception("The --config|-c option is missing.")
if not path:
path = self.option("config")
filename, ext = os.path.splitext(path)
if ext in [".yml", ".yaml"]:
... | Get the config.
:rtype: dict |
377,259 | def data(self, name, chunk, body):
self.callRemote(Data, name=name, chunk=chunk, body=body) | Issue a DATA command
return None
Sends a chunk of data to a peer. |
377,260 | def evaluate_report(report):
if report["valid"]:
return
for warn in report["warnings"]:
LOGGER.warning(warn)
for err in report["tables"][0]["errors"]:
LOGGER.error(err["message"])
raise ValueError("Invalid data file. Please see errors... | Iterate over validation errors. |
377,261 | def add_generator_action(self, action):
if not isinstance(action, GeneratorAction):
raise RuntimeError()
self.__generator_actions.append(action) | Attach/add one :class:`GeneratorAction`.
Warning:
The order in which you add :class:`GeneratorAction` objects **is** important in case of conflicting :class:`GeneratorAction` objects:
**only** the **first compatible** :class:`GeneratorAction` object will be used to generate the (source ... |
377,262 | def add_command_line_options(cls, parser):
if "add_argument" in dir(parser):
return cls.add_command_line_options_argparse(parser)
else:
return cls.add_command_line_options_optparse(parser) | function to inject command line parameters |
377,263 | def add_color(self, name, model, description):
r
if self.color is False:
self.packages.append(Package("color"))
self.color = True
self.preamble.append(Command("definecolor", arguments=[name,
model,
... | r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The values to use to define the color |
377,264 | 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:
... | Reads a table from the database, and writes SQL to replicate the table's
data to the output ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
table_name: name of the table
fileobj: file-like object to write to
wheredict: optional dictionary of ``{column_name: value}`` to use... |
377,265 | def imread(files, **kwargs):
kwargs_file = parse_kwargs(kwargs, , , ,
, , ,
, , )
kwargs_seq = parse_kwargs(kwargs, )
if kwargs.get(, None) is not None:
if kwargs.get(, None) is not None:
raise TypeError(
... | Return image data from TIFF file(s) as numpy array.
Refer to the TiffFile and TiffSequence classes and their asarray
functions for documentation.
Parameters
----------
files : str, binary stream, or sequence
File name, seekable binary stream, glob pattern, or sequence of
file name... |
377,266 | def save(self, filepath=None, filename=None, mode="md"):
if mode not in ["html", "md", "markdown"]:
raise ValueError("`mode` must be , or ,"
" got {0}".format(mode))
self._make_soup()
file = get_path(filepath, filename, mode, self.column.name,
... | 保存答案为 Html 文档或 markdown 文档.
:param str filepath: 要保存的文件所在的目录,
不填为当前目录下以专栏标题命名的目录, 设为"."则为当前目录。
:param str filename: 要保存的文件名,
不填则默认为 所在文章标题 - 作者名.html/md。
如果文件已存在,自动在后面加上数字区分。
**自定义文件名时请不要输入后缀 .html 或 .md。**
:param str mode: 保存类型,可选 `html` 、 `markd... |
377,267 | def send_reminder(self, user, sender=None, **kwargs):
if user.is_active:
return False
token = RegistrationTokenGenerator().make_token(user)
kwargs.update({"token": token})
self.email_message(
user, self.reminder_subject, self.reminder_body, sender, **kwar... | Sends a reminder email to the specified user |
377,268 | def nmb_weights_hidden(self) -> int:
nmb = 0
for idx_layer in range(self.nmb_layers-1):
nmb += self.nmb_neurons[idx_layer] * self.nmb_neurons[idx_layer+1]
return nmb | Number of hidden weights.
>>> from hydpy import ANN
>>> ann = ANN(None)
>>> ann(nmb_inputs=2, nmb_neurons=(4, 3, 2), nmb_outputs=3)
>>> ann.nmb_weights_hidden
18 |
377,269 | def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3,
maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True):
if not hasattr(x_in, ):
x_in = [x_in, ]
if not hasattr(y_in, ):
y_in = [y_in, ]
if (not os.path.exists(fits_filename) and
... | Compute the centroids and magnitudes of a bunch sources on fits image.
:rtype : astropy.table.Table
:param fits_filename: Name of fits image to measure source photometry on.
:type fits_filename: str
:param x_in: x location of source to measure
:type x_in: float, numpy.array
:param y_in: y loca... |
377,270 | def state(self, state):
assert state !=
self.buildstate.state.current = state
self.buildstate.state[state] = time()
self.buildstate.state.lasttime = time()
self.buildstate.state.error = False
self.buildstate.state.exception = None
self.buildstate.stat... | Set the current build state and record the time to maintain history.
Note! This is different from the dataset state. Setting the build set is commiteed to the
progress table/database immediately. The dstate is also set, but is not committed until the
bundle is committed. So, the dstate changes ... |
377,271 | def fingerprint(
self,
phrase,
phonetic_algorithm=double_metaphone,
joiner=,
*args,
**kwargs
):
phonetic =
for word in phrase.split():
word = phonetic_algorithm(word, *args, **kwargs)
if not isinstance(word, text_type)... | Return the phonetic fingerprint of a phrase.
Parameters
----------
phrase : str
The string from which to calculate the phonetic fingerprint
phonetic_algorithm : function
A phonetic algorithm that takes a string and returns a string
(presumably a phone... |
377,272 | def get_settings_from_client(client):
settings = {
: ,
: ,
: ,
: ,
}
try:
settings[] = client.auth.username
settings[] = client.auth.api_key
except AttributeError:
pass
transport = _resolve_transport(client.transport)
try:
set... | Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance |
377,273 | def extended_key_usage(self):
try:
ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE)
except x509.ExtensionNotFound:
return None
return ExtendedKeyUsage(ext) | The :py:class:`~django_ca.extensions.ExtendedKeyUsage` extension, or ``None`` if it doesn't
exist. |
377,274 | def add_status_code(code):
def class_decorator(cls):
cls.status_code = code
_mprpc_exceptions[code] = cls
return cls
return class_decorator | 用于将mprpc的标准异常注册到`_mprpc_exceptions`的装饰器.
Parameters:
code (int): - 标准状态码
Return:
(Callable): - 装饰函数 |
377,275 | def set_system_time(self, time_source, ntp_server, date_format,
time_format, time_zone, is_dst, dst, year,
mon, day, hour, minute, sec, callback=None):
if ntp_server not in [,
,
,
... | Set systeim time |
377,276 | def get_command(self, ctx: click.Context, name: str) -> click.Command:
info = ctx.ensure_object(ScriptInfo)
command = None
try:
command = info.load_app().cli.get_command(ctx, name)
except NoAppException:
pass
if command is None:
comman... | Return the relevant command given the context and name.
.. warning::
This differs substaintially from Flask in that it allows
for the inbuilt commands to be overridden. |
377,277 | def pressure_tendency(code: str, unit: str = ) -> str:
width, precision = int(code[2:4]), code[4]
return (
f) | Translates a 5-digit pressure outlook code
Ex: 50123 -> 12.3 mb: Increasing, then decreasing |
377,278 | def _mod_run_check(cmd_kwargs, onlyif, unless):
if onlyif:
if __salt__[](onlyif, **cmd_kwargs) != 0:
return {: ,
: True,
: True}
if unless:
if __salt__[](unless, **cmd_kwargs) == 0:
return {: ,
: True,
... | Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True |
377,279 | def run_to_selected_state(self, path, state_machine_id=None):
if self.state_machine_manager.get_active_state_machine() is not None:
self.state_machine_manager.get_active_state_machine().root_state.recursively_resume_states()
if not self.finished_or_stopped():
logger.deb... | Execute the state machine until a specific state. This state won't be executed. This is an asynchronous task |
377,280 | def op_canonicalize(op_name, parsed_op):
global CANONICALIZE_METHODS
if op_name not in CANONICALIZE_METHODS:
return parsed_op
else:
return CANONICALIZE_METHODS[op_name](parsed_op) | Get the canonical representation of a parsed operation's data.
Meant for backwards-compatibility |
377,281 | def process_constraints(self, inequalities=None, equalities=None,
momentinequalities=None, momentequalities=None,
block_index=0, removeequalities=False):
self.status = "unsolved"
if block_index == 0:
if self._original_F is not ... | Process the constraints and generate localizing matrices. Useful
only if the moment matrix already exists. Call it if you want to
replace your constraints. The number of the respective types of
constraints and the maximum degree of each constraint must remain the
same.
:param in... |
377,282 | def dispatch(self, event: Event) -> Iterator[Any]:
LOG.debug(, event.get("type"))
if event["type"] in self._routes:
for detail_key, detail_values in self._routes.get(
event["type"], {}
).items():
event_value = event.get(detail_key, "*")
... | Yields handlers matching the routing of the incoming :class:`slack.events.Event`.
Args:
event: :class:`slack.events.Event`
Yields:
handler |
377,283 | def remove_cons_vars_from_problem(model, what):
context = get_context(model)
model.solver.remove(what)
if context:
context(partial(model.solver.add, what)) | Remove variables and constraints from a Model's solver object.
Useful to temporarily remove variables and constraints from a Models's
solver object.
Parameters
----------
model : a cobra model
The model from which to remove the variables and constraints.
what : list or tuple of optlang ... |
377,284 | def get_url(params):
baseurl = .format(
**app.config)
with app.test_request_context():
return urllib.parse.urljoin(
baseurl,
url_for(, **params),
) | Return external URL for warming up a given chart/table cache. |
377,285 | def p_instanceDeclaration(p):
alias = None
quals = OrderedDict()
ns = p.parser.handle.default_namespace
if isinstance(p[1], six.string_types):
cname = p[3]
if p[4] == :
props = p[5]
else:
props = p[6]
alias = p[4]
else:
... | instanceDeclaration : INSTANCE OF className '{' valueInitializerList '}' ';'
| INSTANCE OF className alias '{' valueInitializerList '}' ';'
| qualifierList INSTANCE OF className '{' valueInitializerList '}' ';'
| qualifierList INSTANCE OF ... |
377,286 | def _parse_octet(self, octet_str):
if not octet_str:
raise ValueError("Empty octet not permitted")
if not self._DECIMAL_DIGITS.issuperset(octet_str):
msg = "Only decimal digits permitted in %r"
raise ValueError(msg % octet_str)
... | Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255]. |
377,287 | def _build_integer_type(var, property_path=None):
if not property_path:
property_path = []
schema = {"type": "integer"}
if is_builtin_type(var):
return schema
if is_config_var(var):
schema.update(
_build_attribute_modifiers(var, {"min": "minimum", "max": "maxi... | Builds schema definitions for integer type values.
:param var: The integer type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The built schema definition
:rtype: Dict[str, Any] |
377,288 | def preprocess_worksheet(self, table, worksheet):
table_conversion = []
flags = {}
units = {}
for rind, row in enumerate(table):
conversion_row = []
table_conversion.append(conversion_row)
if self.skippable_rows and worksheet in self.skippable... | Performs a preprocess pass of the table to attempt naive conversions of data and to record
the initial types of each cell. |
377,289 | def do_usufy(self, query, **kwargs):
results = []
test = self.check_usufy(query, **kwargs)
if test:
r = {
"type": "i3visio.profile",
"value": self.platformName + " - " + query,
"attributes": []
}
... | Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be appended. |
377,290 | def get_data_pct(self, xpct, ypct):
xy_mn, xy_mx = self.get_limits()
width = abs(xy_mx[0] - xy_mn[0])
height = abs(xy_mx[1] - xy_mn[1])
x, y = int(float(xpct) * width), int(float(ypct) * height)
return (x, y) | Calculate new data size for the given axis ratios.
See :meth:`get_limits`.
Parameters
----------
xpct, ypct : float
Ratio for X and Y, respectively, where 1 is 100%.
Returns
-------
x, y : int
Scaled dimensions. |
377,291 | def retry(num_attempts=3, exception_class=Exception, log=None, sleeptime=1):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for i in range(num_attempts):
try:
return func(*args, **kwargs)
except exceptio... | >>> def fail():
... runs[0] += 1
... raise ValueError()
>>> runs = [0]; retry(sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>> runs
[3]
>>> runs = [0]; retry(2, sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>... |
377,292 | def make_file_object_logger(fh):
def logger_func(stmt, args, fh=fh):
now = datetime.datetime.now()
six.print_("Executing (%s):" % now.isoformat(), file=fh)
six.print_(textwrap.dedent(stmt), file=fh)
six.print_("Arguments:", file=fh)
pprint.pprint(args, fh)
r... | Make a logger that logs to the given file object. |
377,293 | def nd_load_and_stats(filenames, base_path=BASEPATH):
nds = []
for filename in filenames:
try:
nd_load = results.load_nd_from_pickle(filename=
os.path.join(base_path,
,... | Load multiple files from disk and generate stats
Passes the list of files assuming the ding0 data structure as default in
:code:`~/.ding0`.
Data will be concatenated and key indicators for each grid district are
returned in table and graphic format.
Parameters
----------
filenames : list o... |
377,294 | def _within_box(points, boxes):
x_within = (points[..., 0] >= boxes[:, 0, None]) & (
points[..., 0] <= boxes[:, 2, None]
)
y_within = (points[..., 1] >= boxes[:, 1, None]) & (
points[..., 1] <= boxes[:, 3, None]
)
return x_within & y_within | Validate which keypoints are contained inside a given box.
points: NxKx2
boxes: Nx4
output: NxK |
377,295 | def get_nameserver_detail_output_show_nameserver_nameserver_ag_base_device(self, **kwargs):
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
output = ET.SubElement(get_nameserver_detail, "output")
sh... | Auto Generated Code |
377,296 | def function_exclusion_filter_builder(func: Strings) -> NodePredicate:
if isinstance(func, str):
def function_exclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
return node[FUNCTION] != func
return function_exclusion_filter
elif isinstance(func, Iterable):
... | Build a filter that fails on nodes of the given function(s).
:param func: A BEL Function or list/set/tuple of BEL functions |
377,297 | def explore(args):
logger.info("reading sequeces")
data = load_data(args.json)
logger.info("get sequences from json")
c1, c2 = args.names.split(",")
seqs, names = get_sequences_from_cluster(c1, c2, data[0])
loci = get_precursors_from_cluster(c1, c2, data[0])
logger.info("map all se... | Create mapping of sequences of two clusters |
377,298 | def analyze(self, text):
try:
self.process
text = render_safe(text).replace(, ).lower()
results = []
for chunk in string_pieces(text):
self.send_input((chunk + ).encode())
while True:
out_line = self.r... | Runs a line of text through MeCab, and returns the results as a
list of lists ("records") that contain the MeCab analysis of each
word. |
377,299 | async def expand_all_quays(self) -> None:
if not self.stops:
return
headers = {: self._client_name}
request = {
: GRAPHQL_STOP_TO_QUAY_TEMPLATE,
: {
: self.stops,
: self.omit_non_boarding
}
}
... | Find all quays from stop places. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.