code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def TableDrivenVacuumAgent():
"[Fig. 2.3]"
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Clean'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_A, 'Dir... | [Fig. 2.3] |
def get(self, element, selected=False):
"""
Returns the curses attribute code for the given element.
"""
if self._attribute_map is None:
raise RuntimeError('Attempted to access theme attribute before '
'calling initialize_curses_theme()')
... | Returns the curses attribute code for the given element. |
def _header_poster(self, uri, headers):
"""POST Headers on a specified object in the container.
:param uri: ``str``
:param headers: ``dict``
"""
resp = self.http.post(url=uri, body=None, headers=headers)
self._resp_exception(resp=resp)
return resp | POST Headers on a specified object in the container.
:param uri: ``str``
:param headers: ``dict`` |
def load_index(self, filename, reindex=False):
''' Load the Layout's index from a plaintext file.
Args:
filename (str): Path to the plaintext index file.
reindex (bool): If True, discards entity values provided in the
loaded index and instead re-indexes every fil... | Load the Layout's index from a plaintext file.
Args:
filename (str): Path to the plaintext index file.
reindex (bool): If True, discards entity values provided in the
loaded index and instead re-indexes every file in the loaded
index against the entities ... |
def image_convert(fname,saveAs=True,showToo=False):
"""
Convert weird TIF files into web-friendly versions.
Auto contrast is applied (saturating lower and upper 0.1%).
make saveAs True to save as .TIF.png
make saveAs False and it won't save at all
make saveAs "someFile.jpg" to save i... | Convert weird TIF files into web-friendly versions.
Auto contrast is applied (saturating lower and upper 0.1%).
make saveAs True to save as .TIF.png
make saveAs False and it won't save at all
make saveAs "someFile.jpg" to save it as a different path/format |
def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None):
"""
Computes the inverse kinematic on the specified target with an optimization method
Parameters
----------
chain: ikpy.chain.Chain
The chain used for the Inverse k... | Computes the inverse kinematic on the specified target with an optimization method
Parameters
----------
chain: ikpy.chain.Chain
The chain used for the Inverse kinematics.
target_frame: numpy.array
The desired target.
starting_nodes_angles: numpy.array
The initial pose of yo... |
def reverse_pivot_to_fact(self, staging_table, piv_column, piv_list, from_column, meas_names, meas_values, new_line):
"""
For each column in the piv_list, append ALL from_column's using the group_list
e.g.
Input Table
YEAR Person Q1 Q2
2010 Fre... | For each column in the piv_list, append ALL from_column's using the group_list
e.g.
Input Table
YEAR Person Q1 Q2
2010 Fred Spain 14
2010 Jane Spain 13.995
Output Table
Year Person Question ... |
def hdbscan(X, min_cluster_size=5, min_samples=None, alpha=1.0,
metric='minkowski', p=2, leaf_size=40,
algorithm='best', memory=Memory(cachedir=None, verbose=0),
approx_min_span_tree=True, gen_min_span_tree=False,
core_dist_n_jobs=4,
cluster_selection_method='... | Perform HDBSCAN clustering from a vector array or distance matrix.
Parameters
----------
X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \
array of shape (n_samples, n_samples)
A feature array, or array of distances between samples if
``metric='precomputed'... |
def cli(ctx, feature_id, old_db, old_accession, new_db, new_accession, organism="", sequence=""):
"""Delete a dbxref from a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.update_dbxref(feature_id, old_db, old_accession, new_db, new_accession,... | Delete a dbxref from a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]}) |
def get_service_account_token(request, service_account='default'):
"""Get the OAuth 2.0 access token for a service account.
Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
service_account (str): The string 'default' or a service account email
... | Get the OAuth 2.0 access token for a service account.
Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
service_account (str): The string 'default' or a service account email
address. The determines which service account for which to acqui... |
def _updateFrame(self):
"""
Updates the frame for the given sender.
"""
mov = self.movie()
if mov:
self.setIcon(QtGui.QIcon(mov.currentPixmap())) | Updates the frame for the given sender. |
def write_string(self, string):
""" Writes a string to the underlying output file as a buffer of chars with UTF-8 encoding. """
buf = bytes(string, 'UTF-8')
length = len(buf)
self.write_int(length)
self.write(buf) | Writes a string to the underlying output file as a buffer of chars with UTF-8 encoding. |
def _parse_byte_data(self, byte_data):
"""Extract the values from byte string."""
self.data_type = b''.join(unpack('cccc', byte_data[:4])).decode()
self.run = unpack('>i', byte_data[4:8])[0]
self.udp_sequence = unpack('>i', byte_data[8:12])[0]
self.timestamp, self.ns_ticks = unpa... | Extract the values from byte string. |
def _update_record(self, identifier=None, rtype=None, name=None, content=None): # pylint: disable=too-many-locals,too-many-branches
"""
Connects to Hetzner account, changes an existing record and returns a boolean,
if update was successful or not. Needed identifier or rtype & name to lookup
... | Connects to Hetzner account, changes an existing record and returns a boolean,
if update was successful or not. Needed identifier or rtype & name to lookup
over all records of the zone for exactly one record to update. |
def Expandkey(key, clen):
""" Internal method supporting encryption and decryption functionality. """
import sha
from string import join
from array import array
blocks = (clen + 19) / 20
xkey = []
seed = key
for i in xrange(blocks):
seed = sha.new(key + seed).digest()
xkey.append(seed)
j = join... | Internal method supporting encryption and decryption functionality. |
async def redis(self) -> aioredis.RedisConnection:
"""
Get Redis connection
This property is awaitable.
"""
# Use thread-safe asyncio Lock because this method without that is not safe
async with self._connection_lock:
if self._redis is None:
s... | Get Redis connection
This property is awaitable. |
def init_array(store, shape, chunks=True, dtype=None, compressor='default',
fill_value=None, order='C', overwrite=False, path=None,
chunk_store=None, filters=None, object_codec=None):
"""Initialize an array store with the given configuration. Note that this is a low-level
function ... | Initialize an array store with the given configuration. Note that this is a low-level
function and there should be no need to call this directly from user code.
Parameters
----------
store : MutableMapping
A mapping that supports string keys and bytes-like values.
shape : int or tuple of in... |
def mctransp(I,J,K,c,d,M):
"""mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for ... | mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for commodity k at node i
- M[... |
def taf(wxdata: TafData, units: Units) -> TafTrans:
"""
Translate the results of taf.parse
Keys: Forecast, Min-Temp, Max-Temp
Forecast keys: Wind, Visibility, Clouds, Altimeter, Wind-Shear, Turbulance, Icing, Other
"""
translations = {'forecast': []} # type: ignore
for line in wxdata.fore... | Translate the results of taf.parse
Keys: Forecast, Min-Temp, Max-Temp
Forecast keys: Wind, Visibility, Clouds, Altimeter, Wind-Shear, Turbulance, Icing, Other |
def validate_aead_otp(self, public_id, otp, key_handle, aead):
"""
Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@para... | Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to
decrypt the AEAD.
@param public_id: The six bytes public id of the YubiKey
@param otp: The one time password (OTP) to validate
@param key_handle: The key handle that can decrypt the AEAD
@param aead: AEAD co... |
def with_access_to(self, request, *args, **kwargs): # pylint: disable=invalid-name,unused-argument
"""
Returns the list of enterprise customers the user has a specified group permission access to.
"""
self.queryset = self.queryset.order_by('name')
enterprise_id = self.request.qu... | Returns the list of enterprise customers the user has a specified group permission access to. |
def header(text):
'''Display an header'''
print(' '.join((blue('>>'), cyan(text))))
sys.stdout.flush() | Display an header |
def pool(n=None, dummy=False):
"""
create a multiprocessing pool that responds to interrupts.
"""
if dummy:
from multiprocessing.dummy import Pool
else:
from multiprocessing import Pool
if n is None:
import multiprocessing
n = multiprocessing.cpu_count() - 1
... | create a multiprocessing pool that responds to interrupts. |
def Mean(self):
"""Computes the mean of a CDF.
Returns:
float mean
"""
old_p = 0
total = 0.0
for x, new_p in zip(self.xs, self.ps):
p = new_p - old_p
total += p * x
old_p = new_p
return total | Computes the mean of a CDF.
Returns:
float mean |
def unapprove(self, **kwargs):
"""Unapprove the merge request.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabMRApprovalError: If the unapproval failed
"""
... | Unapprove the merge request.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabMRApprovalError: If the unapproval failed |
def module_entry(yfile):
"""Add entry for one file containing YANG module text.
Args:
yfile (file): File containing a YANG module or submodule.
"""
ytxt = yfile.read()
mp = ModuleParser(ytxt)
mst = mp.statement()
submod = mst.keyword == "submodule"
import_only = True
rev = "... | Add entry for one file containing YANG module text.
Args:
yfile (file): File containing a YANG module or submodule. |
def set_row_name(self, index, name):
"""
Sets the row name.
:param index: the 0-based row index
:type index: int
:param name: the name of the row
:type name: str
"""
javabridge.call(self.jobject, "setRowName", "(ILjava/lang/String;)V", index, name) | Sets the row name.
:param index: the 0-based row index
:type index: int
:param name: the name of the row
:type name: str |
def next(self):
"""
Returns the next packet in the cap.
If the capture's keep_packets flag is True, will also keep it in the internal packet list.
"""
if not self.keep_packets:
return self._packet_generator.send(None)
elif self._current_packet >= len(self._pac... | Returns the next packet in the cap.
If the capture's keep_packets flag is True, will also keep it in the internal packet list. |
def _cleanstarlog(file_in):
"""
cleaning history.data or star.log file, e.g. to take care of
repetitive restarts.
private, should not be called by user directly
Parameters
----------
file_in : string
Typically the filename of the mesa output history.data or
star.log file, c... | cleaning history.data or star.log file, e.g. to take care of
repetitive restarts.
private, should not be called by user directly
Parameters
----------
file_in : string
Typically the filename of the mesa output history.data or
star.log file, creates a clean file called history.datas... |
def init_all_objects(self, data, target=None, single_result=True):
"""
Initializes model instances from given data.
Returns single instance if single_result=True.
"""
if single_result:
return self.init_target_object(target, data)
return list(self.expand_models... | Initializes model instances from given data.
Returns single instance if single_result=True. |
async def readobj(self):
"""
Return a parsed Redis object or an exception
when something wrong happened.
"""
assert self._parser is not None, "set_parser must be called"
while True:
obj = self._parser.gets()
if obj is not False:
# ... | Return a parsed Redis object or an exception
when something wrong happened. |
def send_put(self, mri, attribute_name, value):
"""Abstract method to dispatch a Put to the server
Args:
mri (str): The mri of the Block
attribute_name (str): The name of the Attribute within the Block
value: The value to put
"""
path = attribute_name... | Abstract method to dispatch a Put to the server
Args:
mri (str): The mri of the Block
attribute_name (str): The name of the Attribute within the Block
value: The value to put |
def get_activity_ids_by_objective_bank(self, objective_bank_id):
"""Gets the list of ``Activity`` ``Ids`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.id.IdList) - list of related activity ``Ids``
... | Gets the list of ``Activity`` ``Ids`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.id.IdList) - list of related activity ``Ids``
raise: NotFound - ``objective_bank_id`` is not found
raise: ... |
def violations(self, src_path):
"""
Return a list of Violations recorded in `src_path`.
"""
if not any(src_path.endswith(ext) for ext in self.driver.supported_extensions):
return []
if src_path not in self.violations_dict:
if self.reports:
... | Return a list of Violations recorded in `src_path`. |
def send(self, use_open_peers=True, queue=True, **kw):
"""
send a transaction immediately. Failed transactions are picked up by the TxBroadcaster
:param ip: specific peer IP to send tx to
:param port: port of specific peer
:param use_open_peers: use Arky's broadcast method
... | send a transaction immediately. Failed transactions are picked up by the TxBroadcaster
:param ip: specific peer IP to send tx to
:param port: port of specific peer
:param use_open_peers: use Arky's broadcast method |
def frequency_app(parser, cmd, args): # pragma: no cover
"""
perform frequency analysis on a value.
"""
parser.add_argument('value', help='the value to analyse, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
data = frequency(six.iterbytes(pwnypack.main.binary_value_or_s... | perform frequency analysis on a value. |
def subjects(self):
""" Return identifiers for all the subjects that are in the cache.
:return: list of subject identifiers
"""
subj = [i["subject_id"] for i in self._cache.find()]
return list(set(subj)) | Return identifiers for all the subjects that are in the cache.
:return: list of subject identifiers |
def __add_location(self, type, *args):
"""
Defines the slot triggered by **Where_lineEdit** Widget when a context menu entry is clicked.
:param type: Location type.
:type type: unicode
:param \*args: Arguments.
:type \*args: \*
"""
if type == "directory"... | Defines the slot triggered by **Where_lineEdit** Widget when a context menu entry is clicked.
:param type: Location type.
:type type: unicode
:param \*args: Arguments.
:type \*args: \* |
def get_settings(self):
'''get all settings for a client, if defined in config.
'''
config = self._load_config_user()
if self.name in config:
return config[self.name] | get all settings for a client, if defined in config. |
def _iterslice(self, slice):
"""Yield records from a slice index."""
indices = range(*slice.indices(len(self._records)))
if self.is_attached():
rows = self._enum_attached_rows(indices)
if slice.step is not None and slice.step < 0:
rows = reversed(list(rows... | Yield records from a slice index. |
def rehash(path, algo='sha256', blocksize=1 << 20):
"""Return (hash, length) for path using hashlib.new(algo)"""
h = hashlib.new(algo)
length = 0
with open(path, 'rb') as f:
block = f.read(blocksize)
while block:
length += len(block)
h.update(block)
bl... | Return (hash, length) for path using hashlib.new(algo) |
def update_local(self):
"""Update CPU stats using psutil."""
# Grab CPU stats using psutil's cpu_percent and cpu_times_percent
# Get all possible values for CPU stats: user, system, idle,
# nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
# The following s... | Update CPU stats using psutil. |
def params_as_tensors(method):
"""
The `params_as_tensors` decorator converts representation for parameters into
their unconstrained tensors, and data holders to their data tensors inside
wrapped function, subject to this function is a member of parameterized object.
"""
@functools.wraps(method)... | The `params_as_tensors` decorator converts representation for parameters into
their unconstrained tensors, and data holders to their data tensors inside
wrapped function, subject to this function is a member of parameterized object. |
def likes_count(obj):
"""
Usage:
{% likes_count obj %}
or
{% likes_count obj as var %}
or
{{ obj|likes_count }}
"""
return Like.objects.filter(
receiver_content_type=ContentType.objects.get_for_model(obj),
receiver_object_id=obj.pk
).count() | Usage:
{% likes_count obj %}
or
{% likes_count obj as var %}
or
{{ obj|likes_count }} |
def _at_include(self, calculator, rule, scope, block):
"""
Implements @include, for @mixins
"""
caller_namespace = rule.namespace
caller_calculator = self._make_calculator(caller_namespace)
funct, caller_argspec = self._get_funct_def(rule, caller_calculator, block.argumen... | Implements @include, for @mixins |
def classpath(self, targets, classpath_prefix=None, classpath_product=None, exclude_scopes=None,
include_scopes=None):
"""Builds a transitive classpath for the given targets.
Optionally includes a classpath prefix or building from a non-default classpath product.
:param targets: the target... | Builds a transitive classpath for the given targets.
Optionally includes a classpath prefix or building from a non-default classpath product.
:param targets: the targets for which to build the transitive classpath.
:param classpath_prefix: optional additional entries to prepend to the classpath.
:para... |
def _jsonfileconstructor(self, filename=None, filepath=None, logger=None):
"""
Constructor method for the JsonFile object.
:param filename: Name of the file
:param filepath: Path to the file
:param logger: Optional logger.
:return: JsonFile
"""
if filepat... | Constructor method for the JsonFile object.
:param filename: Name of the file
:param filepath: Path to the file
:param logger: Optional logger.
:return: JsonFile |
def value(self):
"""
Returns the current value (adjusted for the time decay)
:rtype: float
"""
with self.lock:
now = time.time()
dt = now - self.t0
self.t0 = now
self.p = self.p * (math.pow(self.e, self.r * dt))
return ... | Returns the current value (adjusted for the time decay)
:rtype: float |
def go_offline(connected=None):
"""
connected : bool
If True, the plotly.js library will be loaded
from an online CDN. If False, the plotly.js library will be loaded locally
from the plotly python package
"""
from .auth import get_config_file
if connected is None:
try... | connected : bool
If True, the plotly.js library will be loaded
from an online CDN. If False, the plotly.js library will be loaded locally
from the plotly python package |
def _lock_renewer(lockref, interval, stop):
"""
Renew the lock key in redis every `interval` seconds for as long
as `self._lock_renewal_thread.should_exit` is False.
"""
log = getLogger("%s.lock_refresher" % __name__)
while not stop.wait(timeout=interval):
log... | Renew the lock key in redis every `interval` seconds for as long
as `self._lock_renewal_thread.should_exit` is False. |
def run(self):
"""
Write the input/data files and run LAMMPS.
"""
lammps_cmd = self.lammps_bin + ['-in', self.input_filename]
print("Running: {}".format(" ".join(lammps_cmd)))
p = Popen(lammps_cmd, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate()
... | Write the input/data files and run LAMMPS. |
def _discover_masters(self):
'''
Discover master(s) and decide where to connect, if SSDP is around.
This modifies the configuration on the fly.
:return:
'''
if self.opts['master'] == DEFAULT_MINION_OPTS['master'] and self.opts['discovery'] is not False:
master... | Discover master(s) and decide where to connect, if SSDP is around.
This modifies the configuration on the fly.
:return: |
def remove_index(self, field=None, value=None):
"""
remove_index(field=None, value=None)
Remove the specified field/value pair as an index on this
object.
:param field: The index field.
:type field: string
:param value: The index value.
:type value: stri... | remove_index(field=None, value=None)
Remove the specified field/value pair as an index on this
object.
:param field: The index field.
:type field: string
:param value: The index value.
:type value: string or integer
:rtype: :class:`RiakObject <riak.riak_object.R... |
def is_password_valid(password):
"""
Check if a password is valid
"""
pattern = re.compile(r"^.{4,75}$")
return bool(pattern.match(password)) | Check if a password is valid |
def reshape(x,input_dim):
'''
Reshapes x into a matrix with input_dim columns
'''
x = np.array(x)
if x.size ==input_dim:
x = x.reshape((1,input_dim))
return x | Reshapes x into a matrix with input_dim columns |
def chdir(path: str) -> Iterator[None]:
"""Context manager for changing dir and restoring previous workdir after exit.
"""
curdir = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(curdir) | Context manager for changing dir and restoring previous workdir after exit. |
def parse_delete(prs, conn):
"""Delete record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_delete = prs.add_parser(
'delete', help='delete a record of specific zone')
set_option(prs_delete, 'domain')
conn_options(prs_del... | Delete record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information |
def reload(self, client=None):
"""API call: reload the config via a ``GET`` request.
This method will reload the newest data for the config.
See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs/get
:type client: :class:`... | API call: reload the config via a ``GET`` request.
This method will reload the newest data for the config.
See
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs/get
:type client: :class:`google.cloud.runtimeconfig.client.Client`
... |
def schedule_in(self, job, timedelta):
""" Schedule job to run at datetime.timedelta from now."""
now = long(self._now() * 1e6)
when = now + timedelta.total_seconds() * 1e6
self.schedule(job, when) | Schedule job to run at datetime.timedelta from now. |
def stop_process(self):
"""
Stop the process.
:raises: EnvironmentError if stopping fails due to unknown environment
TestStepError if process stops with non-default returncode and return code is not ignored.
"""
if self.read_thread is not None:
self.logger.de... | Stop the process.
:raises: EnvironmentError if stopping fails due to unknown environment
TestStepError if process stops with non-default returncode and return code is not ignored. |
def tracer(object):
"""
| Traces execution.
| Any method / definition decorated will have it's execution traced.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
@functools.partial(validate_tracer, object)
... | | Traces execution.
| Any method / definition decorated will have it's execution traced.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object |
def update_dimension(model, input_dimension):
"""
Given a model that takes an array of dimension input_dimension, returns
the output dimension.
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
_sklearn_util.check_fitted(mod... | Given a model that takes an array of dimension input_dimension, returns
the output dimension. |
def driver(self, sim):
"""
Push data to interface
set vld high and wait on rd in high then pass new data
"""
r = sim.read
# pop new data if there are not any pending
if self.actualData is NOP and self.data:
self.actualData = self.data.popleft()
... | Push data to interface
set vld high and wait on rd in high then pass new data |
def add_suffix(self, suffix):
"""
Suffix labels with string `suffix`.
For Series, the row labels are suffixed.
For DataFrame, the column labels are suffixed.
Parameters
----------
suffix : str
The string to add after each label.
Returns
... | Suffix labels with string `suffix`.
For Series, the row labels are suffixed.
For DataFrame, the column labels are suffixed.
Parameters
----------
suffix : str
The string to add after each label.
Returns
-------
Series or DataFrame
... |
def cd(self, path=None):
"""
Get or set the current working directory from the underlying
interpreter (see https://en.wikipedia.org/wiki/Working_directory).
Args:
path: New working directory or None (to display the working
directory).
Returns:
... | Get or set the current working directory from the underlying
interpreter (see https://en.wikipedia.org/wiki/Working_directory).
Args:
path: New working directory or None (to display the working
directory).
Returns:
Current working directory. |
def _Close(self):
"""Closes the file system.
Raises:
IOError: if the close failed.
"""
self._cpio_archive_file.Close()
self._cpio_archive_file = None
self._file_object.close()
self._file_object = None | Closes the file system.
Raises:
IOError: if the close failed. |
def create_schema(self):
"""Create all necessary tables"""
execute = self.cursor.execute
try:
return execute('SELECT 1 FROM gauged_statistics')
except self.psycopg2.ProgrammingError:
pass
self.db.rollback()
execute("""CREATE TABLE IF NOT EXISTS gau... | Create all necessary tables |
def create_reference_server_flask_app(cfg):
"""Create referece server Flask application with one or more IIIF handlers."""
# Create Flask app
app = Flask(__name__)
Flask.secret_key = "SECRET_HERE"
app.debug = cfg.debug
# Install request handlers
client_prefixes = dict()
for api_version i... | Create referece server Flask application with one or more IIIF handlers. |
def use_comparative_bin_view(self):
"""Pass through to provider ResourceBinSession.use_comparative_bin_view"""
self._bin_view = COMPARATIVE
# self._get_provider_session('resource_bin_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
... | Pass through to provider ResourceBinSession.use_comparative_bin_view |
def func(self, node):
'func = "(" parameters ")" _ "->" expr'
_, params, _, _, _, expr = node
params = map(self.eval, params)
def func(*args):
env = dict(self.env.items() + zip(params, args))
return Mini(env).eval(expr)
return func | func = "(" parameters ")" _ "->" expr |
def list_all(self):
'''
Return a list of the reactors
'''
if isinstance(self.minion.opts['reactor'], six.string_types):
log.debug('Reading reactors from yaml %s', self.opts['reactor'])
try:
with salt.utils.files.fopen(self.opts['reactor']) as fp_:
... | Return a list of the reactors |
def shift_rows(state):
"""
Transformation in the Cipher that processes the State by cyclically shifting
the last three rows of the State by different offsets.
"""
state = state.reshape(4, 4, 8)
return fcat(
state[0][0], state[1][1], state[2][2], state[3][3],
state[1][0], state[2]... | Transformation in the Cipher that processes the State by cyclically shifting
the last three rows of the State by different offsets. |
def Missenard(T, P, Tc, Pc, kl):
r'''Adjustes for pressure the thermal conductivity of a liquid using an
emperical formula based on [1]_, but as given in [2]_.
.. math::
\frac{k}{k^*} = 1 + Q P_r^{0.7}
Parameters
----------
T : float
Temperature of fluid [K]
P : float
... | r'''Adjustes for pressure the thermal conductivity of a liquid using an
emperical formula based on [1]_, but as given in [2]_.
.. math::
\frac{k}{k^*} = 1 + Q P_r^{0.7}
Parameters
----------
T : float
Temperature of fluid [K]
P : float
Pressure of fluid [Pa]
Tc: flo... |
def max_id_length(self):
"""
Returns the maximum length of a todo ID, used for formatting purposes.
"""
if config().identifiers() == "text":
return max_id_length(len(self._todos))
else:
try:
return math.ceil(math.log(len(self._todos), 10))
... | Returns the maximum length of a todo ID, used for formatting purposes. |
def __set_data(self, data):
"""
Sets the given state data on the given entity of the given class.
:param data: State data to set.
:type data: Dictionary mapping attributes to attribute values.
:param entity: Entity to receive the state data.
"""
ent = self.__enti... | Sets the given state data on the given entity of the given class.
:param data: State data to set.
:type data: Dictionary mapping attributes to attribute values.
:param entity: Entity to receive the state data. |
def reload(self, index):
"""Reload file from disk"""
finfo = self.data[index]
txt, finfo.encoding = encoding.read(finfo.filename)
finfo.lastmodified = QFileInfo(finfo.filename).lastModified()
position = finfo.editor.get_position('cursor')
finfo.editor.set_text(txt)
... | Reload file from disk |
def status(self):
"""Return the current status of the solve.
Returns:
SolverStatus: Enum representation of the state of the solver.
"""
if self.request_list.conflict:
return SolverStatus.failed
if self.callback_return == SolverCallbackReturn.fail:
... | Return the current status of the solve.
Returns:
SolverStatus: Enum representation of the state of the solver. |
def get_next(self,oid):
"""Return snmp value for the next OID."""
try: # Nested try..except because of Python 2.4
self.lock.acquire()
try:
# remove trailing zeroes from the oid
while len(oid) > 0 and oid[-2:] == ".0" and oid not in self.data:
oid = oid[:-2];
return self.get(self.data_idx[self... | Return snmp value for the next OID. |
def topoplot(values, locations, axes=None, offset=(0, 0), plot_locations=True,
plot_head=True, **kwargs):
"""Wrapper function for :class:`Topoplot.
"""
topo = Topoplot(**kwargs)
topo.set_locations(locations)
topo.set_values(values)
topo.create_map()
topo.plot_map(axes=axes, offs... | Wrapper function for :class:`Topoplot. |
def groupby(self, group, squeeze: bool = True):
"""Returns a GroupBy object for performing grouped operations.
Parameters
----------
group : str, DataArray or IndexVariable
Array whose unique values should be used to group this array. If a
string, must be the nam... | Returns a GroupBy object for performing grouped operations.
Parameters
----------
group : str, DataArray or IndexVariable
Array whose unique values should be used to group this array. If a
string, must be the name of a variable contained in this dataset.
squeeze ... |
def _build_connstr(host, port, bucket):
"""
Converts a 1.x host:port specification to a connection string
"""
hostlist = []
if isinstance(host, (tuple, list)):
for curhost in host:
if isinstance(curhost, (list, tuple)):
hostlist.append(_fmthost(*curhost))
... | Converts a 1.x host:port specification to a connection string |
def _screen(self, s, newline=False):
"""Print something on screen when self.verbose == True"""
if self.verbose:
if newline:
print(s)
else:
print(s, end=' ') | Print something on screen when self.verbose == True |
def freefn(self, key, free_fn):
"""
Set a free function for the specified hash table item. When the item is
destroyed, the free function, if any, is called on that item.
Use this when hash items are dynamically allocated, to ensure that
you don't have memory leaks. You can pass 'free' or NULL as a free_... | Set a free function for the specified hash table item. When the item is
destroyed, the free function, if any, is called on that item.
Use this when hash items are dynamically allocated, to ensure that
you don't have memory leaks. You can pass 'free' or NULL as a free_fn.
Returns the item, or NULL if there is no such it... |
def which_roles_can(self, name):
"""Which role can SendMail? """
targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first()
return [{'role': group.role} for group in targetPermissionRecords.groups] | Which role can SendMail? |
def ping(self, reconnect=True):
"""
Check if the server is alive.
:param reconnect: If the connection is closed, reconnect.
:raise Error: If the connection is closed and reconnect=False.
"""
if self._sock is None:
if reconnect:
self.connect()
... | Check if the server is alive.
:param reconnect: If the connection is closed, reconnect.
:raise Error: If the connection is closed and reconnect=False. |
def render(self, route=None):
"""
Renders the application and returns the HTML unicode that would
normally appear when visiting in the browser.
"""
if route is None:
route = '/'
with self.test_client() as c:
response = c.get(route, follow_redirects... | Renders the application and returns the HTML unicode that would
normally appear when visiting in the browser. |
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
"""Same as tree_multiplier, but uses two's-complement signed integers"""
if len(A) == 1 or len(B) == 1:
raise pyrtl.PyrtlError("sign bit required, one or both wires too small")
aneg, bneg = A[-1], B[-1]... | Same as tree_multiplier, but uses two's-complement signed integers |
def calc_crc(raw_mac):
"""
This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00.
"""
result = 0x00
for b in struct.unpack("B" * 6, raw_mac):
result ^= b
for _ in rang... | This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00. |
def progress(status_code):
"""Translate PROGRESS status codes from GnuPG to messages."""
lookup = {
'pk_dsa': 'DSA key generation',
'pk_elg': 'Elgamal key generation',
'primegen': 'Prime generation',
'need_entropy': 'Waiting for new entropy in the RNG',
'tick': 'Generic t... | Translate PROGRESS status codes from GnuPG to messages. |
def merge_objects(self, mujoco_objects):
"""Adds physical objects to the MJCF model."""
self.mujoco_objects = mujoco_objects
self.objects = {} # xml manifestation
self.max_horizontal_radius = 0
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mj... | Adds physical objects to the MJCF model. |
def isInstalledBuild(self):
"""
Determines if the Engine is an Installed Build
"""
sentinelFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'InstalledBuild.txt')
return os.path.exists(sentinelFile) | Determines if the Engine is an Installed Build |
def setup_logger():
"""
setup basic logger
"""
logger = logging.getLogger('dockerstache')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
return logger | setup basic logger |
def update(self):
""" updates the configuration settings """
with open(os.path.join(self.config_dir, CONFIG_FILE_NAME), 'w') as config_file:
self.config.write(config_file) | updates the configuration settings |
def dict_fun(data, function):
"""
Apply a function to all values in a dictionary, return a dictionary with
results.
Parameters
----------
data : dict
a dictionary whose values are adequate input to the second argument
of this function.
function : function
a function... | Apply a function to all values in a dictionary, return a dictionary with
results.
Parameters
----------
data : dict
a dictionary whose values are adequate input to the second argument
of this function.
function : function
a function that takes one argument
Returns
... |
def update(self, key, value):
"""Updates a value of a given key and apply reduction"""
if key not in self.value:
self.value[key] = ReducedMetric(self.reducer)
self.value[key].update(value) | Updates a value of a given key and apply reduction |
def show_xys(self, xs, ys, max_len:int=70)->None:
"Show the `xs` (inputs) and `ys` (targets). `max_len` is the maximum number of tokens displayed."
from IPython.display import display, HTML
names = ['idx','text'] if self._is_lm else ['text','target']
items = []
for i, (x,y) in en... | Show the `xs` (inputs) and `ys` (targets). `max_len` is the maximum number of tokens displayed. |
def cleanup_docstamp_output(output_dir=''):
""" Remove the 'tmp*.aux', 'tmp*.out' and 'tmp*.log' files in `output_dir`.
:param output_dir:
"""
suffixes = ['aux', 'out', 'log']
files = [f for suf in suffixes for f in glob(os.path.join(output_dir, 'tmp*.{}'.format(suf)))]
[os.remove(file) for file... | Remove the 'tmp*.aux', 'tmp*.out' and 'tmp*.log' files in `output_dir`.
:param output_dir: |
def main():
"""
NAME
orientation_magic.py
DESCRIPTION
takes tab delimited field notebook information and converts to MagIC formatted tables
SYNTAX
orientation_magic.py [command line options]
OPTIONS
-f FILE: specify input file, default is: orient.txt
-Fsa F... | NAME
orientation_magic.py
DESCRIPTION
takes tab delimited field notebook information and converts to MagIC formatted tables
SYNTAX
orientation_magic.py [command line options]
OPTIONS
-f FILE: specify input file, default is: orient.txt
-Fsa FILE: specify output file... |
def _inject():
""" Copy functions from OpenGL.GL into _pyopengl namespace.
"""
NS = _pyopengl2.__dict__
for glname, ourname in _pyopengl2._functions_to_import:
func = _get_function_from_pyopengl(glname)
NS[ourname] = func | Copy functions from OpenGL.GL into _pyopengl namespace. |
def load_ipa_data():
"""
Load the IPA data from the built-in IPA database, creating the following globals:
1. ``IPA_CHARS``: list of all IPAChar objects
2. ``UNICODE_TO_IPA``: dict mapping a Unicode string (often, a single char) to an IPAChar
3. ``UNICODE_TO_IPA_MAX_KEY_LENGTH``: length of a longes... | Load the IPA data from the built-in IPA database, creating the following globals:
1. ``IPA_CHARS``: list of all IPAChar objects
2. ``UNICODE_TO_IPA``: dict mapping a Unicode string (often, a single char) to an IPAChar
3. ``UNICODE_TO_IPA_MAX_KEY_LENGTH``: length of a longest key in ``UNICODE_TO_IPA``
4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.