code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def integrate(self, function, lower_bound, upper_bound):
"""
Calculates the integral of the given one dimensional function
in the interval from lower_bound to upper_bound, with the simplex integration method.
"""
ret = 0.0
n = self.nsteps
xStep = (float(upper_boun... | Calculates the integral of the given one dimensional function
in the interval from lower_bound to upper_bound, with the simplex integration method. |
def readlen(args):
"""
%prog readlen fastqfile
Calculate read length, will only try the first N reads. Output min, max, and
avg for each file.
"""
p = OptionParser(readlen.__doc__)
p.set_firstN()
p.add_option("--silent", default=False, action="store_true",
help="Do not ... | %prog readlen fastqfile
Calculate read length, will only try the first N reads. Output min, max, and
avg for each file. |
def fftw_normxcorr(templates, stream, pads, threaded=False, *args, **kwargs):
"""
Normalised cross-correlation using the fftw library.
Internally this function used double precision numbers, which is definitely
required for seismic data. Cross-correlations are computed as the
inverse fft of the dot... | Normalised cross-correlation using the fftw library.
Internally this function used double precision numbers, which is definitely
required for seismic data. Cross-correlations are computed as the
inverse fft of the dot product of the ffts of the stream and the reversed,
normalised, templates. The cross... |
def get_changes(self, fixer=str.lower,
task_handle=taskhandle.NullTaskHandle()):
"""Fix module names
`fixer` is a function that takes and returns a `str`. Given
the name of a module, it should return the fixed name.
"""
stack = changestack.ChangeStack(self.... | Fix module names
`fixer` is a function that takes and returns a `str`. Given
the name of a module, it should return the fixed name. |
def memoize(f):
"""Memoization decorator for a function taking one or more arguments."""
def _c(*args, **kwargs):
if not hasattr(f, 'cache'):
f.cache = dict()
key = (args, tuple(kwargs))
if key not in f.cache:
f.cache[key] = f(*args, **kwargs)
return f.cac... | Memoization decorator for a function taking one or more arguments. |
def repack_all(self):
"""Repacks the side chains of all Polymers in the Assembly."""
non_na_sequences = [s for s in self.sequences if ' ' not in s]
self.pack_new_sequences(non_na_sequences)
return | Repacks the side chains of all Polymers in the Assembly. |
def to_bytes(self):
r'''
Create bytes from properties
>>> message = DataPacket(nonce='XyZ', instance_id=1234,
... payload='SomeDummyPayloadData')
>>> message.to_bytes()
'\x88XyZ\x00\x04\xd2\x00SomeDummyPayloadData'
'''
# Verify that p... | r'''
Create bytes from properties
>>> message = DataPacket(nonce='XyZ', instance_id=1234,
... payload='SomeDummyPayloadData')
>>> message.to_bytes()
'\x88XyZ\x00\x04\xd2\x00SomeDummyPayloadData' |
def get_vlan_brief_output_vlan_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubEl... | Auto Generated Code |
def get_patient_pharmacies(self, patient_id,
patients_favorite_only='N'):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response
"""
magic = self._magic_json(
action=TouchWorksMagicConsta... | invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:return: JSON response |
def get_instance(self, payload):
"""
Build an instance of InviteInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance
:rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance
"""
... | Build an instance of InviteInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.channel.invite.InviteInstance
:rtype: twilio.rest.chat.v2.service.channel.invite.InviteInstance |
def begin_operation(self, conn_or_internal_id, op_name, callback, timeout):
"""Begin an operation on a connection
Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id
op_name (string): The name of the operation that we ... | Begin an operation on a connection
Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id
op_name (string): The name of the operation that we are starting (stored in
the connection's microstate)
callba... |
def insert(self, loc, item):
"""
Make new Index inserting new item at location.
Follows Python list.append semantics for negative values.
Parameters
----------
loc : int
item : object
Returns
-------
new_index : Index
"""
... | Make new Index inserting new item at location.
Follows Python list.append semantics for negative values.
Parameters
----------
loc : int
item : object
Returns
-------
new_index : Index |
def getcwd(cls):
"""
Provide a context dependent current working directory. This method
will return the directory currently holding the lock.
"""
if not hasattr(cls._tl, "cwd"):
cls._tl.cwd = os.getcwd()
return cls._tl.cwd | Provide a context dependent current working directory. This method
will return the directory currently holding the lock. |
def show_vcs_output_nodes_disconnected_from_cluster(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
nodes_disconnected_from_cluster = ET.SubEle... | Auto Generated Code |
def enable_digital_reporting(self, pin):
"""
Enables digital reporting. By turning reporting on for all 8 bits in the "port" -
this is part of Firmata's protocol specification.
:param pin: Pin and all pins for this port
:return: No return value
"""
port = pin //... | Enables digital reporting. By turning reporting on for all 8 bits in the "port" -
this is part of Firmata's protocol specification.
:param pin: Pin and all pins for this port
:return: No return value |
def __get_user(self, login):
"""Get user and org data for the login"""
user = {}
if not login:
return user
user_raw = self.client.user(login)
user = json.loads(user_raw)
user_orgs_raw = \
self.client.user_orgs(login)
user['organizations'... | Get user and org data for the login |
def _remove_wrappers(self):
"""
Uninstall the PluginLoader monkey patches.
"""
ansible_mitogen.loaders.action_loader.get = action_loader__get
ansible_mitogen.loaders.connection_loader.get = connection_loader__get
ansible.executor.process.worker.WorkerProcess.run = worker_... | Uninstall the PluginLoader monkey patches. |
def addFeature(self, features,
gdbVersion=None,
rollbackOnFailure=True):
""" Adds a single feature to the service
Inputs:
feature - list of common.Feature object or a single
common.Feature Object, a FeatureSet object, or a
... | Adds a single feature to the service
Inputs:
feature - list of common.Feature object or a single
common.Feature Object, a FeatureSet object, or a
list of dictionary objects
gdbVersion - Geodatabase version to apply the edits
... |
def pprint(self, indent: str = ' ', remove_comments=False):
"""Deprecated, use self.pformat instead."""
warn(
'pprint method is deprecated, use pformat instead.',
DeprecationWarning,
)
return self.pformat(indent, remove_comments) | Deprecated, use self.pformat instead. |
def on_entry_click(self, event):
"""
function that gets called whenever entry is clicked
"""
if event.widget.config('fg') [4] == 'grey':
event.widget.delete(0, "end" ) # delete all the text in the entry
event.widget.insert(0, '') #Insert blank for user input
event.widget.config(fg = 'black') | function that gets called whenever entry is clicked |
def _fmt_args_kwargs(self, *some_args, **some_kwargs):
"""Helper to convert the given args and kwargs into a string."""
if some_args:
out_args = str(some_args).lstrip('(').rstrip(',)')
if some_kwargs:
out_kwargs = ', '.join([str(i).lstrip('(').rstrip(')').replace(', ',': ... | Helper to convert the given args and kwargs into a string. |
def find_particles_in_tile(positions, tile):
"""
Finds the particles in a tile, as numpy.ndarray of ints.
Parameters
----------
positions : `numpy.ndarray`
[N,3] array of the particle positions to check in the tile
tile : :class:`peri.util.Tile` instance
Tile of ... | Finds the particles in a tile, as numpy.ndarray of ints.
Parameters
----------
positions : `numpy.ndarray`
[N,3] array of the particle positions to check in the tile
tile : :class:`peri.util.Tile` instance
Tile of the region inside which to check for particles.
Retu... |
def _choose_port(self):
"""
Return a port number from 5000-5999 based on the environment name
to be used as a default when the user hasn't selected one.
"""
# instead of random let's base it on the name chosen (and the site name)
return 5000 + unpack('Q',
... | Return a port number from 5000-5999 based on the environment name
to be used as a default when the user hasn't selected one. |
def steam64_from_url(url, http_timeout=30):
"""
Takes a Steam Community url and returns steam64 or None
.. note::
Each call makes a http request to ``steamcommunity.com``
.. note::
For a reliable resolving of vanity urls use ``ISteamUser.ResolveVanityURL`` web api
:param url: stea... | Takes a Steam Community url and returns steam64 or None
.. note::
Each call makes a http request to ``steamcommunity.com``
.. note::
For a reliable resolving of vanity urls use ``ISteamUser.ResolveVanityURL`` web api
:param url: steam community url
:type url: :class:`str`
:param h... |
def tokenized(self, delimiter=' ', overlap_threshold=0.1):
"""
Return a ordered list of tokens based on all labels.
Joins all token from all labels (``label.tokenized()```).
If the overlapping between two labels is greater than ``overlap_threshold``,
an Exception is thrown.
... | Return a ordered list of tokens based on all labels.
Joins all token from all labels (``label.tokenized()```).
If the overlapping between two labels is greater than ``overlap_threshold``,
an Exception is thrown.
Args:
delimiter (str): The delimiter used to split labels into ... |
async def post(self, public_key):
"""Accepting offer by buyer
Function accepts:
- cid
- buyer access string
- buyer public key
- seller public key
"""
logging.debug("[+] -- Deal debugging. ")
if settings.SIGNATURE_VERIFICATION:
super().verify()
# Check if message contains required data
tr... | Accepting offer by buyer
Function accepts:
- cid
- buyer access string
- buyer public key
- seller public key |
def shrink(self):
"""
Calculate the Constant-Correlation covariance matrix.
:return: shrunk sample covariance matrix
:rtype: np.ndarray
"""
x = np.nan_to_num(self.X.values)
# de-mean returns
t, n = np.shape(x)
meanx = x.mean(axis=0)
x = x... | Calculate the Constant-Correlation covariance matrix.
:return: shrunk sample covariance matrix
:rtype: np.ndarray |
def get_notification(self, id):
"""
Return a Notification object.
:param id: The id of the notification object to return.
"""
url = self._base_url + "/3/notification/{0}".format(id)
resp = self._send_request(url)
return Notification(resp, self) | Return a Notification object.
:param id: The id of the notification object to return. |
def get_dag_configs(self) -> Dict[str, Dict[str, Any]]:
"""
Returns configuration for each the DAG in factory
:returns: dict with configuration for dags
"""
return {dag: self.config[dag] for dag in self.config.keys() if dag != "default"} | Returns configuration for each the DAG in factory
:returns: dict with configuration for dags |
def get_connected(self):
"""
Returns the connection status
:returns: a boolean that indicates if connected.
"""
connected = c_int32()
result = self.library.Cli_GetConnected(self.pointer, byref(connected))
check_error(result, context="client")
return bool(... | Returns the connection status
:returns: a boolean that indicates if connected. |
def setValue(self, value):
"""
Sets the value that will be used for this query instance.
:param value <variant>
"""
self.__value = projex.text.decoded(value) if isinstance(value, (str, unicode)) else value | Sets the value that will be used for this query instance.
:param value <variant> |
def history_file(self, location=None):
"""Return history file location.
"""
if location:
# Hardcoded location passed from the config file.
if os.path.exists(location):
return location
else:
logger.warn("The specified history fil... | Return history file location. |
def create_key_ring(
self,
parent,
key_ring_id,
key_ring,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Create a new ``KeyRing`` in a given Project and Location.
E... | Create a new ``KeyRing`` in a given Project and Location.
Example:
>>> from google.cloud import kms_v1
>>>
>>> client = kms_v1.KeyManagementServiceClient()
>>>
>>> parent = client.location_path('[PROJECT]', '[LOCATION]')
>>>
>>... |
def get_draw(self, index: Index, additional_key: Any=None) -> pd.Series:
"""Get an indexed sequence of floats pulled from a uniform distribution over [0.0, 1.0)
Parameters
----------
index :
An index whose length is the number of random draws made
and which index... | Get an indexed sequence of floats pulled from a uniform distribution over [0.0, 1.0)
Parameters
----------
index :
An index whose length is the number of random draws made
and which indexes the returned `pandas.Series`.
additional_key :
Any additional... |
def _line_parse(line):
"""Removes line ending characters and returns a tuple (`stripped_line`,
`is_terminated`).
"""
if line[-2:] in ["\r\n", b"\r\n"]:
return line[:-2], True
elif line[-1:] in ["\r", "\n", b"\r", b"\n"]:
return line[:-1], True
return line, False | Removes line ending characters and returns a tuple (`stripped_line`,
`is_terminated`). |
def process(self):
"""Collect the results.
Raises:
DFTimewolfError: if no files specified
"""
client = self._get_client_by_hostname(self.host)
self._await_flow(client, self.flow_id)
collected_flow_data = self._download_files(client, self.flow_id)
if collected_flow_data:
print('{... | Collect the results.
Raises:
DFTimewolfError: if no files specified |
def getTemplate(self, uri, meta=None):
"""Return the template for an action. Cache the result. Can use an optional meta parameter with meta information"""
if not meta:
metaKey = self.cacheKey + '_templatesmeta_cache_' + uri
meta = cache.get(metaKey, None)
if not m... | Return the template for an action. Cache the result. Can use an optional meta parameter with meta information |
def get_account_holds(self, account_id, **kwargs):
""" Get holds on an account.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Holds are placed on an account for active orders or
pending withdraw requests.
As an order ... | Get holds on an account.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Holds are placed on an account for active orders or
pending withdraw requests.
As an order is filled, the hold amount is updated. If an order
is c... |
def os_change_list(self, subid, params=None):
''' /v1/server/os_change_list
GET - account
Retrieves a list of operating systems to which this server can be
changed.
Link: https://www.vultr.com/api/#server_os_change_list
'''
params = update_params(params, {'SUBID'... | /v1/server/os_change_list
GET - account
Retrieves a list of operating systems to which this server can be
changed.
Link: https://www.vultr.com/api/#server_os_change_list |
def load_nb(cls, inline=True):
"""
Loads any resources required for display of plots
in the Jupyter notebook
"""
with param.logging_level('ERROR'):
cls.notebook_context = True
cls.comm_manager = JupyterCommManager | Loads any resources required for display of plots
in the Jupyter notebook |
def iterline(x1, y1, x2, y2):
'Yields (x, y) coords of line from (x1, y1) to (x2, y2)'
xdiff = abs(x2-x1)
ydiff = abs(y2-y1)
xdir = 1 if x1 <= x2 else -1
ydir = 1 if y1 <= y2 else -1
r = math.ceil(max(xdiff, ydiff))
if r == 0: # point, not line
yield x1, y1
else:
x, y =... | Yields (x, y) coords of line from (x1, y1) to (x2, y2) |
def do_file_upload(client, args):
"""Upload files"""
# Sanity check
if len(args.paths) > 1:
# destination must be a directory
try:
resource = client.get_resource_by_uri(args.dest_uri)
except ResourceNotFoundError:
resource = None
if resource and not ... | Upload files |
def save_parameters(self, path, grad_only=False):
"""Save all parameters into a file with the specified format.
Currently hdf5 and protobuf formats are supported.
Args:
path : path or file object
grad_only (bool, optional): Return parameters with `need_grad` option as `... | Save all parameters into a file with the specified format.
Currently hdf5 and protobuf formats are supported.
Args:
path : path or file object
grad_only (bool, optional): Return parameters with `need_grad` option as `True`. |
def guess_sequence(redeem_script):
'''
str -> int
If OP_CSV is used, guess an appropriate sequence
Otherwise, disable RBF, but leave lock_time on.
Fails if there's not a constant before OP_CSV
'''
try:
script_array = redeem_script.split()
loc = script_array.index('OP_CHECKSEQ... | str -> int
If OP_CSV is used, guess an appropriate sequence
Otherwise, disable RBF, but leave lock_time on.
Fails if there's not a constant before OP_CSV |
def hook_key(key, callback, suppress=False):
"""
Hooks key up and key down events for a single key. Returns the event handler
created. To remove a hooked key use `unhook_key(key)` or
`unhook_key(handler)`.
Note: this function shares state with hotkeys, so `clear_all_hotkeys`
affects it aswell.
... | Hooks key up and key down events for a single key. Returns the event handler
created. To remove a hooked key use `unhook_key(key)` or
`unhook_key(handler)`.
Note: this function shares state with hotkeys, so `clear_all_hotkeys`
affects it aswell. |
def _checkup(peaks, ecg_integrated, sample_rate, rr_buffer, spk1, npk1, threshold):
"""
Check each peak according to thresholds
----------
Parameters
----------
peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
an R peak.
... | Check each peak according to thresholds
----------
Parameters
----------
peaks : list
List of local maximums that pass the first stage of conditions needed to be considered as
an R peak.
ecg_integrated : ndarray
Array that contains the samples of the integrated signal.
s... |
def zinnia_pagination(context, page, begin_pages=1, end_pages=1,
before_pages=2, after_pages=2,
template='zinnia/tags/pagination.html'):
"""
Return a Digg-like pagination,
by splitting long list of page into 3 blocks of pages.
"""
get_string = ''
for k... | Return a Digg-like pagination,
by splitting long list of page into 3 blocks of pages. |
def _get_repeat_masker_header(pairwise_alignment):
"""generate header string of repeatmasker formated repr of self."""
res = ""
res += str(pairwise_alignment.meta[ALIG_SCORE_KEY]) + " "
res += "{:.2f}".format(pairwise_alignment.meta[PCENT_SUBS_KEY]) + " "
res += "{:.2f}".format(pairwise_alignment.meta[PCENT_S... | generate header string of repeatmasker formated repr of self. |
def replace_project(self, owner, id, **kwargs):
"""
Create / Replace a project
Create a project with a given id or completely rewrite the project, including any previously added files or linked datasets, if one already exists with the given id.
This method makes a synchronous HTTP reques... | Create / Replace a project
Create a project with a given id or completely rewrite the project, including any previously added files or linked datasets, if one already exists with the given id.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please d... |
def _apply_filters(self, **filters):
"""Determine rows to keep in data for given set of filters
Parameters
----------
filters: dict
dictionary of filters ({col: values}}); uses a pseudo-regexp syntax
by default, but accepts `regexp: True` to use regexp directly
... | Determine rows to keep in data for given set of filters
Parameters
----------
filters: dict
dictionary of filters ({col: values}}); uses a pseudo-regexp syntax
by default, but accepts `regexp: True` to use regexp directly |
def encrypt_file(file, keys=secretKeys()):
'''Encrypt file data with the same method as the Send browser/js client'''
key = keys.encryptKey
iv = keys.encryptIV
encData = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b')
cipher = Cryptodome.Cipher.AES.new(key, Cryptodome.Cipher.AES.MODE_... | Encrypt file data with the same method as the Send browser/js client |
def missing(name, limit=''):
'''
The inverse of service.available.
Return True if the named service is not available. Use the ``limit`` param to
restrict results to services of that type.
CLI Examples:
.. code-block:: bash
salt '*' service.missing sshd
salt '*' service.missin... | The inverse of service.available.
Return True if the named service is not available. Use the ``limit`` param to
restrict results to services of that type.
CLI Examples:
.. code-block:: bash
salt '*' service.missing sshd
salt '*' service.missing sshd limit=upstart
salt '*' ser... |
def critical(self, msg, *args, **kwargs) -> Task: # type: ignore
"""
Log msg with severity 'CRITICAL'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
await logger.critical("Houston, we have a major disaster", exc_info=1)
"""
... | Log msg with severity 'CRITICAL'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
await logger.critical("Houston, we have a major disaster", exc_info=1) |
def configure_versioning(self, versioning, mfa_delete=False,
mfa_token=None, headers=None):
"""
Configure versioning for this bucket.
..note:: This feature is currently in beta.
:type versioning: bool
:param versioning: A bo... | Configure versioning for this bucket.
..note:: This feature is currently in beta.
:type versioning: bool
:param versioning: A boolean indicating whether version is
enabled (True) or disabled (False).
:type mfa_delete: bool
:p... |
def update_catalog_extent(self, current_extent):
# type: (int) -> None
'''
A method to update the extent associated with this Boot Catalog.
Parameters:
current_extent - New extent to associate with this Boot Catalog
Returns:
Nothing.
'''
if not ... | A method to update the extent associated with this Boot Catalog.
Parameters:
current_extent - New extent to associate with this Boot Catalog
Returns:
Nothing. |
def restart(self, restart_only_stale_services=None,
redeploy_client_configuration=None,
restart_service_names=None):
"""
Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that ... | Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that have stale
configuration and their dependent
services. De... |
def store_random(self):
"""
Populate array with random quartets sampled from a generator.
Holding all sets in memory might take a lot, but holding a very
large list of random numbers for which ones to sample will fit
into memory for most reasonable sized sets. So we'll load a
list of random nu... | Populate array with random quartets sampled from a generator.
Holding all sets in memory might take a lot, but holding a very
large list of random numbers for which ones to sample will fit
into memory for most reasonable sized sets. So we'll load a
list of random numbers in the range of the length of ... |
def get_width(self, c, default=0, match_only=None):
"""
Get the display width of a component. Wraps `getattr()`.
Development note: Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c (component): The componen... | Get the display width of a component. Wraps `getattr()`.
Development note: Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c (component): The component to look up.
default (float): The width to return in the ev... |
def set_nodes_vlan(site, nodes, interface, vlan_id):
"""Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to ... | Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to put in the vlan
vlan_id(str): the id of the vlan |
def todo(self, **kwargs):
"""Create a todo associated to the object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the todo cannot be set
"""
... | Create a todo associated to the object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the todo cannot be set |
def decode_mst(energy: numpy.ndarray,
length: int,
has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""
Note: Counter to typical intuition, this function decodes the _maximum_
spanning tree.
Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for... | Note: Counter to typical intuition, this function decodes the _maximum_
spanning tree.
Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for
maximum spanning arborescences on graphs.
Parameters
----------
energy : ``numpy.ndarray``, required.
A tensor with shape (num_label... |
def _get_synset_offsets(synset_idxes):
"""Returs pointer offset in the WordNet file for every synset index.
Notes
-----
Internal function. Do not call directly.
Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)].
Parameters
----------
synset_idxes : list of ints
... | Returs pointer offset in the WordNet file for every synset index.
Notes
-----
Internal function. Do not call directly.
Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)].
Parameters
----------
synset_idxes : list of ints
Lists synset IDs, which need offset.
... |
def all_announcements_view(request):
''' The view of manager announcements. '''
page_name = "Archives - All Announcements"
userProfile = UserProfile.objects.get(user=request.user)
announcement_form = None
manager_positions = Manager.objects.filter(incumbent=userProfile)
if manager_positions:
... | The view of manager announcements. |
async def update(self) -> None:
"""Retrieve updated device state."""
if self.next_allowed_update is not None and \
datetime.utcnow() < self.next_allowed_update:
return
self.next_allowed_update = None
await self.api._update_device_state()
self._device_... | Retrieve updated device state. |
def to_instants_dataframe(self, sql_ctx):
"""
Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD.
"""
... | Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time.
This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column
is a key form one of the rows in the TimeSeriesRDD. |
def find_expcoef(self, nsd_below=0., plot=False,
trimlim=None, autorange_kwargs={}):
"""
Determines exponential decay coefficient for despike filter.
Fits an exponential decay function to the washout phase of standards
to determine the washout time of your laser cel... | Determines exponential decay coefficient for despike filter.
Fits an exponential decay function to the washout phase of standards
to determine the washout time of your laser cell. The exponential
coefficient reported is `nsd_below` standard deviations below the
fitted exponent, to ensur... |
def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):
"""A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
T... | A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
The dataset name you want to use(the default is 'mnist').
url : str
The url of dataset(th... |
def authenticate_credentials(self, request, access_token):
"""
Authenticate the request, given the access token.
"""
try:
token = oauth2_provider.oauth2.models.AccessToken.objects.select_related('user')
# provider_now switches to timezone aware datetime when
... | Authenticate the request, given the access token. |
def gcs_read(self, remote_log_location):
"""
Returns the log found at the remote_log_location.
:param remote_log_location: the log's location in remote storage
:type remote_log_location: str (path)
"""
bkt, blob = self.parse_gcs_url(remote_log_location)
return sel... | Returns the log found at the remote_log_location.
:param remote_log_location: the log's location in remote storage
:type remote_log_location: str (path) |
def write_byte_data(self, addr, cmd, val):
"""write_byte_data(addr, cmd, val)
Perform SMBus Write Byte Data transaction.
"""
self._set_addr(addr)
if SMBUS.i2c_smbus_write_byte_data(self._fd,
ffi.cast("__u8", cmd),
... | write_byte_data(addr, cmd, val)
Perform SMBus Write Byte Data transaction. |
def _tree_view_builder(self, indent=0, is_root=True):
"""
Build a text to represent the package structure.
"""
def pad_text(indent):
return " " * indent + "|-- "
lines = list()
if is_root:
lines.append(SP_DIR)
lines.append(
... | Build a text to represent the package structure. |
def inverted(self):
'''
Return a version of this instance with inputs replaced by outputs and vice versa.
'''
return Instance(input=self.output, output=self.input,
annotated_input=self.annotated_output,
annotated_output=self.annotated_input... | Return a version of this instance with inputs replaced by outputs and vice versa. |
def trace_integration(tracer=None):
"""Wrap threading functions to trace."""
log.info("Integrated module: {}".format(MODULE_NAME))
# Wrap the threading start function
start_func = getattr(threading.Thread, "start")
setattr(
threading.Thread, start_func.__name__, wrap_threading_start(start_fu... | Wrap threading functions to trace. |
def go_to_position(self, position):
"""
Moves the text cursor to given position.
:param position: Position to go to.
:type position: int
:return: Method success.
:rtype: bool
"""
cursor = self.textCursor()
cursor.setPosition(position)
sel... | Moves the text cursor to given position.
:param position: Position to go to.
:type position: int
:return: Method success.
:rtype: bool |
def convert_block_dicts_to_string(self, block_1st2nd, block_1st, block_2nd, block_3rd):
"""Takes into account whether we need to output all codon positions."""
out = ""
# We need 1st and 2nd positions
if self.codon_positions in ['ALL', '1st-2nd']:
for gene_code, seqs in block... | Takes into account whether we need to output all codon positions. |
def search(self, keyword, count=30):
"""
Search files or directories
:param str keyword: keyword
:param int count: number of entries to be listed
"""
kwargs = {}
kwargs['search_value'] = keyword
root = self.root_directory
entries = root._load_entr... | Search files or directories
:param str keyword: keyword
:param int count: number of entries to be listed |
def condense(self):
"""
Condense the data set to the distinct intervals based on the pseudo key.
"""
for pseudo_key, rows in self._rows.items():
tmp1 = []
intervals = sorted(self._derive_distinct_intervals(rows))
for interval in intervals:
... | Condense the data set to the distinct intervals based on the pseudo key. |
def Prep(self, size, additionalBytes):
"""
Prep prepares to write an element of `size` after `additional_bytes`
have been written, e.g. if you write a string, you need to align
such the int length field is aligned to SizeInt32, and the string
data follows it directly.
If ... | Prep prepares to write an element of `size` after `additional_bytes`
have been written, e.g. if you write a string, you need to align
such the int length field is aligned to SizeInt32, and the string
data follows it directly.
If all you need to do is align, `additionalBytes` will be 0. |
def cbar_value_cb(self, cbar, value, event):
"""
This method is called when the user moves the mouse over the
ColorBar. It displays the value of the mouse position in the
ColorBar in the Readout (if any).
"""
if self.cursor_obj is not None:
readout = self.cur... | This method is called when the user moves the mouse over the
ColorBar. It displays the value of the mouse position in the
ColorBar in the Readout (if any). |
def getkeypress(self):
u'''Return next key press event from the queue, ignoring others.'''
ck = System.ConsoleKey
while 1:
e = System.Console.ReadKey(True)
if e.Key == System.ConsoleKey.PageDown: #PageDown
self.scroll_window(12)
elif e.K... | u'''Return next key press event from the queue, ignoring others. |
def p_expression_lesseq(self, p):
'expression : expression LE expression'
p[0] = LessEq(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression LE expression |
def main():
"""Create application.properties for a given application."""
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_properties(parser)
add_region(parser)
add_artifact_pa... | Create application.properties for a given application. |
def is_writable(filename):
"""Check if
- the file is a regular file and is writable, or
- the file does not exist and its parent directory exists and is
writable
"""
if not os.path.exists(filename):
parentdir = os.path.dirname(filename)
return os.path.isdir(parentdir) and os.ac... | Check if
- the file is a regular file and is writable, or
- the file does not exist and its parent directory exists and is
writable |
def check(self, orb):
"""Method that check whether or not the listener is triggered
Args:
orb (Orbit):
Return:
bool: True if there is a zero-crossing for the parameter watched by the listener
"""
return self.prev is not None and np.sign(self(orb)) != np... | Method that check whether or not the listener is triggered
Args:
orb (Orbit):
Return:
bool: True if there is a zero-crossing for the parameter watched by the listener |
def _value_format(self, value):
"""
Format value for map value display.
"""
return '%s: %s' % (
self.area_names.get(self.adapt_code(value[0]), '?'),
self._y_format(value[1])
) | Format value for map value display. |
def ldeo(magfile, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
specnum=0, samp_con="1", location="unknown", codelist="",
coil="", arm_labfield=50e-6, trm_peakT=873.,... | converts Lamont Doherty Earth Observatory measurement files to MagIC data base model 3.0
Parameters
_________
magfile : input measurement file
dir_path : output directory path, default "."
input_dir_path : input file directory IF different from dir_path, default ""
meas_file : output file measu... |
def get_pull_requests(self, project, repository, state='OPEN', order='newest', limit=100, start=0):
"""
Get pull requests
:param project:
:param repository:
:param state:
:param order: OPTIONAL: defaults to NEWEST) the order to return pull requests in, either OLDEST
... | Get pull requests
:param project:
:param repository:
:param state:
:param order: OPTIONAL: defaults to NEWEST) the order to return pull requests in, either OLDEST
(as in: "oldest first") or NEWEST.
:param limit:
:param start:
:retur... |
def _get_matching(self, reltype, target, is_external=False):
"""
Return relationship of matching *reltype*, *target*, and
*is_external* from collection, or None if not found.
"""
def matches(rel, reltype, target, is_external):
if rel.reltype != reltype:
... | Return relationship of matching *reltype*, *target*, and
*is_external* from collection, or None if not found. |
def update(self,table, sys_id, **kparams):
"""
update a record via table api, kparams being the dict of PUT params to update.
returns a SnowRecord obj.
"""
record = self.api.update(table, sys_id, **kparams)
return record | update a record via table api, kparams being the dict of PUT params to update.
returns a SnowRecord obj. |
def _get_alpha_data(data: np.ndarray, kwargs) -> Union[float, np.ndarray]:
"""Get alpha values for all data points.
Parameters
----------
alpha: Callable or float
This can be a fixed value or a function of the data.
"""
alpha = kwargs.pop("alpha", 1)
if hasattr(alpha, "__call__"):
... | Get alpha values for all data points.
Parameters
----------
alpha: Callable or float
This can be a fixed value or a function of the data. |
def show(self, start_date, end_date):
"""setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux"""
# title in the report file name
vars = {"title": _("Time track"),
"start": start_date.strftime("%x").replace("/", ".")... | setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux |
async def get_headline(self, name):
"""Get stored messages for a service.
Args:
name (string): The name of the service to get messages from.
Returns:
ServiceMessage: the headline or None if no headline has been set
"""
resp = await self.send_command(OPE... | Get stored messages for a service.
Args:
name (string): The name of the service to get messages from.
Returns:
ServiceMessage: the headline or None if no headline has been set |
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
... | Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object). |
def addTab(self, view, title):
"""
Adds a new view tab to this panel.
:param view | <XView>
title | <str>
:return <bool> | success
"""
if not isinstance(view, XView):
return False
tab = self._tabBar.... | Adds a new view tab to this panel.
:param view | <XView>
title | <str>
:return <bool> | success |
def encode_field(self, field, value):
"""Encode the given value as JSON.
Args:
field: a messages.Field for the field we're encoding.
value: a value for field.
Returns:
A python value suitable for json.dumps.
"""
for encoder in _GetFieldCodecs(field... | Encode the given value as JSON.
Args:
field: a messages.Field for the field we're encoding.
value: a value for field.
Returns:
A python value suitable for json.dumps. |
def register_callback(self):
"""Register callback that we will have to wait for"""
cid = str(self.__cid)
self.__cid += 1
event = queue.Queue()
self.__callbacks[cid] = event
return cid, event | Register callback that we will have to wait for |
def _handle_precalled(data):
"""Copy in external pre-called variants fed into analysis.
Symlinks for non-CWL runs where we want to ensure VCF present
in a local directory.
"""
if data.get("vrn_file") and not cwlutils.is_cwl_run(data):
vrn_file = data["vrn_file"]
if isinstance(vrn_fi... | Copy in external pre-called variants fed into analysis.
Symlinks for non-CWL runs where we want to ensure VCF present
in a local directory. |
def _exponent_handler_factory(ion_type, exp_chars, parse_func, first_char=None):
"""Generates a handler co-routine which tokenizes an numeric exponent.
Args:
ion_type (IonType): The type of the value with this exponent.
exp_chars (sequence): The set of ordinals of the legal exponent characters ... | Generates a handler co-routine which tokenizes an numeric exponent.
Args:
ion_type (IonType): The type of the value with this exponent.
exp_chars (sequence): The set of ordinals of the legal exponent characters for this component.
parse_func (callable): Called upon ending the numeric value.... |
def Run(self, arg):
"""Does the actual work."""
try:
if self.grr_worker.client.FleetspeakEnabled():
raise ValueError("Not supported on Fleetspeak enabled clients.")
except AttributeError:
pass
smart_arg = {str(field): value for field, value in iteritems(arg)}
disallowed_fields ... | Does the actual work. |
def get_fmt_widget(self, parent, project):
"""Create a combobox with the attributes"""
from psy_simple.widgets.texts import LabelWidget
return LabelWidget(parent, self, project) | Create a combobox with the attributes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.