Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
368,300 | def set_id(self,my_id):
if self.type == :
self.node.set(,my_id)
elif self.type == :
self.node.set(,my_id) | Sets the opinion identifier
@type my_id: string
@param my_id: the opinion identifier |
368,301 | def save_global(self, obj, name=None, pack=struct.pack):
if obj is type(None):
return self.save_reduce(type, (None,), obj=obj)
elif obj is type(Ellipsis):
return self.save_reduce(type, (Ellipsis,), obj=obj)
elif obj is type(NotImplemented):
return sel... | Save a "global".
The name of this method is somewhat misleading: all types get
dispatched here. |
368,302 | def Polygon(pos=(0, 0, 0), normal=(0, 0, 1), nsides=6, r=1, c="coral",
bc="darkgreen", lw=1, alpha=1, followcam=False):
ps = vtk.vtkRegularPolygonSource()
ps.SetNumberOfSides(nsides)
ps.SetRadius(r)
ps.SetNormal(-np.array(normal))
ps.Update()
tf = vtk.vtkTriangleFilter()
tf... | Build a 2D polygon of `nsides` of radius `r` oriented as `normal`.
:param followcam: if `True` the text will auto-orient itself to the active camera.
A ``vtkCamera`` object can also be passed.
:type followcam: bool, vtkCamera
|Polygon| |
368,303 | def _extended_lookup(
datastore_api,
project,
key_pbs,
missing=None,
deferred=None,
eventual=False,
transaction_id=None,
):
if missing is not None and missing != []:
raise ValueError("missing must be None or an empty list")
if deferred is not None and deferred != []:
... | Repeat lookup until all keys found (unless stop requested).
Helper function for :meth:`Client.get_multi`.
:type datastore_api:
:class:`google.cloud.datastore._http.HTTPDatastoreAPI`
or :class:`google.cloud.datastore_v1.gapic.DatastoreClient`
:param datastore_api: The datastore API object u... |
368,304 | def _parse_volumes(volume_values: dict) -> str:
for v_values in volume_values:
for v_key, v_value in v_values.items():
if v_key == :
if v_value == :
source = os.path.dirname(
os.path.abspath(__file__))
... | Parse volumes key.
Args:
volume_values (dict): volume configuration values
Returns:
string, volume specification with mount source and container path |
368,305 | def libvlc_media_get_user_data(p_md):
s user_data. user_data is specialized data
accessed by the host application, VLC.framework uses it as a pointer to
an native object that references a L{Media} pointer.
@param p_md: media descriptor object.
libvlc_media_get_user_datalibvlc_media_get_user_data', (... | Get media descriptor's user_data. user_data is specialized data
accessed by the host application, VLC.framework uses it as a pointer to
an native object that references a L{Media} pointer.
@param p_md: media descriptor object. |
368,306 | def _get_current_names(current, dsn, pc):
_table_name = ""
_variable_name = ""
try:
_table_name = current[.format(pc)]
_variable_name = current[.format(pc)]
except Exception as e:
print("Error: Unable to collapse time series: {}, {}".format(dsn, e))
logger_ts.er... | Get the table name and variable name from the given time series entry
:param dict current: Time series entry
:param str pc: paleoData or chronData
:return str _table_name:
:return str _variable_name: |
368,307 | def remove_content(self, *keys):
LOGGER.debug("> Removing content from the cache.".format(self.__class__.__name__, keys))
for key in keys:
if not key in self:
raise KeyError("{0} | key doesn't exists in cache content!".format(self.__class__.__name__, key))
... | Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
{}
:param \*keys: Content to remove.
... |
368,308 | def cg(output,
show,
verbose,
classname,
methodname,
descriptor,
accessflag,
no_isolated,
apk):
androcg_main(verbose=verbose,
APK=apk,
classname=classname,
methodname=methodname,
descript... | Create a call graph and export it into a graph format.
classnames are found in the type "Lfoo/bar/bla;".
Example:
\b
$ androguard cg APK |
368,309 | def delete_topic(self, project, topic, fail_if_not_exists=False):
service = self.get_conn()
full_topic = _format_topic(project, topic)
try:
service.projects().topics().delete(topic=full_topic).execute(num_retries=self.num_retries)
except HttpError as e:
... | Deletes a Pub/Sub topic if it exists.
:param project: the GCP project ID in which to delete the topic
:type project: str
:param topic: the Pub/Sub topic name to delete; do not
include the ``projects/{project}/topics/`` prefix.
:type topic: str
:param fail_if_not_exis... |
368,310 | def astra_cuda_bp_scaling_factor(proj_space, reco_space, geometry):
angle_extent = geometry.motion_partition.extent
num_angles = geometry.motion_partition.shape
scaling_factor = (angle_extent / num_angles).prod()
proj_extent = float(proj_space.partition.extent.prod())
... | Volume scaling accounting for differing adjoint definitions.
ASTRA defines the adjoint operator in terms of a fully discrete
setting (transposed "projection matrix") without any relation to
physical dimensions, which makes a re-scaling necessary to
translate it to spaces with physical dimensions.
... |
368,311 | def device_action(device_id, action_id):
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
if callable(input_cmd):
input_cmd()
success = True
return jsonify(success=success) | Initiate device action via HTTP GET. |
368,312 | def close(self, response):
LOGGER.info(, os.getpid())
if not self.database.is_closed():
self.database.close()
return response | Close connection to database. |
368,313 | def non_transactional(func, args, kwds, allow_existing=True):
from . import tasklets
ctx = tasklets.get_context()
if not ctx.in_transaction():
return func(*args, **kwds)
if not allow_existing:
raise datastore_errors.BadRequestError(
% func.__name__)
save_ctx = ctx
while ctx.in_transactio... | A decorator that ensures a function is run outside a transaction.
If there is an existing transaction (and allow_existing=True), the
existing transaction is paused while the function is executed.
Args:
allow_existing: If false, throw an exception if called from within
a transaction. If true, temporar... |
368,314 | def set_interval(self, interval):
self._interval = interval
if self.timer is not None:
self.timer.setInterval(interval) | Set timer interval (ms). |
368,315 | def cmd_status(self, run, finished=False):
if finished:
return [, , , , str(run.job_id)]
else:
return [, , , , , str(run.job_id)] | Given a :class:`~clusterjob.AsyncResult` instance, return a command
that queries the scheduler for the job status, as a list of command
arguments. If ``finished=True``, the scheduler is queried via
``sacct``. Otherwise, ``squeue`` is used. |
368,316 | def get_help(func):
help_text = ""
if isinstance(func, dict):
name = context_name(func)
help_text = "\n" + name + "\n\n"
doc = inspect.getdoc(func)
if doc is not None:
doc = inspect.cleandoc(doc)
help_text += doc +
return help_text
si... | Return usage information about a context or function.
For contexts, just return the context name and its docstring
For functions, return the function signature as well as its
argument types.
Args:
func (callable): An annotated callable function
Returns:
str: The formatted help tex... |
368,317 | def alter_partitions_with_environment_context(self, db_name, tbl_name, new_parts, environment_context):
self.send_alter_partitions_with_environment_context(db_name, tbl_name, new_parts, environment_context)
self.recv_alter_partitions_with_environment_context() | Parameters:
- db_name
- tbl_name
- new_parts
- environment_context |
368,318 | def files(self):
res = None
if not res:
res = glob.glob(self.path)
if not res and self.is_glob:
res = glob.glob(self.magic_path)
if not res:
res = glob.glob(self.alias)
if not res:
raise ValueError( % self)
return r... | Returns a list of all the files that match the given
input token. |
368,319 | def get_cluster_custom_object(self, group, version, plural, name, **kwargs):
kwargs[] = True
if kwargs.get():
return self.get_cluster_custom_object_with_http_info(group, version, plural, name, **kwargs)
else:
(data) = self.get_cluster_custom_object_with_http_... | get_cluster_custom_object # noqa: E501
Returns a cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_cluster_custom_object(group, version, plural, name,... |
368,320 | def generate_keywords(additional_keywords=None):
keywords = dict(BABEL_KEYWORDS)
keywords.update({
: None,
: None,
: None,
: None,
: None,
: (1, 2),
: (1, 2),
: ((1, ), 2, 3),
: ((1, ), 2),
: ((1, ), 2, 3),
})
... | Generates gettext keywords list
:arg additional_keywords: dict of keyword -> value
:returns: dict of keyword -> values for Babel extraction
Here's what Babel has for DEFAULT_KEYWORDS::
DEFAULT_KEYWORDS = {
'_': None,
'gettext': None,
'ngettext': (1, 2),
... |
368,321 | def engine(self):
if not self._engine:
if in self.driver:
if not in self.engine_kwargs:
self.engine_kwargs[] = {
: .format(self._application_prefix, os.getpid())
}
... | return the SqlAlchemy engine for this database. |
368,322 | def _do_delete(self):
return requests.delete(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token)) | HTTP Delete Request |
368,323 | def add_rules(self, rules: _RuleList) -> None:
for rule in rules:
if isinstance(rule, (tuple, list)):
assert len(rule) in (2, 3, 4)
if isinstance(rule[0], basestring_type):
rule = Rule(PathMatches(rule[0]), *rule[1:])
else:... | Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor). |
368,324 | def get_single_node(self) -> yaml.Node:
node = super().get_single_node()
if node is not None:
node = self.__process_node(node, type(self).document_type)
return node | Hook used when loading a single document.
This is the hook we use to hook yatiml into ruamel.yaml. It is \
called by the yaml libray when the user uses load() to load a \
YAML document.
Returns:
A processed node representing the document. |
368,325 | def hmset(self, name, mapping):
with self.pipe as pipe:
m_encode = self.memberparse.encode
mapping = {m_encode(k): self._value_encode(k, v)
for k, v in mapping.items()}
return pipe.hmset(self.redis_key(name), mapping) | Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future() |
368,326 | def service_command(name, command):
service_command_template = getattr(env, ,
u)
sudo(service_command_template % {: name,
: command}, pty=False) | Run an init.d/upstart command. |
368,327 | def freader(filename, gz=False, bz=False):
filecheck(filename)
if filename.endswith():
gz = True
elif filename.endswith():
bz = True
if gz:
return gzip.open(filename, )
elif bz:
return bz2.BZ2File(filename, )
else:
return io.open(filename, ) | Returns a filereader object that can handle gzipped input |
368,328 | def WriteTo(self, values):
try:
return self._struct.pack(*values)
except (TypeError, struct.error) as exception:
raise IOError(.format(
exception)) | Writes values to a byte stream.
Args:
values (tuple[object, ...]): values to copy to the byte stream.
Returns:
bytes: byte stream.
Raises:
IOError: if byte stream cannot be written.
OSError: if byte stream cannot be read. |
368,329 | def exit_with_error(message):
click.secho(message, err=True, bg=, fg=)
sys.exit(0) | Display formatted error message and exit call |
368,330 | def is_attr_private(attrname: str) -> Optional[Match[str]]:
regex = re.compile("^_{2,}.*[^_]+_?$")
return regex.match(attrname) | Check that attribute name is private (at least two leading underscores,
at most one trailing underscore) |
368,331 | def extract_tmaster(self, topology):
tmasterLocation = {
"name": None,
"id": None,
"host": None,
"controller_port": None,
"master_port": None,
"stats_port": None,
}
if topology.tmaster:
tmasterLocation["name"] = topology.tmaster.topology_name
... | Returns the representation of tmaster that will
be returned from Tracker. |
368,332 | def img(self, **kwargs):
safe = % self.url.replace(,).replace(, )\
.replace(, ).replace(, ).replace( "& | Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML |
368,333 | def _read_channel(self):
if self.protocol == "ssh":
output = ""
while True:
if self.remote_conn.recv_ready():
outbuf = self.remote_conn.recv(MAX_BUFFER)
if len(outbuf) == 0:
raise EOFError("Channel s... | Generic handler that will read all the data from an SSH or telnet channel. |
368,334 | def write_np_dat(self, store_format=, delimiter=, fmt=):
ret = False
system = self.system
if not system.Recorder.n:
n_vars = system.dae.m + system.dae.n
if system.tds.config.compute_flows:
n_vars +=... | Write TDS data stored in `self.np_vars` to the output file
Parameters
----------
store_format : str
dump format in ('csv', 'txt', 'hdf5')
delimiter : str
delimiter for the `csv` and `txt` format
fmt : str
output formatting template
... |
368,335 | def binary_to_float(binary_list, lower_bound, upper_bound):
if binary_list == []:
return lower_bound
return ((
float(upper_bound - lower_bound)
/ (2**len(binary_list) - 1)
* binary_to_int(binar... | Return a floating point number between lower and upper bounds, from binary.
Args:
binary_list: list<int>; List of 0s and 1s.
The number of bits in this list determine the number of possible
values between lower and upper bound.
Increase the size of binary_list for more p... |
368,336 | def value_at_coord(dset,coords):
return nl.numberize(nl.run([,,] + list(coords) + [dset],stderr=None).output) | returns value at specified coordinate in ``dset`` |
368,337 | def get_power_all(self):
power_dict = {}
for device in self.get_device_names().keys():
power_dict[device] = self.get_power_single(device)
return power_dict | Returns the power in mW for all devices |
368,338 | def axes(self, axes):
s degrees of freedom.
Parameters
----------
axes : list of axes specifications
A list of axis values to set. This list must have the same number of
elements as the degrees of freedom of the underlying ODE object.
Each element can... | Set the axes for this object's degrees of freedom.
Parameters
----------
axes : list of axes specifications
A list of axis values to set. This list must have the same number of
elements as the degrees of freedom of the underlying ODE object.
Each element can ... |
368,339 | def _slugify_foreign_key(schema):
for foreign_key in schema.get(, []):
foreign_key[][] = _slugify_resource_name(
foreign_key[].get(, ))
return schema | Slugify foreign key |
368,340 | def remove(self, id):
p = Pool.get(int(id))
p.remove()
redirect(url(controller = , action = )) | Remove pool. |
368,341 | def page(self, from_=values.unset, to=values.unset,
date_created_on_or_before=values.unset,
date_created_after=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
params = values.of({
: from_,
: to,
... | Retrieve a single page of FaxInstance records from the API.
Request is executed immediately
:param unicode from_: Retrieve only those faxes sent from this phone number
:param unicode to: Retrieve only those faxes sent to this phone number
:param datetime date_created_on_or_before: Retri... |
368,342 | def create_dataset(self,
name,
x_img_size,
y_img_size,
z_img_size,
x_vox_res,
y_vox_res,
z_vox_res,
x_offset=0,
y... | Creates a dataset.
Arguments:
name (str): Name of dataset
x_img_size (int): max x coordinate of image size
y_img_size (int): max y coordinate of image size
z_img_size (int): max z coordinate of image size
x_vox_res (float): x voxel resolution
... |
368,343 | def applet_validate_batch(object_id, input_params={}, always_retry=True, **kwargs):
return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs) | Invokes the /applet-xxxx/validateBatch API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2FvalidateBatch |
368,344 | def close_shell(self, shell_id):
message_id = uuid.uuid4()
req = {: self._get_soap_header(
resource_uri=,
action=,
shell_id=shell_id,
message_id=message_id)}
req[].setdefault(, {})
res = self.send_message(xmltodict.unp... | Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool |
368,345 | def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
allow_redirects=False):
kwargs = {
: method.upper(),
: url,
: params,
: data,
: headers,
: auth,
: self.requ... | Make an HTTP Request with parameters provided.
:param str method: The HTTP method to use
:param str url: The URL to request
:param dict params: Query parameters to append to the URL
:param dict data: Parameters to go in the body of the HTTP request
:param dict headers: HTTP Head... |
368,346 | def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys):
workbook = create_excel_workbook(data, result_info_key, identifier_keys)
workbook.save(output_file_name)
print(.format(output_file_name)) | Creates an Excel file containing data returned by the Analytics API
Args:
data: Analytics API data as a list of dicts
output_file_name: File name for output Excel file (use .xlsx extension). |
368,347 | def get_bandstructure_by_material_id(self, material_id, line_mode=True):
prop = "bandstructure" if line_mode else "bandstructure_uniform"
data = self.get_data(material_id, prop=prop)
return data[0][prop] | Get a BandStructure corresponding to a material_id.
REST Endpoint: https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure or
https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure_uniform
Args:
material_id (str): Materials Project mater... |
368,348 | async def message(self, recipient: str, text: str, notice: bool=False) -> None:
await self._send(cc.PRIVMSG if not notice else cc.NOTICE, recipient, rest=text) | Lower level messaging function used by User and Channel |
368,349 | def eps(self):
import tkFileDialog,tkMessageBox
filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=[,])
if filename is None:
return
self.postscript(file=filename) | Print the canvas to a postscript file |
368,350 | def from_fill_parent(cls, eg_fillProperties_parent):
fill_elm = eg_fillProperties_parent.eg_fillProperties
fill = _Fill(fill_elm)
fill_format = cls(eg_fillProperties_parent, fill)
return fill_format | Return a |FillFormat| instance initialized to the settings contained
in *eg_fillProperties_parent*, which must be an element having
EG_FillProperties in its child element sequence in the XML schema. |
368,351 | def _do_classifyplot(df, out_file, title=None, size=None, samples=None, callers=None):
metric_labels = {"fdr": "False discovery rate",
"fnr": "False negative rate"}
metrics = [("fnr", "tpr"), ("fdr", "spc")]
is_mpl2 = LooseVersion(mpl.__version__) >= LooseVersion()
colors = ["l... | Plot using classification-based plot using seaborn. |
368,352 | def _release_command_buffer(self, command_buffer):
if command_buffer.closed:
return
self._cb_poll.unregister(command_buffer.host_id)
self.connection_pool.release(command_buffer.connection)
command_buffer.connection = None | This is called by the command buffer when it closes. |
368,353 | def target_power(self):
ret = api.py_aa_target_power(self.handle, TARGET_POWER_QUERY)
_raise_error_if_negative(ret)
return ret | Setting this to `True` will activate the power pins (4 and 6). If
set to `False` the power will be deactivated.
Raises an :exc:`IOError` if the hardware adapter does not support
the switchable power pins. |
368,354 | def execute_code_block(compiler, block, example_globals,
script_vars, gallery_conf):
blabel, bcontent, lineno = block
if not script_vars[] or blabel == :
script_vars[].append(0)
return
cwd = os.getcwd()
orig_stdout = sys.stdout
src_file = scrip... | Executes the code block of the example file |
368,355 | def save_blocks(self, id_env, blocks):
url =
map_dict = dict()
map_dict[] = id_env
map_dict[] = blocks
code, xml = self.submit({: map_dict}, , url)
return self.response(code, xml) | Save blocks from environment
:param id_env: Environment id
:param blocks: Lists of blocks in order. Ex: ['content one', 'content two', ...]
:return: None
:raise AmbienteNaoExisteError: Ambiente não cadastrado.
:raise InvalidValueError: Invalid parameter.
:raise UserNot... |
368,356 | def _work_chain_mod_time(self, worker_name):
if worker_name== or worker_name== or worker_name==:
return datetime.datetime(1970, 1, 1)
my_mod_time = self._get_work_results(, worker_name)[][]
dependencies = self.plugin_meta[worker_name][]
if not dependencies... | Internal: We compute a modification time of a work chain.
Returns:
The newest modification time of any worker in the work chain. |
368,357 | def qteBindKeyGlobal(self, keysequence, macroName: str):
keysequence = QtmacsKeysequence(keysequence)
if not self.qteIsMacroRegistered(macroName):
msg =
msg = msg.format(macroName)
self.qteLogger.error(msg, stack_info=Tru... | Associate ``macroName`` with ``keysequence`` in all current
applets.
This method will bind ``macroName`` to ``keysequence`` in the
global key map and **all** local key maps. This also applies
for all applets (and their constituent widgets) yet to be
instantiated because they wil... |
368,358 | def DbAddDevice(self, argin):
self._log.debug("In DbAddDevice()")
if len(argin) < 3:
self.warn_stream("DataBase::AddDevice(): incorrect number of input arguments ")
th_exc(DB_IncorrectArguments,
"incorrect no. of input arguments, needs at least 3 (ser... | Add a Tango class device to a specific device server
:param argin: Str[0] = Full device server process name
Str[1] = Device name
Str[2] = Tango class name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid |
368,359 | def ce(actual, predicted):
return (sum([1.0 for x,y in zip(actual,predicted) if x != y]) /
len(actual)) | Computes the classification error.
This function computes the classification error between two lists
Parameters
----------
actual : list
A list of the true classes
predicted : list
A list of the predicted classes
Returns
-------
score : double
... |
368,360 | def _set_matplotlib_default_backend():
if _matplotlib_installed():
import matplotlib
matplotlib.use(, force=True)
config = matplotlib.matplotlib_fname()
if os.access(config, os.W_OK):
with file_transaction(config) as tx_out_file:
with open(config) as ... | matplotlib will try to print to a display if it is available, but don't want
to run it in interactive mode. we tried setting the backend to 'Agg'' before
importing, but it was still resulting in issues. we replace the existing
backend with 'agg' in the default matplotlibrc. This is a hack until we can
f... |
368,361 | def normalize_bbox(coords, ymax, scaler=2):
return [
coords[0] * scaler,
ymax - (coords[3] * scaler),
coords[2] * scaler,
ymax - (coords[1] * scaler),
] | scales all coordinates and flip y axis due to different
origin coordinates (top left vs. bottom left) |
368,362 | def __parse_enrollments(self, user):
enrollments = []
for company in user[]:
name = company[]
org = self._organizations.get(name, None)
if not org:
org = Organization(name=name)
self._organizations[name] = org
... | Parse user enrollments |
368,363 | def read(self):
if self._process and self._process.poll() is not None:
ip = get_ipython()
err = ip.user_ns[].read().decode()
out = ip.user_ns[].read().decode()
else:
out =
err =
return out, err | Read stdout and stdout pipes if process is no longer running. |
368,364 | def unwrap(lines, max_wrap_lines, min_header_lines, min_quoted_lines):
headers = {}
start, end, typ = find_unwrap_start(lines, max_wrap_lines, min_header_lines, min_quoted_lines)
return main_type, (0, start), headers, (start+(start2 or 0)+1, None), None, False
... | Returns a tuple of:
- Type ('forward', 'reply', 'headers', 'quoted')
- Range of the text at the top of the wrapped message (or None)
- Headers dict (or None)
- Range of the text of the wrapped message (or None)
- Range of the text below the wrapped message (or None)
- Whether the wrapped text ne... |
368,365 | def ensemble_simulations(
t, y0=None, volume=1.0, model=None, solver=,
is_netfree=False, species_list=None, without_reset=False,
return_type=, opt_args=(), opt_kwargs=None,
structures=None, rndseed=None,
n=1, nproc=None, method=None, errorbar=True,
**kwargs):
y0 = y0 or {}
opt_kwarg... | Run simulations multiple times and return its ensemble.
Arguments are almost same with ``ecell4.util.simulation.run_simulation``.
`observers` and `progressbar` is not available here.
Parameters
----------
n : int, optional
A number of runs. Default is 1.
nproc : int, optional
A ... |
368,366 | def wait(self, pattern, seconds=None):
if isinstance(pattern, (int, float)):
if pattern == FOREVER:
while True:
time.sleep(1)
time.sleep(pattern)
return None
if seconds is None:
seconds = self.autoWaitTimeout
... | Searches for an image pattern in the given region, given a specified timeout period
Functionally identical to find(). If a number is passed instead of a pattern,
just waits the specified number of seconds.
Sikuli supports OCR search with a text parameter. This does not (yet). |
368,367 | def get_train_eval_files(input_dir):
data_dir = _get_latest_data_dir(input_dir)
train_pattern = os.path.join(data_dir, )
eval_pattern = os.path.join(data_dir, )
train_files = file_io.get_matching_files(train_pattern)
eval_files = file_io.get_matching_files(eval_pattern)
return train_files, eval_files | Get preprocessed training and eval files. |
368,368 | def try_instance_init(self, instance, late_start=False):
try:
instance.init_try += 1
if instance.last_init_try > time.time() - MODULE_INIT_PERIOD:
logger.info("Too early to retry initialization, retry period is %d seconds",
... | Try to "initialize" the given module instance.
:param instance: instance to init
:type instance: object
:param late_start: If late_start, don't look for last_init_try
:type late_start: bool
:return: True on successful init. False if instance init method raised any Exception.
... |
368,369 | def register_post_execute(self, func):
if not callable(func):
raise ValueError( % func)
self._post_execute[func] = True | Register a function for calling after code execution. |
368,370 | def score(self, context, models, revids):
if isinstance(revids, int):
rev_ids = [revids]
else:
rev_ids = [int(rid) for rid in revids]
return self._score(context, models, rev_ids) | Genetate scores for model applied to a sequence of revisions.
:Parameters:
context : str
The name of the context -- usually the database name of a wiki
models : `iterable`
The names of a models to apply
revids : `iterable`
A se... |
368,371 | def mysql(
self,
tableNamePrefix="TNS",
dirPath=None):
if dirPath:
p = self._file_prefix()
createStatement = % locals()
mysqlSources = self.sourceResults.mysql(
tableNamePrefix + "_sources", filepath=dirPath + "/... | *Render the results as MySQL Insert statements*
**Key Arguments:**
- ``tableNamePrefix`` -- the prefix for the database table names to assign the insert statements to. Default *TNS*.
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Re... |
368,372 | def _set_parameters(self, parameters):
nr_f = self.f.size
rho0, m, tau, c = self._sort_parameters(parameters)
newsize = (nr_f, len(m))
m_resized = np.resize(m, newsize)
tau_resized = np.resize(tau, newsize)
c_resized = np.resize(c, newsize)
... | Sort out the various possible parameter inputs and return a config
object (dict)
We have multiple input formats:
1) a list, tuple, or numpy.ndarray, containing the linear parameters
in the following order:
* for single term: rho0, m1, tau1, c1
* for multiple termss: rho... |
368,373 | def viewbox_key_event(self, event):
PerspectiveCamera.viewbox_key_event(self, event)
if event.handled or not self.interactive:
return
if not self._timer.running:
self._timer.start()
if event.key in self._keymap:
val_dims = self._ke... | ViewBox key event handler
Parameters
----------
event : instance of Event
The event. |
368,374 | def send_photo(self, *args, **kwargs):
return send_photo(*args, **self._merge_overrides(**kwargs)).run() | See :func:`send_photo` |
368,375 | def execute_update(args):
provider_class = getattr(dnsupdater,
dnsupdater.AVAILABLE_PLUGINS.get(args.provider))
updater_options = {}
process_message = None
auth = None
if args.store:
if provider_class.auth_type == :
user_arg = args.usertoken ... | Execute the update based on command line args and returns a dictionary
with 'execution result, ''response code', 'response info' and
'process friendly message'. |
368,376 | def to_sql(cls, qc, **kwargs):
empty_df = qc.head(1).to_pandas().head(0)
empty_df.to_sql(**kwargs)
kwargs["if_exists"] = "append"
columns = qc.columns
def func(df, **kwargs):
df.columns = columns
... | Write records stored in a DataFrame to a SQL database.
Args:
qc: the query compiler of the DF that we want to run to_sql on
kwargs: parameters for pandas.to_sql(**kwargs) |
368,377 | def summarise_file_as_html(fname):
txt = + fname +
num_lines = 0
print(, fname)
with open(ip_folder + os.sep + fname, ) as f:
txt +=
for line in f:
if line.strip() != :
num_lines += 1
if num_lines < 80:
txt += str(n... | takes a large data file and produces a HTML summary as html |
368,378 | def icasa(taskname, mult=None, clearstart=False, loadthese=[],**kw0):
td = tempfile.mkdtemp(dir=)
cdir = os.path.realpath()
_load = ""
if "os" not in loadthese or "import os" not in loadthese:
loadthese.append("os")
if loadthese:
exclude = filter(lambda line: l... | runs a CASA task given a list of options.
A given task can be run multiple times with a different options,
in this case the options must be parsed as a list/tuple of dictionaries via mult, e.g
icasa('exportfits',mult=[{'imagename':'img1.image','fitsimage':'image1.fits},{'imagename':'img2.image','fit... |
368,379 | def validate_one_format(jupytext_format):
if not isinstance(jupytext_format, dict):
raise JupytextFormatError()
for key in jupytext_format:
if key not in _VALID_FORMAT_INFO + _VALID_FORMAT_OPTIONS:
raise JupytextFormatError("Unknown format option - should be one of ".format(
... | Validate extension and options for the given format |
368,380 | def init(self, game_info, static_data):
self._game_info = game_info
self._static_data = static_data
if not game_info.HasField("start_raw"):
raise ValueError("Raw observations are required for the renderer.")
self._map_size = point.Point.build(game_info.start_raw.map_size)
if game_info.... | Take the game info and the static data needed to set up the game.
This must be called before render or get_actions for each game or restart.
Args:
game_info: A `sc_pb.ResponseGameInfo` object for this game.
static_data: A `StaticData` object for this game.
Raises:
ValueError: if there i... |
368,381 | def auto(cls, func):
@functools.wraps(func)
def auto_claim_handle(*args, **kwargs):
with cls():
return func(*args, **kwargs)
return auto_claim_handle | The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's advisable to use the `requires_refcount`... |
368,382 | def get_functions_writing_to_variable(self, variable):
return [f for f in self.functions if f.is_writing(variable)] | Return the functions writting the variable |
368,383 | def reload(self):
if self.config_filename != "":
try:
self.config_content = codecs.open(self.config_filename, "r", "utf8").read()
except Exception as e:
raise Exception(
"{}: json/yaml settings error reading: {}".format(self.config_filename, e))
self.is_json = False
self.is_yaml... | fonction de chargement automatique de la configuration
depuis le fichier extérieur |
368,384 | def _dumpArrayToFile(filelike, array):
bytedata = array.tobytes()
start = filelike.tell()
end = start + len(bytedata)
metadata = {: start, : end, : array.size,
: array.dtype.name
}
filelike.write(bytedata)
return metadata | Serializes a 1-dimensional ``numpy.array`` to bytes, writes the bytes to
the filelike object and returns a dictionary with metadata, necessary to
restore the ``numpy.array`` from the file.
:param filelike: can be a file or a file-like object that provides the
methods ``.write()`` and ``.tell()``.
... |
368,385 | def delete_record(self, domain, recordid, params=None):
params = update_params(params, {
: domain,
: recordid
})
return self.request(, params, ) | /v1/dns/delete_record
POST - account
Deletes an individual DNS record
Link: https://www.vultr.com/api/#dns_delete_record |
368,386 | def _format(self, object, stream, indent, allowance, context, level):
try:
PrettyPrinter._format(self, object, stream, indent, allowance, context, level)
except Exception as e:
stream.write(_format_exception(e)) | Recursive part of the formatting |
368,387 | def has(self):
self._done = os.path.exists(self._cache_file)
return self._done or self._out is not None | Whether the cache file exists in the file system. |
368,388 | def levenshtein_distance(word1, word2):
if len(word1) < len(word2):
return levenshtein_distance(word2, word1)
if len(word2) == 0:
return len(word1)
previous_row = list(range(len(word2) + 1))
for i, char1 in enumerate(word1):
current_row = [i + 1]
for j, char2 in ... | Computes the Levenshtein distance.
[Reference]: https://en.wikipedia.org/wiki/Levenshtein_distance
[Article]: Levenshtein, Vladimir I. (February 1966). "Binary codes capable of correcting deletions,
insertions,and reversals". Soviet Physics Doklady 10 (8): 707–710.
[Implementation]: https://en.wiki... |
368,389 | def inject2(module_name=None, module_prefix=None, DEBUG=False, module=None, N=1):
if module_prefix is None:
module_prefix = % (module_name,)
noinject(module_name, module_prefix, DEBUG, module, N=N)
module = _get_module(module_name, module)
rrr = make_module_reload_func(None, module_pr... | wrapper that depricates print_ and printDBG |
368,390 | def to_dict(self):
schema = super(Schema, self).to_dict()
schema[] = "http://json-schema.org/draft-04/schema
if self._id:
schema[] = self._id
if self._desc:
schema[] = self._desc
return schema | Return the schema as a dict ready to be serialized. |
368,391 | def downside_risk(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None):
allocated_output = out is None
if allocated_output:
out = np.empty(returns.shape[1:])
returns_1d = returns.ndim == 1
if len(re... | Determines the downside deviation below a threshold
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum accep... |
368,392 | def add_at(self, moment: float, fn_process: Callable, *args: Any, **kwargs: Any) -> :
delay = moment - self.now()
if delay < 0.0:
raise ValueError(
f"The given moment to start the process ({moment:f}) is in the past (now is {self.now():f})."
)
ret... | Adds a process to the simulation, which is made to start at the given exact time on the simulated clock. Note
that times in the past when compared to the current moment on the simulated clock are forbidden.
See method add() for more details. |
368,393 | def get(self, key):
if not key in self._actions:
return None
if not key in self._cache:
self._cache[key] = self._actions[key]()
return self._cache[key] | Executes the callable registered at the specified key and returns
its value. Subsequent queries are cached internally.
`key`
String key for a previously stored callable. |
368,394 | def __set_date(self, value):
value = date_to_datetime(value)
if value > datetime.now() + timedelta(hours=14, minutes=1):
raise ValueError("Date cannot be in the future.")
if self.__due_date and value.date() > self.__due_date:
raise ValueError("Date cannot be po... | Sets the invoice date.
@param value:datetime |
368,395 | def unique_list(input_, key=lambda x:x):
seen = set()
output = []
for x in input_:
keyx = key(x)
if keyx not in seen:
seen.add(keyx)
output.append(x)
return output | Return the unique elements from the input, in order. |
368,396 | def create_single_button_clone(self, submit_text=, submit_css_class=,
read_form_data=True, form_type=None):
from .basicfields import BooleanCheckbox, HiddenField, SubmitButton
fields = []
for field in self.all_fields:
if field... | This will create a copy of this form, with all of inputs replaced with hidden inputs,
and with a single submit button. This allows you to easily create a "button" that
will submit a post request which is identical to the current state of the form.
You could then, if required, change some of the... |
368,397 | def polygon(self, points, stroke=None, fill=None, stroke_width=1, disable_anti_aliasing=False):
self.put()
self.put(.join([ % p for p in points]))
self.put()
self.put(str(stroke_width))
self.put()
if fill:
self.put()
self.put(fill)
... | :param points: List of points |
368,398 | def quote(code):
try:
code = code.rstrip()
except AttributeError:
return code
if code and code[0] + code[-1] not in (, "", "u""u""'
else:
return code | Returns quoted code if not already quoted and if possible
Parameters
----------
code: String
\tCode thta is quoted |
368,399 | def _extract_game_info(self, games):
all_boxscores = []
for game in games:
details = self._get_team_details(game)
away_name, away_abbr, away_score, home_name, home_abbr, \
home_score = details
boxscore_url = game()
boxscore_uri = ... | Parse game information from all boxscores.
Find the major game information for all boxscores listed on a
particular boxscores webpage and return the results in a list.
Parameters
----------
games : generator
A generator where each element points to a boxscore on the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.