code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def unicode_to_string(self):
"""Convert unicode in string
"""
for tag in self.tags:
self.ununicode.append(str(tag)) | Convert unicode in string |
def syscall_direct(*events):
'''
Directly process these events. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in events:
processor(e)
return _syscall | Directly process these events. This should never be used for normal events. |
def schedule_downtime(scope,
api_key=None,
app_key=None,
monitor_id=None,
start=None,
end=None,
message=None,
recurrence=None,
timezone=None,
... | Schedule downtime for a scope of monitors.
CLI Example:
.. code-block:: bash
salt-call datadog.schedule_downtime 'host:app2' \\
stop=$(date --date='30 minutes' +%s) \\
app_key='0123456789' \\
... |
def is_complete(self):
"""Returns True if this is a complete solution, i.e, all nodes are allocated
Returns
-------
bool
True if all nodes are llocated.
"""
return all(
[node.route_allocation() is not None for node in list(self._nodes.valu... | Returns True if this is a complete solution, i.e, all nodes are allocated
Returns
-------
bool
True if all nodes are llocated. |
def getVisibility(self):
'''
Gets the View visibility
'''
try:
if self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':
return VISIBLE
elif self.map[GET_VISIBILITY_PROPERTY] == 'INVISIBLE':
return INVISIBLE
elif self.map[GET_... | Gets the View visibility |
def download(self,
url,
dest_path=None):
"""
:param url:
:type url: str
:param dest_path:
:type dest_path: str
"""
if os.path.exists(dest_path):
os.remove(dest_path)
resp = get(url, stream=True)
size =... | :param url:
:type url: str
:param dest_path:
:type dest_path: str |
def pow2_quantized_affine(inp, n_outmaps,
base_axis=1,
w_init=None, b_init=None,
fix_parameters=False, rng=None, with_bias=True,
quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True,... | Pow2 Quantized Affine.
Pow2 Quantized Affine is the affine function,
except the definition of the inner product is modified.
The input-output relation of this function is as follows:
.. math::
y_j = \sum_{i} Q(w_{ji}) x_i,
where :math:`Q(w_{ji})` is the power-of-2 quantization function.
... |
def stage(self):
"""Stage python packages for release, verifying everything we can about them."""
if 'PYPI_USER' not in os.environ or 'PYPI_PASS' not in os.environ:
raise BuildError("You must set the PYPI_USER and PYPI_PASS environment variables")
try:
import twine
... | Stage python packages for release, verifying everything we can about them. |
def get_build_configuration(id=None, name=None):
"""
Retrieve a specific BuildConfiguration
"""
data = get_build_configuration_raw(id, name)
if data:
return utils.format_json(data) | Retrieve a specific BuildConfiguration |
def _set_serial_console(self):
"""
Configures the first serial port to allow a serial console connection.
"""
# activate the first serial port
yield from self._modify_vm("--uart1 0x3F8 4")
# set server mode with a pipe on the first serial port
pipe_name = self._... | Configures the first serial port to allow a serial console connection. |
def process_file(source_file):
"""
Extract text from a file (pdf, txt, eml, csv, json)
:param source_file path to file to read
:return text from file
"""
if source_file.endswith(('.pdf', '.PDF')):
txt = extract_pdf(source_file)
elif source_file.endswith(('.txt', '.eml', '.csv', '.jso... | Extract text from a file (pdf, txt, eml, csv, json)
:param source_file path to file to read
:return text from file |
def rollsd(self, scale=1, **kwargs):
'''A :ref:`rolling function <rolling-function>` for
stadard-deviation values:
Same as::
self.rollapply('sd', **kwargs)
'''
ts = self.rollapply('sd', **kwargs)
if scale != 1:
ts *= scale
return... | A :ref:`rolling function <rolling-function>` for
stadard-deviation values:
Same as::
self.rollapply('sd', **kwargs) |
def _fix_lsm_bitspersample(self, parent):
"""Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag.
"""
if self.code != 258 or self.count != 2:
return
# TODO: t... | Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag. |
def run( self, for_time=None ):
"""
Run the simulation.
Args:
for_time (:obj:Float, optional): If `for_time` is set, then run the simulation until a set amount of time has passed. Otherwise, run the simulation for a set number of jumps. Defaults to None.
Returns:
... | Run the simulation.
Args:
for_time (:obj:Float, optional): If `for_time` is set, then run the simulation until a set amount of time has passed. Otherwise, run the simulation for a set number of jumps. Defaults to None.
Returns:
None |
def filter(self, dict_name, priority_min='-inf', priority_max='+inf',
start=0, limit=None):
'''Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it s... | Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it skips the first `start` ones, and then returns
at most `limit` keys.
With default parameters, this ret... |
def denoise_grid(self, val, expand=1):
"""
for every cell in the grid of 'val' fill all cells
around it to de noise the grid
"""
updated_grid = [[self.grd.get_tile(y,x) \
for x in range(self.grd.grid_width)] \
for y in rang... | for every cell in the grid of 'val' fill all cells
around it to de noise the grid |
def _make_shred(self, c, name, feature_extractors, sheet_name):
"""Creates a Shred instances from a given contour.
Args:
c: cv2 contour object.
name: string shred name within a sheet.
feature_extractors: iterable of AbstractShredFeature instances.
Returns:
... | Creates a Shred instances from a given contour.
Args:
c: cv2 contour object.
name: string shred name within a sheet.
feature_extractors: iterable of AbstractShredFeature instances.
Returns:
A new Shred instance or None on failure. |
def not_has_branch(branch):
"""Raises `ExistingBranchError` if the specified branch exists."""
if _has_branch(branch):
msg = 'Cannot proceed while {} branch exists; remove and try again.'.format(branch)
raise temple.exceptions.ExistingBranchError(msg) | Raises `ExistingBranchError` if the specified branch exists. |
def before_app_websocket(self, func: Callable) -> Callable:
"""Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered o... | Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
bluep... |
def channels_open(self, room_id, **kwargs):
"""Adds the channel back to the user’s list of channels."""
return self.__call_api_post('channels.open', roomId=room_id, kwargs=kwargs) | Adds the channel back to the user’s list of channels. |
def run(self):
"""主函数"""
# try:
self.fenum.write('\n')
self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiDataType.h'), 'r')
for idx, line in enumerate(self.fcpp):
l = self.process_line(idx, line)
self.f_data_type.write(l)
... | 主函数 |
def init_model(engine, create=True, drop=False):
"""
Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module.
@param engine: The SQLAlchemy engine instance.
@type engine: C{sqlalchemy.Engine}
@param create: Whether to create the tables (if they do not exist).
@type creat... | Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module.
@param engine: The SQLAlchemy engine instance.
@type engine: C{sqlalchemy.Engine}
@param create: Whether to create the tables (if they do not exist).
@type create: C{bool}
@param drop: Whether to drop the tables (if t... |
def __event_exist(self, event_type):
"""Return the event position, if it exists.
An event exist if:
* end is < 0
* event_type is matching
Return -1 if the item is not found.
"""
for i in range(self.len()):
if self.events_list[i][1] < 0 and self.events... | Return the event position, if it exists.
An event exist if:
* end is < 0
* event_type is matching
Return -1 if the item is not found. |
def _maybe_throw(self):
"""
Throw any deferred exceptions set via :meth:`_add_err`
"""
if self._err:
ex_cls, ex_obj, ex_bt = self._err
self._err = None
PyCBC.raise_helper(ex_cls, ex_obj, ex_bt) | Throw any deferred exceptions set via :meth:`_add_err` |
def GET(self, func, data):
"""Send GET request to execute Ndrive API
:param func: The function name you want to execute in Ndrive API.
:param params: Parameter data for HTTP request.
:returns: metadata when success or False when failed
"""
if func not in ['getRegisterUs... | Send GET request to execute Ndrive API
:param func: The function name you want to execute in Ndrive API.
:param params: Parameter data for HTTP request.
:returns: metadata when success or False when failed |
def add_plot_parser(subparsers):
"""Add function 'plot' argument parsers."""
argparser_replot = subparsers.add_parser("replot", help="Reproduce GSEA desktop output figures.")
group_replot = argparser_replot.add_argument_group("Input arguments")
group_replot.add_argument("-i", "--indir", action="store... | Add function 'plot' argument parsers. |
def get_opcodes_from_bp_table(bp):
"""Given a 2d list structure, collect the opcodes from the best path."""
x = len(bp) - 1
y = len(bp[0]) - 1
opcodes = []
while x != 0 or y != 0:
this_bp = bp[x][y]
opcodes.append(this_bp)
if this_bp[0] == EQUAL or this_bp[0] == REPLACE:
... | Given a 2d list structure, collect the opcodes from the best path. |
def add_constraint(self, name, coefficients={}, ub=0):
"""
Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to
linear coefficients.
The constraint can only have an upper bound. To make a constraint with a lower bound, multiply
all coe... | Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to
linear coefficients.
The constraint can only have an upper bound. To make a constraint with a lower bound, multiply
all coefficients by -1. |
def register(self, config_file, contexts, config_template=None):
"""
Register a config file with a list of context generators to be called
during rendering.
config_template can be used to load a template from a string instead of
using template loaders and template files.
... | Register a config file with a list of context generators to be called
during rendering.
config_template can be used to load a template from a string instead of
using template loaders and template files.
:param config_file (str): a path where a config file will be rendered
:param ... |
def pmdec(self,*args,**kwargs):
"""
NAME:
pmdec
PURPOSE:
return proper motion in declination (in mas/yr)
INPUT:
t - (optional) time at which to get pmdec (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observe... | NAME:
pmdec
PURPOSE:
return proper motion in declination (in mas/yr)
INPUT:
t - (optional) time at which to get pmdec (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
in the Galactocentric fr... |
def register(self, name):
"""Decorator for registering a function with PyPhi.
Args:
name (string): The name of the function
"""
def register_func(func):
self.store[name] = func
return func
return register_func | Decorator for registering a function with PyPhi.
Args:
name (string): The name of the function |
def get_auth_basic(self):
"""return the username and password of a basic auth header if it exists"""
username = ''
password = ''
auth_header = self.get_header('authorization')
if auth_header:
m = re.search(r"^Basic\s+(\S+)$", auth_header, re.I)
if m:
... | return the username and password of a basic auth header if it exists |
def set(self, tclass, tnum, tlvt=0, tdata=b''):
"""set the values of the tag."""
if isinstance(tdata, bytearray):
tdata = bytes(tdata)
elif not isinstance(tdata, bytes):
raise TypeError("tag data must be bytes or bytearray")
self.tagClass = tclass
self.ta... | set the values of the tag. |
def show_linkinfo_output_show_link_info_linkinfo_domain_reachable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_linkinfo = ET.Element("show_linkinfo")
config = show_linkinfo
output = ET.SubElement(show_linkinfo, "output")
show_link... | Auto Generated Code |
def add_exit(self, guard, dst, jk, ip):
"""
Add an exit out of the middle of an IRSB.
(e.g., a conditional jump)
:param guard: An expression, the exit is taken if true
:param dst: the destination of the exit (a Const)
:param jk: the JumpKind of this exit (probably Ijk_Bor... | Add an exit out of the middle of an IRSB.
(e.g., a conditional jump)
:param guard: An expression, the exit is taken if true
:param dst: the destination of the exit (a Const)
:param jk: the JumpKind of this exit (probably Ijk_Boring)
:param ip: The address of this exit's source |
def delay(self, func, args=None, kwargs=None, queue=None,
hard_timeout=None, unique=None, lock=None, lock_key=None,
when=None, retry=None, retry_on=None, retry_method=None,
max_queue_size=None):
"""
Queues a task. See README.rst for an explanation of the options... | Queues a task. See README.rst for an explanation of the options. |
def has_code(state, text, pattern=True, not_typed_msg=None):
"""Test the student code.
Tests if the student typed a (pattern of) text. It is advised to use ``has_equal_ast()`` instead of ``has_code()``,
as it is more robust to small syntactical differences that don't change the code's behavior.
Args:
... | Test the student code.
Tests if the student typed a (pattern of) text. It is advised to use ``has_equal_ast()`` instead of ``has_code()``,
as it is more robust to small syntactical differences that don't change the code's behavior.
Args:
text (str): the text that is searched for
pattern (b... |
def __embed_frond(node_u, node_w, dfs_data, as_branch_marker=False):
"""Embeds a frond uw into either LF or RF. Returns whether the embedding was successful."""
d_u = D(node_u, dfs_data)
d_w = D(node_w, dfs_data)
comp_d_w = abs(d_w)
if as_branch_marker:
d_w *= -1
if dfs_data['last_i... | Embeds a frond uw into either LF or RF. Returns whether the embedding was successful. |
def _sparse_blockify(tuples, dtype=None):
""" return an array of blocks that potentially have different dtypes (and
are sparse)
"""
new_blocks = []
for i, names, array in tuples:
array = _maybe_to_sparse(array)
block = make_block(array, placement=[i])
new_blocks.append(block... | return an array of blocks that potentially have different dtypes (and
are sparse) |
def _leftMouseDragged(self, stopCoord, strCoord, speed):
"""Private method to handle generic mouse left button dragging and
dropping.
Parameters: stopCoord(x,y) drop point
Optional: strCoord (x, y) drag point, default (0,0) get current
mouse position
... | Private method to handle generic mouse left button dragging and
dropping.
Parameters: stopCoord(x,y) drop point
Optional: strCoord (x, y) drag point, default (0,0) get current
mouse position
speed (int) 1 to unlimit, simulate mouse moving
ac... |
def tagfunc(nargs=None, ndefs=None, nouts=None):
"""
decorate of tagged function
"""
def wrapper(f):
return wraps(f)(FunctionWithTag(f, nargs=nargs, nouts=nouts, ndefs=ndefs))
return wrapper | decorate of tagged function |
def _parser():
"""Parse command-line options."""
launcher = 'pip%s-utils' % sys.version_info.major
parser = argparse.ArgumentParser(
description='%s.' % __description__,
epilog='See `%s COMMAND --help` for help '
'on a specific subcommand.' % launcher,
prog=launcher)
... | Parse command-line options. |
def execute(self):
"""Generate local DB, pulling metadata and data from RWSConnection"""
logging.info('Requesting view metadata for project %s' % self.project_name)
project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))
# Process it into a set of... | Generate local DB, pulling metadata and data from RWSConnection |
def edit_account_info(self, short_name=None, author_name=None,
author_url=None):
""" Update information about a Telegraph account.
Pass only the parameters that you want to edit
:param short_name: Account name, helps users with several
ac... | Update information about a Telegraph account.
Pass only the parameters that you want to edit
:param short_name: Account name, helps users with several
accounts remember which they are currently using.
Displayed to the user above the "Edit/Publis... |
def fetch_mim_files(api_key, mim2genes=False, mimtitles=False, morbidmap=False, genemap2=False):
"""Fetch the necessary mim files using a api key
Args:
api_key(str): A api key necessary to fetch mim data
Returns:
mim_files(dict): A dictionary with the neccesary files
"""
L... | Fetch the necessary mim files using a api key
Args:
api_key(str): A api key necessary to fetch mim data
Returns:
mim_files(dict): A dictionary with the neccesary files |
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
key_spec=None, grant_tokens=None, region=None, key=None,
keyid=None, profile=None):
'''
Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias... | Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 |
def _get_axis_bounds(self, dim, bunch):
"""Return the min/max of an axis."""
if dim in self.attributes:
# Attribute: specified lim, or compute the min/max.
vmin, vmax = bunch['lim']
assert vmin is not None
assert vmax is not None
return vmin, v... | Return the min/max of an axis. |
def load_remote_db(self):
"""
Load remote S3 DB
"""
signature_version = self.settings_dict.get("SIGNATURE_VERSION", "s3v4")
s3 = boto3.resource(
's3',
config=botocore.client.Config(signature_version=signature_version),
)
if '/tmp/' not in... | Load remote S3 DB |
def _query_ned_and_add_results_to_database(
self,
batchCount):
""" query ned and add results to database
**Key Arguments:**
- ``batchCount`` - the index number of the batch sent to NED
.. todo ::
- update key arguments values and definitions wit... | query ned and add results to database
**Key Arguments:**
- ``batchCount`` - the index number of the batch sent to NED
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples a... |
def list_fonts():
"""List system fonts
Returns
-------
fonts : list of str
List of system fonts.
"""
vals = _list_fonts()
for font in _vispy_fonts:
vals += [font] if font not in vals else []
vals = sorted(vals, key=lambda s: s.lower())
return vals | List system fonts
Returns
-------
fonts : list of str
List of system fonts. |
def circ_corrcl(x, y, tail='two-sided'):
"""Correlation coefficient between one circular and one linear variable
random variables.
Parameters
----------
x : np.array
First circular variable (expressed in radians)
y : np.array
Second circular variable (linear)
tail : string
... | Correlation coefficient between one circular and one linear variable
random variables.
Parameters
----------
x : np.array
First circular variable (expressed in radians)
y : np.array
Second circular variable (linear)
tail : string
Specify whether to return 'one-sided' or ... |
def process(self):
"""Entry point of SelectableSelector"""
if WINDOWS:
select_inputs = []
for i in self.inputs:
if not isinstance(i, SelectableObject):
warning("Unknown ignored object type: %s", type(i))
elif i.__selectable_forc... | Entry point of SelectableSelector |
def create(cls, name, template=None):
"""Creates an LXC"""
command = ['lxc-create', '-n', name]
if template:
command.extend(['-t', template])
subwrap.run(command) | Creates an LXC |
def filter(self, scored_list):
'''
Filtering with top-n ranking.
Args:
scored_list: The list of scoring.
Retruns:
The list of filtered result.
'''
top_n_key = -1 * self.top_n
top_n_list = sorted(scored_list, key=lambda x: x[1])[top_n_... | Filtering with top-n ranking.
Args:
scored_list: The list of scoring.
Retruns:
The list of filtered result. |
def content(self, content):
"""
Sets the content of this SupportLevelPage.
:param content: The content of this SupportLevelPage.
:type: list[str]
"""
allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"]
if not set(content).issubs... | Sets the content of this SupportLevelPage.
:param content: The content of this SupportLevelPage.
:type: list[str] |
def get_tabs(self, request, **kwargs):
"""Returns the initialized tab group for this view."""
if self._tab_group is None:
self._tab_group = self.tab_group_class(request, **kwargs)
return self._tab_group | Returns the initialized tab group for this view. |
def remove_dashboard_tag(self, id, tag_value, **kwargs): # noqa: E501
"""Remove a tag from a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = ap... | Remove a tag from a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_dashboard_tag(id, tag_value, async_req=True)
>>> result = thread.... |
async def write(self, item):
"""
Write an item in the queue.
:param item: The item.
"""
await self._queue.put(item)
self._can_read.set()
if self._queue.full():
self._can_write.clear() | Write an item in the queue.
:param item: The item. |
def byname(nlist):
"""
**Deprecated:** Convert a list of named objects into an ordered dictionary
indexed by name.
This function is internal and has been deprecated in pywbem 0.12.
"""
warnings.warn("The internal byname() function has been deprecated, with "
"no replacement.",... | **Deprecated:** Convert a list of named objects into an ordered dictionary
indexed by name.
This function is internal and has been deprecated in pywbem 0.12. |
def iter_chunks_class(self):
"""
Yield each readable chunk present in the region.
Chunks that can not be read for whatever reason are silently skipped.
This function returns a :class:`nbt.chunk.Chunk` instance.
"""
for m in self.get_metadata():
try:
... | Yield each readable chunk present in the region.
Chunks that can not be read for whatever reason are silently skipped.
This function returns a :class:`nbt.chunk.Chunk` instance. |
def _win32_read_junction(path):
"""
Returns the location that the junction points, raises ValueError if path is
not a junction.
CommandLine:
python -m ubelt._win32_links _win32_read_junction
Example:
>>> # xdoc: +REQUIRES(WIN32)
>>> import ubelt as ub
>>> root = ub.... | Returns the location that the junction points, raises ValueError if path is
not a junction.
CommandLine:
python -m ubelt._win32_links _win32_read_junction
Example:
>>> # xdoc: +REQUIRES(WIN32)
>>> import ubelt as ub
>>> root = ub.ensure_app_cache_dir('ubelt', 'win32_junctio... |
def from_json_file(file: TextIO, check_version=True) -> BELGraph:
"""Build a graph from the Node-Link JSON contained in the given file."""
graph_json_dict = json.load(file)
return from_json(graph_json_dict, check_version=check_version) | Build a graph from the Node-Link JSON contained in the given file. |
def _generic_signal_handler(self, signal_type):
"""
Function for handling both SIGTERM and SIGINT
"""
print("</pre>")
message = "Got " + signal_type + ". Failing gracefully..."
self.timestamp(message)
self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_reco... | Function for handling both SIGTERM and SIGINT |
def stop_playback(self):
"""Stop playback from the audio sink."""
self._sink.flush()
self._sink.stop()
self._playing = False | Stop playback from the audio sink. |
def __setAsOrphaned(self):
"""
Sets the current model as orphaned. This is called when the scheduler is
about to kill the process to reallocate the worker to a different process.
"""
cmplReason = ClientJobsDAO.CMPL_REASON_ORPHAN
cmplMessage = "Killed by Scheduler"
self._jobsDAO.modelSetCompl... | Sets the current model as orphaned. This is called when the scheduler is
about to kill the process to reallocate the worker to a different process. |
def abort(self, jobs=None, targets=None, block=None):
"""Abort specific jobs from the execution queues of target(s).
This is a mechanism to prevent jobs that have already been submitted
from executing.
Parameters
----------
jobs : msg_id, list of msg_ids, or AsyncResul... | Abort specific jobs from the execution queues of target(s).
This is a mechanism to prevent jobs that have already been submitted
from executing.
Parameters
----------
jobs : msg_id, list of msg_ids, or AsyncResult
The jobs to be aborted
If ... |
def clean_egginfo(self):
"""Clean .egginfo directory"""
dir_name = os.path.join(self.root, self.get_egginfo_dir())
self._clean_directory(dir_name) | Clean .egginfo directory |
def Run(self):
"Execute the action"
inputs = self.GetInput()
return SendInput(
len(inputs),
ctypes.byref(inputs),
ctypes.sizeof(INPUT)) | Execute the action |
def FindEnumTypeByName(self, full_name):
"""Loads the named enum descriptor from the pool.
Args:
full_name: The full name of the enum descriptor to load.
Returns:
The enum descriptor for the named type.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in se... | Loads the named enum descriptor from the pool.
Args:
full_name: The full name of the enum descriptor to load.
Returns:
The enum descriptor for the named type. |
def _scipy_distribution_positional_args_from_dict(distribution, params):
"""Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see a... | Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see an example of scipy's positional arguments. This function returns the arguments s... |
def source_start(base='', book_id='book'):
"""
chooses a starting source file in the 'base' directory for id = book_id
"""
repo_htm_path = "{book_id}-h/{book_id}-h.htm".format(book_id=book_id)
possible_paths = ["book.asciidoc",
repo_htm_path,
"{}-0.tx... | chooses a starting source file in the 'base' directory for id = book_id |
def set_data(self, capacity, voltage=None,
capacity_label="q", voltage_label="v"
):
"""Set the data"""
logging.debug("setting data (capacity and voltage)")
if isinstance(capacity, pd.DataFrame):
logging.debug("recieved a pandas.DataFrame")
... | Set the data |
def filter_kwargs(_function, *args, **kwargs):
"""Given a function and args and keyword args to pass to it, call the function
but using only the keyword arguments which it accepts. This is equivalent
to redefining the function with an additional \*\*kwargs to accept slop
keyword args.
If the targe... | Given a function and args and keyword args to pass to it, call the function
but using only the keyword arguments which it accepts. This is equivalent
to redefining the function with an additional \*\*kwargs to accept slop
keyword args.
If the target function already accepts \*\*kwargs parameters, no f... |
def stoch(df, window=14, d=3, k=3, fast=False):
"""
compute the n period relative strength indicator
http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html
"""
my_df = pd.DataFrame(index=df.index)
my_df['rolling_max'] = df['high'].rolling(window).max()
my_df['rolling_mi... | compute the n period relative strength indicator
http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html |
def NetFxSDKIncludes(self):
"""
Microsoft .Net Framework SDK Includes
"""
if self.vc_ver < 14.0 or not self.si.NetFxSdkDir:
return []
return [os.path.join(self.si.NetFxSdkDir, r'include\um')] | Microsoft .Net Framework SDK Includes |
def parallel_part(data, parallel):
"""parallel_part(data, parallel) -> part
Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable.
**Parameters:**
``data`` : [object]
A list of data that should be split up into ``parallel``... | parallel_part(data, parallel) -> part
Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable.
**Parameters:**
``data`` : [object]
A list of data that should be split up into ``parallel`` parts
``parallel`` : int or ``None``... |
def hist(sample, options={}, **kwargs):
"""Draw a histogram in the current context figure.
Parameters
----------
sample: numpy.ndarray, 1d
The sample for which the histogram must be generated.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'coun... | Draw a histogram in the current context figure.
Parameters
----------
sample: numpy.ndarray, 1d
The sample for which the histogram must be generated.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'counts'
is required for that mark, options[... |
def has_started(self):
"""
Whether the handler has completed all start up processes such as
establishing the connection, session, link and authentication, and
is not ready to process messages.
**This function is now deprecated and will be removed in v2.0+.**
:rtype: bool... | Whether the handler has completed all start up processes such as
establishing the connection, session, link and authentication, and
is not ready to process messages.
**This function is now deprecated and will be removed in v2.0+.**
:rtype: bool |
def keyword(
name: str,
ns: Optional[str] = None,
kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN,
) -> Keyword:
"""Create a new keyword."""
h = hash((name, ns))
return kw_cache.swap(__get_or_create, h, name, ns)[h] | Create a new keyword. |
async def edit_2fa(
self, current_password=None, new_password=None,
*, hint='', email=None, email_code_callback=None):
"""
Changes the 2FA settings of the logged in user, according to the
passed parameters. Take note of the parameter explanations.
Note that this ... | Changes the 2FA settings of the logged in user, according to the
passed parameters. Take note of the parameter explanations.
Note that this method may be *incredibly* slow depending on the
prime numbers that must be used during the process to make sure
that everything is safe.
... |
def _init(self):
"""Initialize layer structure."""
group_stack = [self]
clip_stack = []
last_layer = None
for record, channels in self._record._iter_layers():
current_group = group_stack[-1]
blocks = record.tagged_blocks
end_of_group = False
... | Initialize layer structure. |
def run_one(self, set_title=False):
'''Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMI... | Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMINATE`.
:param set_title: if true, set ... |
def encode(self, word, max_length=-1, keep_vowels=False, vowel_char='*'):
r"""Return the Dolby Code of a name.
Parameters
----------
word : str
The word to transform
max_length : int
Maximum length of the returned Dolby code -- this also activates
... | r"""Return the Dolby Code of a name.
Parameters
----------
word : str
The word to transform
max_length : int
Maximum length of the returned Dolby code -- this also activates
the fixed-length code mode if it is greater than 0
keep_vowels : bool... |
def insert_before(self, value: Union[RawValue, Value],
raw: bool = False) -> "ArrayEntry":
"""Insert a new entry before the receiver.
Args:
value: The value of the new entry.
raw: Flag to be set if `value` is raw.
Returns:
An instance n... | Insert a new entry before the receiver.
Args:
value: The value of the new entry.
raw: Flag to be set if `value` is raw.
Returns:
An instance node of the new inserted entry. |
def fetch_credential(self, credential=None, profile=None):
"""Fetch credential from credentials file.
Args:
credential (str): Credential to fetch.
profile (str): Credentials profile. Defaults to ``'default'``.
Returns:
str, None: Fetched credential or ``None... | Fetch credential from credentials file.
Args:
credential (str): Credential to fetch.
profile (str): Credentials profile. Defaults to ``'default'``.
Returns:
str, None: Fetched credential or ``None``. |
def flow_ramp(self):
"""An equally spaced array representing flow at each row."""
return np.linspace(1 / self.n_rows, 1, self.n_rows)*self.q | An equally spaced array representing flow at each row. |
def read_certificate_signing_request(self, name, **kwargs): # noqa: E501
"""read_certificate_signing_request # noqa: E501
read the specified CertificateSigningRequest # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pa... | read_certificate_signing_request # noqa: E501
read the specified CertificateSigningRequest # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_certificate_signing_request(name, asy... |
def remove_entity(self, name):
"""Unload an entity"""
self.entities.remove(name)
self.padaos.remove_entity(name) | Unload an entity |
def serialzeValueToTCL(self, val, do_eval=False) -> Tuple[str, str, bool]:
"""
:see: doc of method on parent class
"""
if isinstance(val, int):
val = hInt(val)
if do_eval:
val = val.staticEval()
if isinstance(val, RtlSignalBase):
ctx =... | :see: doc of method on parent class |
def set_app_id(self, id, version, icon):
'''Sets some meta-information about the application.
See also L{set_user_agent}().
@param id: Java-style application identifier, e.g. "com.acme.foobar".
@param version: application version numbers, e.g. "1.2.3".
@param icon: application ic... | Sets some meta-information about the application.
See also L{set_user_agent}().
@param id: Java-style application identifier, e.g. "com.acme.foobar".
@param version: application version numbers, e.g. "1.2.3".
@param icon: application icon name, e.g. "foobar".
@version: LibVLC 2.1... |
def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, len(buf)
return buf[match.start(1):match.end(1)], match.end(0) | Require a regular expression at the current buffer position. |
def get_queryset(self):
'''
If MultiTenantMiddleware is used, filter queryset by request.site_id
'''
queryset = super(PageList, self).get_queryset()
if hasattr(self.request, 'site_id'):
queryset = queryset.filter(site_id=self.request.site_id)
return queryset | If MultiTenantMiddleware is used, filter queryset by request.site_id |
def write(self, location=None):
"""
Write file to I/O backend.
"""
# Take location and expand tilde.
if location is not None:
self.location = location
assert self.location
# Find I/O backend that handles this location.
for io in self.editor.io... | Write file to I/O backend. |
def move_forward(columns=1, file=sys.stdout):
""" Move the cursor forward a number of columns.
Esc[<columns>C:
Moves the cursor forward by the specified number of columns without
changing lines. If the cursor is already in the rightmost column,
ANSI.SYS ignores this sequence.
""... | Move the cursor forward a number of columns.
Esc[<columns>C:
Moves the cursor forward by the specified number of columns without
changing lines. If the cursor is already in the rightmost column,
ANSI.SYS ignores this sequence. |
def wait_until(predicate, success_description, timeout=10):
"""Wait up to 10 seconds (by default) for predicate to be true.
E.g.:
wait_until(lambda: client.primary == ('a', 1),
'connect to the primary')
If the lambda-expression isn't true after 10 seconds, we raise
Assertio... | Wait up to 10 seconds (by default) for predicate to be true.
E.g.:
wait_until(lambda: client.primary == ('a', 1),
'connect to the primary')
If the lambda-expression isn't true after 10 seconds, we raise
AssertionError("Didn't ever connect to the primary").
Returns the pred... |
def clear_all():
"""DANGER!
*This command is a maintenance tool and clears the complete database.*
"""
sure = input("Are you sure to drop the complete database content? (Type "
"in upppercase YES)")
if not (sure == 'YES'):
db_log('Not deleting the database.')
sys.ex... | DANGER!
*This command is a maintenance tool and clears the complete database.* |
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate,
weight_decay, batch_size):
"""Trains the model."""
dataset_train = gluon.data.ArrayDataset(X_train, y_train)
data_iter_train = gluon.data.DataLoader(dataset_train, batch_size,
shuffle... | Trains the model. |
def main_make_views(gtfs_fname):
"""Re-create all views.
"""
print("creating views")
conn = GTFS(fname_or_conn=gtfs_fname).conn
for L in Loaders:
L(None).make_views(conn)
conn.commit() | Re-create all views. |
async def get_blueprint_params(request, left: int, right: int) -> str:
"""
API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/).
"""
res = left * right
return "{left}*{right}={res}".format(left=left, right=right, res=res) | API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/). |
def lookup_defs(self, variable, size_threshold=32):
"""
Find all definitions of the varaible
:param SimVariable variable: The variable to lookup for.
:param int size_threshold: The maximum bytes to consider for the variable. For example, if the variable is 100
... | Find all definitions of the varaible
:param SimVariable variable: The variable to lookup for.
:param int size_threshold: The maximum bytes to consider for the variable. For example, if the variable is 100
byte long, only the first `size_threshold` bytes are considered... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.