Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
362,900 | def TableDrivenVacuumAgent():
"[Fig. 2.3]"
table = {((loc_A, ),): ,
((loc_A, ),): ,
((loc_B, ),): ,
((loc_B, ),): ,
((loc_A, ), (loc_A, )): ,
((loc_A, ), (loc_A, )): ,
((loc_A, ), (loc_A, ), (loc_A, )): ,
((... | [Fig. 2.3] |
362,901 | def get(self, element, selected=False):
if self._attribute_map is None:
raise RuntimeError(
)
if selected or self._selected:
element = .format(element)
return self._attribute_map[element] | Returns the curses attribute code for the given element. |
362,902 | def _header_poster(self, uri, headers):
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`` |
362,903 | def load_index(self, filename, reindex=False):
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
... | 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 ... |
362,904 | def image_convert(fname,saveAs=True,showToo=False):
cutoffLow=np.percentile(im,.01)
cutoffHigh=np.percentile(im,99.99)
im[np.where(im<cutoffLow)]=cutoffLow
im[np.where(im>cutoffHigh)]=cutoffHigh
im-=np.min(im)
im/=np.max(im)
im*=255
im = Image.fromarray(im)... | 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 |
362,905 | def inverse_kinematic_optimization(chain, target_frame, starting_nodes_angles, regularization_parameter=None, max_iter=None):
target = target_frame[:3, 3]
if starting_nodes_angles is None:
raise ValueError("starting_nodes_angles must be specified")
def optimize_target(x):
... | 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... |
362,906 | def reverse_pivot_to_fact(self, staging_table, piv_column, piv_list, from_column, meas_names, meas_values, new_line):
self.sql_text +=
num_chars_on_line = 0
for piv_num in range(len(piv_list)):
self.sql_text += + self.fact_table + + new_line
if pi... | 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 ... |
362,907 | def hdbscan(X, min_cluster_size=5, min_samples=None, alpha=1.0,
metric=, p=2, leaf_size=40,
algorithm=, memory=Memory(cachedir=None, verbose=0),
approx_min_span_tree=True, gen_min_span_tree=False,
core_dist_n_jobs=4,
cluster_selection_method=, allow_single_clu... | 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'... |
362,908 | def cli(ctx, feature_id, old_db, old_accession, new_db, new_accession, organism="", sequence=""):
return ctx.gi.annotations.update_dbxref(feature_id, old_db, old_accession, new_db, new_accession, organism=organism, sequence=sequence) | Delete a dbxref from a feature
Output:
A standard apollo feature dictionary ({"features": [{...}]}) |
362,909 | def get_service_account_token(request, service_account=):
token_json = get(
request,
.format(service_account))
token_expiry = _helpers.utcnow() + datetime.timedelta(
seconds=token_json[])
return token_json[], token_expiry | 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... |
362,910 | def _updateFrame(self):
mov = self.movie()
if mov:
self.setIcon(QtGui.QIcon(mov.currentPixmap())) | Updates the frame for the given sender. |
362,911 | def write_string(self, string):
buf = bytes(string, )
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. |
362,912 | def _parse_byte_data(self, byte_data):
self.data_type = b.join(unpack(, byte_data[:4])).decode()
self.run = unpack(, byte_data[4:8])[0]
self.udp_sequence = unpack(, byte_data[8:12])[0]
self.timestamp, self.ns_ticks = unpack(, byte_data[12:20])
self.dom_id = unpack(, byte... | Extract the values from byte string. |
362,913 | def _update_record(self, identifier=None, rtype=None, name=None, content=None):
with self._session(self.domain, self.domain_id) as ddata:
if identifier:
dtype, dname, dcontent = self._parse_identifier(identifier, ddata[][])
if dtype and dname a... | 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. |
362,914 | def Expandkey(key, clen):
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(xkey, )
return array(, j) | Internal method supporting encryption and decryption functionality. |
362,915 | async def redis(self) -> aioredis.RedisConnection:
async with self._connection_lock:
if self._redis is None:
self._redis = await aioredis.create_connection((self._host, self._port),
db=self._db, password... | Get Redis connection
This property is awaitable. |
362,916 | def init_array(store, shape, chunks=True, dtype=None, compressor=,
fill_value=None, order=, overwrite=False, path=None,
chunk_store=None, filters=None, object_codec=None):
path = normalize_storage_path(path)
_require_parent_group(path, store=store, chunk_store=chun... | 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... |
362,917 | def mctransp(I,J,K,c,d,M):
model = Model("multi-commodity transportation")
x = {}
for (i,j,k) in c:
x[i,j,k] = model.addVar(vtype="C", name="x(%s,%s,%s)" % (i,j,k), obj=c[i,j,k])
arcs = tuplelist([(i,j,k) for (i,j,k) in x])
for i in I:
for k in K:
... | 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[... |
362,918 | def taf(wxdata: TafData, units: Units) -> TafTrans:
translations = {: []}
for line in wxdata.forecast:
trans = shared(line, units)
trans[] = wind(line.wind_direction, line.wind_speed,
line.wind_gust, unit=units.wind_speed)
trans[] = wind_shear(line.w... | Translate the results of taf.parse
Keys: Forecast, Min-Temp, Max-Temp
Forecast keys: Wind, Visibility, Clouds, Altimeter, Wind-Shear, Turbulance, Icing, Other |
362,919 | def validate_aead_otp(self, public_id, otp, key_handle, aead):
if type(public_id) is not str:
assert()
if type(otp) is not str:
assert()
if type(key_handle) is not int:
assert()
if type(aead) is not str:
assert()
return pyh... | 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... |
362,920 | def with_access_to(self, request, *args, **kwargs):
self.queryset = self.queryset.order_by()
enterprise_id = self.request.query_params.get(, None)
enterprise_slug = self.request.query_params.get(, None)
enterprise_name = self.request.query_params.get(, None)
if enterp... | Returns the list of enterprise customers the user has a specified group permission access to. |
362,921 | def header(text):
print(.join((blue(), cyan(text))))
sys.stdout.flush() | Display an header |
362,922 | def pool(n=None, dummy=False):
if dummy:
from multiprocessing.dummy import Pool
else:
from multiprocessing import Pool
if n is None:
import multiprocessing
n = multiprocessing.cpu_count() - 1
return Pool(n) | create a multiprocessing pool that responds to interrupts. |
362,923 | def Mean(self):
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 |
362,924 | def unapprove(self, **kwargs):
path = % (self.manager.path, self.get_id())
data = {}
server_data = self.manager.gitlab.http_post(path, post_data=data,
**kwargs)
self._update_attrs(server_data) | 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 |
362,925 | def module_entry(yfile):
ytxt = yfile.read()
mp = ModuleParser(ytxt)
mst = mp.statement()
submod = mst.keyword == "submodule"
import_only = True
rev = ""
features = []
includes = []
rec = {}
for sst in mst.substatements:
if not rev and sst.keyword == "revision":
... | Add entry for one file containing YANG module text.
Args:
yfile (file): File containing a YANG module or submodule. |
362,926 | def set_row_name(self, index, name):
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 |
362,927 | def next(self):
if not self.keep_packets:
return self._packet_generator.send(None)
elif self._current_packet >= len(self._packets):
packet = self._packet_generator.send(None)
self._packets += [packet]
return super(FileCapture, self).next_packet() | 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. |
362,928 | def _cleanstarlog(file_in):
file_out=file_in+
f = open(file_in)
lignes = f.readlines()
f.close()
nb = np.array([],dtype=int)
nb = np.concatenate((nb ,[ int(lignes[len(lignes)-1].split()[ 0])]))
nbremove = np.array([],dtype=int)
i=-1
for i in np.arange(len(lign... | 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... |
362,929 | def init_all_objects(self, data, target=None, single_result=True):
if single_result:
return self.init_target_object(target, data)
return list(self.expand_models(target, data)) | Initializes model instances from given data.
Returns single instance if single_result=True. |
362,930 | async def readobj(self):
assert self._parser is not None, "set_parser must be called"
while True:
obj = self._parser.gets()
if obj is not False:
return obj
if self._excepti... | Return a parsed Redis object or an exception
when something wrong happened. |
362,931 | def send_put(self, mri, attribute_name, value):
path = attribute_name + ".value"
typ, value = convert_to_type_tuple_value(serialize_object(value))
if isinstance(typ, tuple):
_, typeid, fields = typ
value = Value(Type(fields, typeid), value)
t... | 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 |
362,932 | def get_activity_ids_by_objective_bank(self, objective_bank_id):
id_list = []
for activity in self.get_activities_by_objective_bank(objective_bank_id):
id_list.append(activity.get_id())
return IdList(id_list) | 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: ... |
362,933 | def violations(self, 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:
self.violations_dict = self.driver.parse_reports(self.reports)
... | Return a list of Violations recorded in `src_path`. |
362,934 | def send(self, use_open_peers=True, queue=True, **kw):
if not use_open_peers:
ip = kw.get()
port = kw.get()
peer = .format(ip, port)
res = arky.rest.POST.peer.transactions(peer=peer, transactions=[self.tx.tx])
else:
res = arky.core.s... | 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 |
362,935 | def frequency_app(parser, cmd, args):
parser.add_argument(, help=, nargs=)
args = parser.parse_args(args)
data = frequency(six.iterbytes(pwnypack.main.binary_value_or_stdin(args.value)))
return .join(
% (key, chr(key), value)
if key >= 32 and chr(key) in string.printable else
... | perform frequency analysis on a value. |
362,936 | def subjects(self):
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 |
362,937 | def __add_location(self, type, *args):
if type == "directory":
location = umbra.ui.common.store_last_browsed_path((QFileDialog.getExistingDirectory(self,
"Add 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: \* |
362,938 | def get_settings(self):
config = self._load_config_user()
if self.name in config:
return config[self.name] | get all settings for a client, if defined in config. |
362,939 | def _iterslice(self, slice):
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))
else:
rows = zip... | Yield records from a slice index. |
362,940 | def rehash(path, algo=, blocksize=1 << 20):
h = hashlib.new(algo)
length = 0
with open(path, ) as f:
block = f.read(blocksize)
while block:
length += len(block)
h.update(block)
block = f.read(blocksize)
digest = + urlsafe_b64encode(
h.dig... | Return (hash, length) for path using hashlib.new(algo) |
362,941 | def update_local(self):
self.cpu_stats_old = cpu_stats
return stats | Update CPU stats using psutil. |
362,942 | def params_as_tensors(method):
@functools.wraps(method)
def tensor_mode_wrapper(obj, *args, **kwargs):
if not isinstance(obj, Parameterized):
raise GPflowError(
)
prev_value = _params_as_tensors_enter(obj, True)
try:
result = method(obj, *args... | 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. |
362,943 | def likes_count(obj):
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 }} |
362,944 | def _at_include(self, calculator, rule, scope, block):
caller_namespace = rule.namespace
caller_calculator = self._make_calculator(caller_namespace)
funct, caller_argspec = self._get_funct_def(rule, caller_calculator, block.argument)
mixin = ca... | Implements @include, for @mixins |
362,945 | def classpath(self, targets, classpath_prefix=None, classpath_product=None, exclude_scopes=None,
include_scopes=None):
include_scopes = Scopes.JVM_RUNTIME_SCOPES if include_scopes is None else include_scopes
classpath_product = classpath_product or self.context.products.get_data()
closu... | 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... |
362,946 | def _jsonfileconstructor(self, filename=None, filepath=None, logger=None):
if filepath:
path = filepath
else:
tc_path = os.path.abspath(os.path.join(inspect.getfile(self.bench.__class__),
os.pardir))
path = o... | Constructor method for the JsonFile object.
:param filename: Name of the file
:param filepath: Path to the file
:param logger: Optional logger.
:return: JsonFile |
362,947 | def value(self):
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 self.p | Returns the current value (adjusted for the time decay)
:rtype: float |
362,948 | def go_offline(connected=None):
from .auth import get_config_file
if connected is None:
try:
connected=True if get_config_file()[] is None else get_config_file()[]
except:
connected=True
if run_from_ipython():
try:
py_offline.init_notebook_mod... | 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 |
362,949 | def _lock_renewer(lockref, interval, stop):
log = getLogger("%s.lock_refresher" % __name__)
while not stop.wait(timeout=interval):
log.debug("Refreshing lock")
lock = lockref()
if lock is None:
log.debug("The lock no longer exists, "
... | Renew the lock key in redis every `interval` seconds for as long
as `self._lock_renewal_thread.should_exit` is False. |
362,950 | def run(self):
lammps_cmd = self.lammps_bin + [, self.input_filename]
print("Running: {}".format(" ".join(lammps_cmd)))
p = Popen(lammps_cmd, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate()
return stdout, stderr | Write the input/data files and run LAMMPS. |
362,951 | def _discover_masters(self):
if self.opts[] == DEFAULT_MINION_OPTS[] and self.opts[] is not False:
master_discovery_client = salt.utils.ssdp.SSDPDiscoveryClient()
masters = {}
for att in range(self.opts[].get(, 3)):
try:
att += 1
... | Discover master(s) and decide where to connect, if SSDP is around.
This modifies the configuration on the fly.
:return: |
362,952 | def remove_index(self, field=None, value=None):
if not field and not value:
self.indexes.clear()
elif field and not value:
for index in [x for x in self.indexes if x[0] == field]:
self.indexes.remove(index)
elif field and value:
self.i... | 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... |
362,953 | def is_password_valid(password):
pattern = re.compile(r"^.{4,75}$")
return bool(pattern.match(password)) | Check if a password is valid |
362,954 | def reshape(x,input_dim):
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 |
362,955 | def chdir(path: str) -> Iterator[None]:
curdir = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(curdir) | Context manager for changing dir and restoring previous workdir after exit. |
362,956 | def parse_delete(prs, conn):
prs_delete = prs.add_parser(
, help=)
set_option(prs_delete, )
conn_options(prs_delete, conn)
prs_delete.set_defaults(func=delete) | Delete record.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information |
362,957 | def reload(self, client=None):
client = self._require_client(client)
resp = client._connection.api_request(method="GET", path=self.path)
self._set_properties(api_response=resp) | 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`
... |
362,958 | def schedule_in(self, job, timedelta):
now = long(self._now() * 1e6)
when = now + timedelta.total_seconds() * 1e6
self.schedule(job, when) | Schedule job to run at datetime.timedelta from now. |
362,959 | def stop_process(self):
if self.read_thread is not None:
self.logger.debug("stop_process::readThread.stop()-in")
self.read_thread.stop()
self.logger.debug("stop_process::readThread.stop()-out")
returncode = None
if self.proc:
self.logger.d... | 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. |
362,960 | def tracer(object):
@functools.wraps(object)
@functools.partial(validate_tracer, object)
def tracer_wrapper(*args, **kwargs):
code = object.func_code
args_count = code.co_argcount
args_names = code.co_varnames[:args_count]
function_defaults = object.func_defau... | | Traces execution.
| Any method / definition decorated will have it's execution traced.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object |
362,961 | def update_dimension(model, input_dimension):
if not(_HAS_SKLEARN):
raise RuntimeError()
_sklearn_util.check_fitted(model, lambda m: hasattr(m, ))
_sklearn_util.check_fitted(model, lambda m: hasattr(m, ))
if model.categorical_features == :
return len(model.active_features_)
el... | Given a model that takes an array of dimension input_dimension, returns
the output dimension. |
362,962 | def driver(self, sim):
r = sim.read
if self.actualData is NOP and self.data:
self.actualData = self.data.popleft()
doSend = self.actualData is not NOP
if self.actualData is not self._lastWritten:
if doSend:
self.doWrit... | Push data to interface
set vld high and wait on rd in high then pass new data |
362,963 | def add_suffix(self, suffix):
f = functools.partial(.format, suffix=suffix)
mapper = {self._info_axis_name: f}
return self.rename(**mapper) | 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
... |
362,964 | def cd(self, path=None):
if path is None:
return lock_and_call(
lambda: self._impl.cd(),
self._lock
)
else:
return lock_and_call(
lambda: self._impl.cd(path),
self._lock
) | 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. |
362,965 | def _Close(self):
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. |
362,966 | def create_schema(self):
execute = self.cursor.execute
try:
return execute()
except self.psycopg2.ProgrammingError:
pass
self.db.rollback()
execute()
self.db.commit() | Create all necessary tables |
362,967 | def create_reference_server_flask_app(cfg):
app = Flask(__name__)
Flask.secret_key = "SECRET_HERE"
app.debug = cfg.debug
client_prefixes = dict()
for api_version in cfg.api_versions:
handler_config = Config(cfg)
handler_config.api_version = api_version
handler_... | Create referece server Flask application with one or more IIIF handlers. |
362,968 | def use_comparative_bin_view(self):
self._bin_view = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_bin_view()
except AttributeError:
pass | Pass through to provider ResourceBinSession.use_comparative_bin_view |
362,969 | def func(self, node):
_, 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 |
362,970 | def list_all(self):
if isinstance(self.minion.opts[], six.string_types):
log.debug(, self.opts[])
try:
with salt.utils.files.fopen(self.opts[]) as fp_:
react_map = salt.utils.yaml.safe_load(fp_)
except (OSError, IOError):
... | Return a list of the reactors |
362,971 | def shift_rows(state):
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][1], state[3][2], state[0][3],
state[2][0], state[3][1], state[0][2], state[1][3],
state[3][0], state[0][1], state[1][2], state[2][3]
... | Transformation in the Cipher that processes the State by cyclically shifting
the last three rows of the State by different offsets. |
362,972 | def Missenard(T, P, Tc, Pc, kl):
r
Tr = T/Tc
Pr = P/Pc
Q = float(Qfunc_Missenard(Pr, Tr))
return kl*(1. + Q*Pr**0.7) | 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... |
362,973 | def max_id_length(self):
if config().identifiers() == "text":
return max_id_length(len(self._todos))
else:
try:
return math.ceil(math.log(len(self._todos), 10))
except ValueError:
return 0 | Returns the maximum length of a todo ID, used for formatting purposes. |
362,974 | def __set_data(self, data):
ent = self.__entity_ref()
self.set_state_data(ent, 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. |
362,975 | def reload(self, index):
finfo = self.data[index]
txt, finfo.encoding = encoding.read(finfo.filename)
finfo.lastmodified = QFileInfo(finfo.filename).lastModified()
position = finfo.editor.get_position()
finfo.editor.set_text(txt)
finfo.editor.document().se... | Reload file from disk |
362,976 | def status(self):
if self.request_list.conflict:
return SolverStatus.failed
if self.callback_return == SolverCallbackReturn.fail:
return SolverStatus.failed
st = self.phase_stack[-1].status
if st == SolverStatus.cyclic:
... | Return the current status of the solve.
Returns:
SolverStatus: Enum representation of the state of the solver. |
362,977 | def get_next(self,oid):
try:
self.lock.acquire()
try:
while len(oid) > 0 and oid[-2:] == ".0" and oid not in self.data:
oid = oid[:-2];
return self.get(self.data_idx[self.data_idx.index(oid)+1])
except ValueError:
for real_oid in self.data_idx:
if real_oid.startswith(oid):... | Return snmp value for the next OID. |
362,978 | def topoplot(values, locations, axes=None, offset=(0, 0), plot_locations=True,
plot_head=True, **kwargs):
topo = Topoplot(**kwargs)
topo.set_locations(locations)
topo.set_values(values)
topo.create_map()
topo.plot_map(axes=axes, offset=offset)
if plot_locations:
topo.pl... | Wrapper function for :class:`Topoplot. |
362,979 | def groupby(self, group, squeeze: bool = True):
return self._groupby_cls(self, group, squeeze=squeeze) | 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 ... |
362,980 | def _build_connstr(host, port, bucket):
hostlist = []
if isinstance(host, (tuple, list)):
for curhost in host:
if isinstance(curhost, (list, tuple)):
hostlist.append(_fmthost(*curhost))
else:
hostlist.append(curhost)
else:
hostlist... | Converts a 1.x host:port specification to a connection string |
362,981 | def _screen(self, s, newline=False):
if self.verbose:
if newline:
print(s)
else:
print(s, end=) | Print something on screen when self.verbose == True |
362,982 | def freefn(self, key, free_fn):
return c_void_p(lib.zhash_freefn(self._as_parameter_, 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_fn.
Returns the item, or NULL if there is no such it... |
362,983 | def which_roles_can(self, name):
targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first()
return [{: group.role} for group in targetPermissionRecords.groups] | Which role can SendMail? |
362,984 | def ping(self, reconnect=True):
if self._sock is None:
if reconnect:
self.connect()
reconnect = False
else:
raise err.Error("Already closed")
try:
self._execute_command(COMMAND.COM_PING, "")
self._re... | Check if the server is alive.
:param reconnect: If the connection is closed, reconnect.
:raise Error: If the connection is closed and reconnect=False. |
362,985 | def render(self, route=None):
if route is None:
route =
with self.test_client() as c:
response = c.get(route, follow_redirects=True)
encoding = response.charset
return response.data.decode(encoding) | Renders the application and returns the HTML unicode that would
normally appear when visiting in the browser. |
362,986 | def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
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]
a = _twos_comp_conditional(A, aneg)
b = _twos_comp_conditional(... | Same as tree_multiplier, but uses two's-complement signed integers |
362,987 | def calc_crc(raw_mac):
result = 0x00
for b in struct.unpack("B" * 6, raw_mac):
result ^= b
for _ in range(8):
lsb = result & 1
result >>= 1
if lsb != 0:
result ^= 0x8c
return result | This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00. |
362,988 | def progress(status_code):
lookup = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: }
for key, value in lookup.items():
if str(status_code) == key:
return value | Translate PROGRESS status codes from GnuPG to messages. |
362,989 | def merge_objects(self, mujoco_objects):
self.mujoco_objects = mujoco_objects
self.objects = {}
self.max_horizontal_radius = 0
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
obj = obj_mjcf.get_collision(name=ob... | Adds physical objects to the MJCF model. |
362,990 | def isInstalledBuild(self):
sentinelFile = os.path.join(self.getEngineRoot(), , , )
return os.path.exists(sentinelFile) | Determines if the Engine is an Installed Build |
362,991 | def setup_logger():
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
return logger | setup basic logger |
362,992 | def update(self):
with open(os.path.join(self.config_dir, CONFIG_FILE_NAME), ) as config_file:
self.config.write(config_file) | updates the configuration settings |
362,993 | def dict_fun(data, function):
return dict((k, function(v)) for k, v in list(data.items())) | 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
... |
362,994 | def update(self, key, value):
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 |
362,995 | 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 = [,] if self._is_lm else [,]
items = []
for i, (x,y) in enumerate(zip(xs,ys)):
... | Show the `xs` (inputs) and `ys` (targets). `max_len` is the maximum number of tokens displayed. |
362,996 | def cleanup_docstamp_output(output_dir=):
suffixes = [, , ]
files = [f for suf in suffixes for f in glob(os.path.join(output_dir, .format(suf)))]
[os.remove(file) for file in files] | Remove the 'tmp*.aux', 'tmp*.out' and 'tmp*.log' files in `output_dir`.
:param output_dir: |
362,997 | def main():
args = sys.argv
if "-h" in args:
print(main.__doc__)
sys.exit()
else:
info = [[, False, ], [, False, ], [, False, ],
[, False, False], [, False, 1], [, False, 1],
[, False, True], [, False, ], [, False, 0],
[, False, ],... | 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... |
362,998 | def _inject():
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. |
362,999 | def load_ipa_data():
ipa_signs = []
unicode_to_ipa = {}
ipa_to_unicode = {}
max_key_length = 0
for line in load_data_file(
file_path=u"ipa.dat",
file_path_is_relative=True,
line_format=u"sU"
):
i_desc, i_unicode_keys = line
name = re.sub(r" [... | 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.