Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
385,300 | def diff_ft(self, xt, yt):
a, b = self.a, self.b
ex = np.exp(a + np.matmul(b, xt))
grad = (-np.sum(ex[:, np.newaxis] * b, axis=0)
+ np.sum(yt.flatten()[:, np.newaxis] * b, axis=0))
hess = np.zeros((self.dx, self.dx))
for k in range(self.dy):
... | First and second derivatives (wrt x_t) of log-density of Y_t|X_t=xt |
385,301 | def direct_normal_radiation(self, value=9999.0):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
.format(value))
if value < 0.0:
raise ValueE... | Corresponds to IDD Field `direct_normal_radiation`
Args:
value (float): value for IDD Field `direct_normal_radiation`
Unit: Wh/m2
value >= 0.0
Missing value: 9999.0
if `value` is None it will not be checked against the
... |
385,302 | def update(self, catalog=None, dependencies=None, allow_overwrite=False):
if catalog:
self._providers.update(catalog, allow_overwrite=allow_overwrite)
if dependencies:
self._dependencies.update(dependencies) | Convenience method to update this Di instance with the specified contents.
:param catalog: ICatalog supporting class or mapping
:type catalog: ICatalog or collections.Mapping
:param dependencies: Mapping of dependencies
:type dependencies: collections.Mapping
:param allow_overwr... |
385,303 | def set_password(name, password):
*
cmd = "dscl . -passwd /Users/{0} ".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if in exc.strerror:
raise CommandExecutionError(.format(name))
raise CommandExecut... | Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful... |
385,304 | def _skw_matches_comparator(kw0, kw1):
def compare(a, b):
return (a > b) - (a < b)
list_comparison = compare(len(kw1[1][0]), len(kw0[1][0]))
if list_comparison:
return list_comparison
if kw0[0].isComposite() and kw1[0].isComposite():
component_avg0 = sum(kw0[1][1]) / len(k... | Compare 2 single keywords objects.
First by the number of their spans (ie. how many times they were found),
if it is equal it compares them by lenghts of their labels. |
385,305 | def setDeclaration(self, declaration):
assert isinstance(declaration.proxy, ProxyAbstractItemView), \
"The model declaration must be a QtAbstractItemView subclass. " \
"Got {]".format(declaration)
self.declaration = declaration | Set the declaration this model will use for rendering
the the headers. |
385,306 | def break_array(a, threshold=numpy.pi, other=None):
assert len(a.shape) == 1, "Only 1D arrays supported"
if other is not None and a.shape != other.shape:
raise ValueError("arrays must be of identical shape")
breaks = numpy.where(numpy.abs(numpy.diff(a)) >= threshold)[0]
breaks +... | Create a array which masks jumps >= threshold.
Extra points are inserted between two subsequent values whose
absolute difference differs by more than threshold (default is
pi).
Other can be a secondary array which is also masked according to
*a*.
Returns (*a_masked*, *other_masked*) (where *o... |
385,307 | def can_ignore_error(self, reqhnd=None):
value = sys.exc_info()[1]
try:
if isinstance(value, BrokenPipeError) or \
isinstance(value, ConnectionResetError):
return True
except NameError:
pass
if not self.done:
... | Tests if the error is worth reporting. |
385,308 | def image_search(auth=None, **kwargs):
**
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.search_images(**kwargs) | Search for images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_search name=image1
salt '*' glanceng.image_search |
385,309 | def aghmean(nums):
m_a = amean(nums)
m_g = gmean(nums)
m_h = hmean(nums)
if math.isnan(m_a) or math.isnan(m_g) or math.isnan(m_h):
return float()
while round(m_a, 12) != round(m_g, 12) and round(m_g, 12) != round(
m_h, 12
):
m_a, m_g, m_h = (
(m_a + m_g +... | Return arithmetic-geometric-harmonic mean.
Iterates over arithmetic, geometric, & harmonic means until they
converge to a single value (rounded to 12 digits), following the
method described in :cite:`Raissouli:2009`.
Parameters
----------
nums : list
A series of numbers
Returns
... |
385,310 | def bulk_docs(self, docs):
url = .join((self.database_url, ))
data = {: docs}
headers = {: }
resp = self.r_session.post(
url,
data=json.dumps(data, cls=self.client.encoder),
headers=headers
)
resp.raise_for_status()
ret... | Performs multiple document inserts and/or updates through a single
request. Each document must either be or extend a dict as
is the case with Document and DesignDocument objects. A document
must contain the ``_id`` and ``_rev`` fields if the document
is meant to be updated.
:p... |
385,311 | def _compute_mean_on_rock(self, C, mag, rrup, F, HW):
f1 = self._compute_f1(C, mag, rrup)
f3 = self._compute_f3(C, mag)
f4 = self._compute_f4(C, mag, rrup)
return f1 + F * f3 + HW * f4 | Compute mean value on rock (that is eq.1, page 105 with S = 0) |
385,312 | def setdict(self, D):
self.D = np.asarray(D, dtype=self.dtype)
self.DTS = self.D.T.dot(self.S)
self.lu, self.piv = sl.cho_factor(self.D, self.rho)
self.lu = np.asarray(self.lu, dtype=self.dtype) | Set dictionary array. |
385,313 | def _read_para_notification(self, code, cbit, clen, *, desc, length, version):
_resv = self._read_fileng(2)
_code = self._read_unpack(2)
_data = self._read_fileng(2)
_type = _NOTIFICATION_TYPE.get(_code)
if _type is None:
if 1 <= _code <= 50:
... | Read HIP NOTIFICATION parameter.
Structure of HIP NOTIFICATION parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-... |
385,314 | def Close(self):
if self.connection is not None:
try:
self.connection.commit()
self.connection.close()
self.connection = None
except Exception, e:
pass | Commits and closes the current connection
@author: Nick Verbeck
@since: 5/12/2008 |
385,315 | def rotateTo(self, angle):
self._transmogrophy(angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV) | rotates the image to a given angle
Parameters:
| angle - the angle that you want the image rotated to.
| Positive numbers are clockwise, negative numbers are counter-clockwise |
385,316 | def remove_instance(self, instance):
if instance.is_external:
logger.info("Request external process to stop for %s", instance.name)
instance.stop_process()
logger.info("External process stopped.")
instance.clear_queues(self.daemon.sync_manager)
... | Request to cleanly remove the given instance.
If instance is external also shutdown it cleanly
:param instance: instance to remove
:type instance: object
:return: None |
385,317 | def absent(name, driver=None):
ret = {: name,
: {},
: False,
: }
volume = _find_volume(name)
if not volume:
ret[] = True
ret[] = {0}\.format(name)
return ret
try:
ret[][] = __salt__[](name)
ret[] = True
except Exception ... | Ensure that a volume is absent.
.. versionadded:: 2015.8.4
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_absent** to **docker_volume.absent**
name
Name of the volume
Usage Examples:
.. code-block:: yaml
volume_foo:
docker_volume.absen... |
385,318 | def _get_stream_schema(fields):
stream_schema = topology_pb2.StreamSchema()
for field in fields:
key = stream_schema.keys.add()
key.key = field
key.type = topology_pb2.Type.Value("OBJECT")
return stream_schema | Returns a StreamSchema protobuf message |
385,319 | def get_arctic_version(self, symbol, as_of=None):
return self._read_metadata(symbol, as_of=as_of).get(, 0) | Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was a... |
385,320 | def validateOpfJsonValue(value, opfJsonSchemaFilename):
jsonSchemaPath = os.path.join(os.path.dirname(__file__),
"jsonschema",
opfJsonSchemaFilename)
jsonhelpers.validate(value, schemaPath=jsonSchemaPath)
return | Validate a python object against an OPF json schema file
:param value: target python object to validate (typically a dictionary)
:param opfJsonSchemaFilename: (string) OPF json schema filename containing the
json schema object. (e.g., opfTaskControlSchema.json)
:raises: jsonhelpers.ValidationError when ... |
385,321 | def validate_refresh_token(self, refresh_token, client, request,
*args, **kwargs):
token = self._tokengetter(refresh_token=refresh_token)
if token and token.client_id == client.client_id:
request.client_id = token.client_id
r... | Ensure the token is valid and belongs to the client
This method is used by the authorization code grant indirectly by
issuing refresh tokens, resource owner password credentials grant
(also indirectly) and the refresh token grant. |
385,322 | def buggy_div(request):
a = float(request.GET.get(, ))
b = float(request.GET.get(, ))
return JsonResponse({: a / b}) | A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or
either a or b are not float.
:param request: request object
:return: |
385,323 | def _check_suffix(self, w_string, access_string, index):
prefix_as = self._membership_query(access_string)
full_as = self._membership_query(access_string + w_string[index:])
prefix_w = self._membership_query(w_string[:index])
full_w = self._membership_query(w_string)
l... | Checks if access string suffix matches with the examined string suffix
Args:
w_string (str): The examined string to be consumed
access_string (str): The access string for the state
index (int): The index value for selecting the prefix of w
Returns:
bool: A... |
385,324 | def set_brightness(host, did, value, token=None):
urllib3.disable_warnings()
if token:
scheme = "https"
if not token:
scheme = "http"
token = "1234567890"
url = (
scheme + + host + + token + + did + + str(
value) + )
response = requests.get(url, v... | Set brightness of a bulb or fixture. |
385,325 | def cumsum(self, axis=0, *args, **kwargs):
nv.validate_cumsum(args, kwargs)
if axis is not None:
self._get_axis_number(axis)
new_array = self.values.cumsum()
return self._constructor(
new_array, index=self.index,
sparse_index=new_ar... | Cumulative sum of non-NA/null values.
When performing the cumulative summation, any non-NA/null values will
be skipped. The resulting SparseSeries will preserve the locations of
NaN values, but the fill value will be `np.nan` regardless.
Parameters
----------
axis : {0}... |
385,326 | def fdf(self, x):
x = self._flatten(x)
n = 1
if hasattr(x, "__len__"):
n = len(x)
if self._dtype == 0:
retval = _functional._fdf(self, x)
else:
retval = _functional._fdfc(self, x)
if len(retval) == n:
return numpy.a... | Calculate the value of the functional for the specified arguments,
and the derivatives with respect to the parameters (taking any
specified mask into account).
:param x: the value(s) to evaluate at |
385,327 | def _CheckCacheFileForMatch(self, cache_filename, scopes):
creds = {
: sorted(list(scopes)) if scopes else None,
: self.__service_account_name,
}
cache_file = _MultiProcessCacheFile(cache_filename)
try:
cached_creds_str = cache_file.LockedRe... | Checks the cache file to see if it matches the given credentials.
Args:
cache_filename: Cache filename to check.
scopes: Scopes for the desired credentials.
Returns:
List of scopes (if cache matches) or None. |
385,328 | def get_ip_addr(self) -> str:
output, _ = self._execute(
, self.device_sn, , , , , , , )
ip_addr = re.findall(
r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", output)
if not ip_addr:
raise ConnectionEr... | Show IP Address. |
385,329 | def get_guest_connection_status(self, userid):
rd = .join((, userid, ))
results = self._request(rd)
if results[] == 1:
return True
else:
return False | Get guest vm connection status. |
385,330 | def load_handgeometry():
dataset_path = _load()
df = _load_csv(dataset_path, )
X = _load_images(os.path.join(dataset_path, ), df.image)
y = df.target.values
return Dataset(load_handgeometry.__doc__, X, y, r2_score) | Hand Geometry Dataset.
The data of this dataset is a 3d numpy array vector with shape (224, 224, 3)
containing 112 224x224 RGB photos of hands, and the target is a 1d numpy
float array containing the width of the wrist in centimeters. |
385,331 | def is_zone_running(self, zone):
self.update_controller_info()
if self.running is None or not self.running:
return False
if int(self.running[0][]) == zone:
return True
return False | Returns the state of the specified zone.
:param zone: The zone to check.
:type zone: int
:returns: Returns True if the zone is currently running, otherwise
returns False if the zone is not running.
:rtype: boolean |
385,332 | def Disconnect(self):
device_path = self.path
if device_path not in mockobject.objects:
raise dbus.exceptions.DBusException(,
name=)
device = mockobject.objects[device_path]
try:
device.props[AUDIO_IFACE][] = dbus.String("disconnected",... | Disconnect a device |
385,333 | def is_build_dir(self, folder_name):
url = % urljoin(self.base_url, self.monthly_build_list_regex, folder_name)
if self.application in APPLICATIONS_MULTI_LOCALE \
and self.locale != :
url = % urljoin(url, self.locale)
parser = self._crea... | Return whether or not the given dir contains a build. |
385,334 | def log(self, logger=None, label=None, eager=False):
if self.closed():
raise ValueError("Attempt to call log() on a closed Queryable.")
if logger is None:
return self
if label is None:
label = repr(self)
if eager:
return self._c... | Log query result consumption details to a logger.
Args:
logger: Any object which supports a debug() method which accepts a
str, such as a Python standard library logger object from the
logging module. If logger is not provided or is None, this
method... |
385,335 | def aesCCM(key, key_handle, nonce, data, decrypt=False):
if decrypt:
(data, saved_mac) = _split_data(data, len(data) - pyhsm.defines.YSM_AEAD_MAC_SIZE)
nonce = pyhsm.util.input_validate_nonce(nonce, pad = True)
mac = _cbc_mac(key, key_handle, nonce, len(data))
counter = _ctr_counter(key_h... | Function implementing YubiHSM AEAD encrypt/decrypt in software. |
385,336 | def _write_single_sample(self, sample):
bytes = sample.extras.get("responseHeadersSize", 0) + 2 + sample.extras.get("responseBodySize", 0)
message = sample.error_msg
if not message:
message = sample.extras.get("responseMessage")
if not message:
for sampl... | :type sample: Sample |
385,337 | def get_uids(self, filename=None):
self._update()
return [Abook._gen_uid(self._book[entry]) for entry in self._book.sections()] | Return a list of UIDs
filename -- unused, for API compatibility only |
385,338 | async def _get_smallest_env(self):
async def slave_task(mgr_addr):
r_manager = await self.env.connect(mgr_addr, timeout=TIMEOUT)
ret = await r_manager.get_agents(addr=True)
return mgr_addr, len(ret)
sizes = await create_tasks(slave_task, self.addrs, flatten=... | Get address of the slave environment manager with the smallest
number of agents. |
385,339 | def debug_sync(self, conn_id, cmd_name, cmd_args, progress_callback):
done = threading.Event()
result = {}
def _debug_done(conn_id, adapter_id, success, retval, reason):
result[] = success
result[] = reason
result[] = retval
done.set()
... | Asynchronously complete a named debug command.
The command name and arguments are passed to the underlying device adapter
and interpreted there. If the command is long running, progress_callback
may be used to provide status updates. Callback is called when the command
has finished.
... |
385,340 | def print_token(self, token_node_index):
err_msg = "The given node is not a token node."
assert isinstance(self.nodes[token_node_index], TokenNode), err_msg
onset = self.nodes[token_node_index].onset
offset = self.nodes[token_node_index].offset
return self.text[onset:off... | returns the string representation of a token. |
385,341 | def resolve_data_objects(objects, project=None, folder=None, batchsize=1000):
if not isinstance(batchsize, int) or batchsize <= 0 or batchsize > 1000:
raise ValueError("batchsize for resolve_data_objects must be a positive integer not exceeding 1000")
args = {}
if project:
args.update({... | :param objects: Data object specifications, each with fields "name"
(required), "folder", and "project"
:type objects: list of dictionaries
:param project: ID of project context; a data object's project defaults
to this if not specified for that object
:type project: ... |
385,342 | def lookup(self, path, is_committed=True, with_proof=False) -> (str, int):
assert path is not None
head_hash = self.state.committedHeadHash if is_committed else self.state.headHash
encoded, proof = self._get_value_from_state(path, head_hash, with_proof=with_proof)
if encoded:
... | Queries state for data on specified path
:param path: path to data
:param is_committed: queries the committed state root if True else the uncommitted root
:param with_proof: creates proof if True
:return: data |
385,343 | def download_file_with_progress_bar(url):
request = requests.get(url, stream=True)
if request.status_code == 404:
msg = (
.format(url))
logger.error(msg)
sys.exit()
total_size = int(request.headers["Content-Length"])
chunk_size = 1024
bars = int(total_size... | Downloads a file from the given url, displays
a progress bar.
Returns a io.BytesIO object |
385,344 | def _correct_build_location(self):
if self.source_dir is not None:
return
assert self.req is not None
assert self._temp_build_dir.path
assert (self._ideal_build_dir is not None and
self._ideal_build_dir.path)
old_location = self._te... | Move self._temp_build_dir to self._ideal_build_dir/self.req.name
For some requirements (e.g. a path to a directory), the name of the
package is not available until we run egg_info, so the build_location
will return a temporary directory and store the _ideal_build_dir.
This is only call... |
385,345 | def fav_songs(self):
if self._fav_songs is None:
songs_data = self._api.user_favorite_songs(self.identifier)
self._fav_songs = []
if not songs_data:
return
for song_data in songs_data:
song = _deserialize(song_data, NestedS... | FIXME: 支持获取所有的收藏歌曲 |
385,346 | def extension_counts(container=None, file_list=None, return_counts=True):
if file_list is None:
file_list = get_container_contents(container, split_delim=)[]
extensions = dict()
for item in file_list:
filename,ext = os.path.splitext(item)
if ext == :
if return_count... | extension counts will return a dictionary with counts of file extensions for
an image.
:param container: if provided, will use container as image. Can also provide
:param image_package: if provided, can be used instead of container
:param file_list: the complete list of files
:param return_counts: r... |
385,347 | def connections_of(self, target):
return gen.chain( ((r,i) for i in self.find(target,r)) for r in self.relations_of(target) ) | generate tuples containing (relation, object_that_applies) |
385,348 | def fast_forward(self, start_dt):
if self.from_stdin:
return
else:
max_mark = self.filesize
step_size = max_mark
self.filehandle.seek(0)
le = self.next()
if le.datetime and le.dateti... | Fast-forward file to given start_dt datetime obj using binary search.
Only fast for files. Streams need to be forwarded manually, and it will
miss the first line that would otherwise match (as it consumes the log
line). |
385,349 | def map_ids(queries,frm=,to=,
organism_taxid=9606,test=False):
url =
params = {
:frm,
:to,
:,
:organism_taxid,
:.join(queries),
}
response = requests.get(url, params=params)
if test:
print(response.url)
if response.ok:
df=pd.read_table(re... | https://www.uniprot.org/help/api_idmapping |
385,350 | def upload_file(self, metadata, filename, signer=None, sign_password=None,
filetype=, pyversion=, keystore=None):
self.check_credentials()
if not os.path.exists(filename):
raise DistlibException( % filename)
metadata.validate()
d = metadata.todict... | Upload a release file to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the file to be uploaded.
:param filename: The pathname of the file to be uploaded.
:param signer: The identifier of the signer of the file.
... |
385,351 | def create(cls, csr, duration, package, altnames=None, dcv_method=None):
params = {: csr, : package, : duration}
if altnames:
params[] = altnames
if dcv_method:
params[] = dcv_method
try:
result = cls.call(, params)
except UsageError:... | Create a new certificate. |
385,352 | def create_tablefn_map(fns, pqdb, poolnames):
poolmap = {name: pid for (name, pid) in pqdb.get_all_poolnames()}
pqdb.store_table_files([(poolmap[pool], os.path.basename(fn))
for fn, pool in zip(fns, poolnames)])
return pqdb.get_tablefn_map() | Stores protein/peptide table names in DB, returns a map with their
respective DB IDs |
385,353 | def drag_sphere(Re, Method=None, AvailableMethods=False):
rs solution.
* If 0.01 <= Re < 0.1, linearly combine with StokesBaratiStokesBaratiBarati_high
def list_methods():
methods = []
for key, (func, Re_min, Re_max) in drag_sphere_correlations.items():
if (Re_min is None or... | r'''This function handles calculation of drag coefficient on spheres.
Twenty methods are available, all requiring only the Reynolds number of the
sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will
be automatically selected if none is specified. The full list of correlations
valid... |
385,354 | def WriteHashBlobReferences(self, references_by_hash, cursor):
values = []
for hash_id, blob_refs in iteritems(references_by_hash):
refs = rdf_objects.BlobReferences(items=blob_refs).SerializeToString()
values.append({
"hash_id": hash_id.AsBytes(),
"blob_references": refs,
... | Writes blob references for a given set of hashes. |
385,355 | def fit(self, X, y):
self._data = X
self._classes = np.unique(y)
self._labels = y
self._is_fitted = True | Fit the model using X as training data and y as target values |
385,356 | def _variable(lexer):
names = _names(lexer)
tok = next(lexer)
if isinstance(tok, LBRACK):
indices = _indices(lexer)
_expect_token(lexer, {RBRACK})
else:
lexer.unpop_token(tok)
indices = tuple()
return (, names, indices) | Return a variable expression. |
385,357 | def splitStis(stisfile, sci_count):
newfiles = []
toclose = False
if isinstance(stisfile, str):
f = fits.open(stisfile)
toclose = True
else:
f = stisfile
hdu0 = f[0].copy()
stisfilename = stisfile.filename()
for count in range(1,sci_count+1):
fitsobj = ... | Split a STIS association file into multiple imset MEF files.
Split the corresponding spt file if present into single spt files.
If an spt file can't be split or is missing a Warning is printed.
Returns
-------
names: list
a list with the names of the new flt files. |
385,358 | def set_lines( lines, target_level, indent_string=" ", indent_empty_lines=False ):
first_non_empty_line_index = _get_first_non_empty_line_index( lines )
first_line_original_level = get_line_level( lines[first_non_empty_line_index], indent_string )
for i in range(first_non_empty_line_index, ... | Sets indentation for the given set of :lines:. |
385,359 | def mutualInformation(sp, activeColumnsCurrentEpoch, column_1, column_2):
i, j = column_1, column_2
batchSize = activeColumnsCurrentEpoch.shape[0]
ci, cj, cij = 0., 0., dict([((0,0),0.), ((1,0),0.), ((0,1),0.), ((1,1),0.)])
for t in range(batchSize):
ai = activeColumnsCurrentEpoch[t, i]
... | Computes the mutual information of the binary variables that represent
the activation probabilities of two columns. The mutual information I(X,Y)
of two random variables is given by
\[
I (X,Y) = \sum_{x,y} p(x,y) log( p(x,y) / ( p(x) p(y) ) ).
\]
(https://en.wikipedia.org/wiki/Mutual_information) |
385,360 | def connect(self, hostname=None, port=None):
if hostname is not None:
self.host = hostname
conn = self._connect_hook(self.host, port)
self.os_guesser.protocol_info(self.get_remote_version())
self.auto_driver = driver_map[self.guess_os()]
if self.get_banner():... | Opens the connection to the remote host or IP address.
:type hostname: string
:param hostname: The remote host or IP address.
:type port: int
:param port: The remote TCP port number. |
385,361 | def guess_settings(self, major, minor):
version = major, minor
if self.vbr_method == 2:
if version in ((3, 90), (3, 91), (3, 92)) and self.encoding_flags:
if self.bitrate < 255:
return u"--alt-preset %d" % self.bitrate
else:
... | Gives a guess about the encoder settings used. Returns an empty
string if unknown.
The guess is mostly correct in case the file was encoded with
the default options (-V --preset --alt-preset --abr -b etc) and no
other fancy options.
Args:
major (int)
min... |
385,362 | def dump(new_data):
*{: }
if not isinstance(new_data, dict):
if isinstance(ast.literal_eval(new_data), dict):
new_data = ast.literal_eval(new_data)
else:
return False
try:
datastore_path = os.path.join(__opts__[], )
with salt.utils.files.fopen(datasto... | Replace the entire datastore with a passed data structure
CLI Example:
.. code-block:: bash
salt '*' data.dump '{'eggs': 'spam'}' |
385,363 | def maps_get_default_rules_output_rules_action(self, **kwargs):
config = ET.Element("config")
maps_get_default_rules = ET.Element("maps_get_default_rules")
config = maps_get_default_rules
output = ET.SubElement(maps_get_default_rules, "output")
rules = ET.SubElement(outp... | Auto Generated Code |
385,364 | def _work_request(self, worker, md5=None):
if not md5 and not self.session.md5:
return
elif not md5:
md5 = self.session.md5
if self.workbench.is_sample_set(md5):
return self.workbench.set_work_request(worker, md5)
... | Wrapper for a work_request to workbench |
385,365 | def set_payload_format(self, payload_format):
request = {
"command": "payload_format",
"format": payload_format
}
status = self._check_command_response_status(request)
self.format = payload_format
return status | Set the payload format for messages sent to and from the VI.
Returns True if the command was successful. |
385,366 | def replace(self, photo_file, **kwds):
result = self._client.photo.replace(self, photo_file, **kwds)
self._replace_fields(result.get_fields()) | Endpoint: /photo/<id>/replace.json
Uploads the specified photo file to replace this photo. |
385,367 | def pca_to_mapping(pca,**extra_props):
from .axes import sampling_axes
method = extra_props.pop(,sampling_axes)
return dict(
axes=pca.axes.tolist(),
covariance=method(pca).tolist(),
**extra_props) | A helper to return a mapping of a PCA result set suitable for
reconstructing a planar error surface in other software packages
kwargs: method (defaults to sampling axes) |
385,368 | def get_subprocess_output(cls, command, ignore_stderr=True, **kwargs):
if ignore_stderr is False:
kwargs.setdefault(, subprocess.STDOUT)
try:
return subprocess.check_output(command, **kwargs).decode().strip()
except (OSError, subprocess.CalledProcessError) as e:
subprocess_output = g... | Get the output of an executed command.
:param command: An iterable representing the command to execute (e.g. ['ls', '-al']).
:param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout.
:raises: `ProcessManager.ExecutionError` on `OSError` or `CalledProcessError`.
:returns... |
385,369 | def pack(chunks, r=32):
if r < 1:
raise ValueError()
n = shift = 0
for c in chunks:
n += c << shift
shift += r
return n | Return integer concatenating integer chunks of r > 0 bit-length.
>>> pack([0, 1, 0, 1, 0, 1], 1)
42
>>> pack([0, 1], 8)
256
>>> pack([0, 1], 0)
Traceback (most recent call last):
...
ValueError: pack needs r > 0 |
385,370 | def map_exp_ids(self, exp):
names = self.exp_feature_names
if self.discretized_feature_names is not None:
names = self.discretized_feature_names
return [(names[x[0]], x[1]) for x in exp] | Maps ids to feature names.
Args:
exp: list of tuples [(id, weight), (id,weight)]
Returns:
list of tuples (feature_name, weight) |
385,371 | def nvmlDeviceGetMemoryInfo(handle):
r
c_memory = c_nvmlMemory_t()
fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryInfo")
ret = fn(handle, byref(c_memory))
_nvmlCheckReturn(ret)
return bytes_to_str(c_memory) | r"""
/**
* Retrieves the amount of used, free and total memory available on the device, in bytes.
*
* For all products.
*
* Enabling ECC reduces the amount of total available memory, due to the extra required parity bits.
* Under WDDM most device memory is allocated and managed on star... |
385,372 | def connected_subgraph(self, node):
G = self.G
subgraph_nodes = set()
subgraph_nodes.add(node)
subgraph_nodes.update(dag.ancestors(G, node))
subgraph_nodes.update(dag.descendants(G, node))
graph_changed = True
while graph_changed:
... | Returns the subgraph containing the given node, its ancestors, and
its descendants.
Parameters
----------
node : str
We want to create the subgraph containing this node.
Returns
-------
subgraph : networkx.DiGraph
The subgraph containing ... |
385,373 | def coin_toss(self):
doc = self.get_doc()
table = doc()
giTable = sportsref.utils.parse_info_table(table)
if in giTable:
pass
else:
return None | Gets information relating to the opening coin toss.
Keys are:
* wonToss - contains the ID of the team that won the toss
* deferred - bool whether the team that won the toss deferred it
:returns: Dictionary of coin toss-related info. |
385,374 | def ping_directories(self, request, queryset, messages=True):
for directory in settings.PING_DIRECTORIES:
pinger = DirectoryPinger(directory, queryset)
pinger.join()
if messages:
success = 0
for result in pinger.results:
... | Ping web directories for selected entries. |
385,375 | def _read(self):
event = self._stick_file.read(self.EVENT_SIZE)
(tv_sec, tv_usec, type, code, value) = struct.unpack(self.EVENT_FORMAT, event)
if type == self.EV_KEY:
return InputEvent(
timestamp=tv_sec + (tv_usec / 1000000),
direction={
... | Reads a single event from the joystick, blocking until one is
available. Returns `None` if a non-key event was read, or an
`InputEvent` tuple describing the event otherwise. |
385,376 | def reload_class_methods(self, class_, verbose=True):
if verbose:
print( % (self, class_))
self.__class__ = class_
for key in dir(class_):
func = getattr(class_, key)
if isinstance(func, types.MethodType):
inject_func_as_method(self, func, class... | rebinds all class methods
Args:
self (object): class instance to reload
class_ (type): type to reload as
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_class import * # NOQA
>>> self = '?'
>>> class_ = '?'
>>> result = reload_class_methods(self, cla... |
385,377 | def headers(self):
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res | Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`. |
385,378 | def GC_partial(portion):
sequence_count = collections.Counter(portion)
gc = ((sum([sequence_count[i] for i in ]) +
sum([sequence_count[i] for i in ]) / 3.0 +
2 * sum([sequence_count[i] for i in ]) / 3.0 +
sum([sequence_count[i] for i in ]) / 2.0) / len(portion))
return 0 ... | Manually compute GC content percentage in a DNA string, taking
ambiguous values into account (according to standard IUPAC notation). |
385,379 | def _par_write(self, dirname):
filename = dirname + +
with open(filename, ) as parfile:
for template in self.templates:
for key in template.__dict__.keys():
if key not in [, ]:
parfile.write(key + +
... | Internal write function to write a formatted parameter file.
:type dirname: str
:param dirname: Directory to write the parameter file to. |
385,380 | def put_intent(name=None, description=None, slots=None, sampleUtterances=None, confirmationPrompt=None, rejectionStatement=None, followUpPrompt=None, conclusionStatement=None, dialogCodeHook=None, fulfillmentActivity=None, parentIntentSignature=None, checksum=None):
pass | Creates an intent or replaces an existing intent.
To define the interaction between the user and your bot, you use one or more intents. For a pizza ordering bot, for example, you would create an OrderPizza intent.
To create an intent or replace an existing intent, you must provide the following:
You can spe... |
385,381 | def create_branch_and_checkout(self, branch_name: str):
self.create_branch(branch_name)
self.checkout(branch_name) | Creates a new branch if it doesn't exist
Args:
branch_name: branch name |
385,382 | def remove(self, address):
with self.lock:
for connection in self.connections.pop(address, ()):
try:
connection.close()
except IOError:
pass | Remove an address from the connection pool, if present, closing
all connections to that address. |
385,383 | def run(cmd,
capture=False,
shell=True,
env=None,
exit_on_error=None,
never_pretend=False):
if context.get(, False) and not never_pretend:
cprint(, cmd)
return ExecResult(
cmd,
0,
,
... | Run a shell command.
Args:
cmd (str):
The shell command to execute.
shell (bool):
Same as in `subprocess.Popen`.
capture (bool):
If set to True, it will capture the standard input/error instead of
just piping it to the caller stdout/stderr.
... |
385,384 | def clean_email(self):
if EMAIL_CONFIRMATION:
from .models import EmailAddress
condition = EmailAddress.objects.filter(
email__iexact=self.cleaned_data["email"],
verified=True
).count() == 0
else:
condition = User.o... | ensure email is in the database |
385,385 | def GetProp(self, prop):
if prop == :
return self.id
elif prop == :
return self.status
elif prop == :
return self.bm
elif prop == :
return self.graph
else:
return self.properties[prop] | get attribute |
385,386 | def selection(self):
sel = QtGui.QItemSelection()
for index in self.selectedIndexes():
sel.select(index, index)
return sel | Returns items in selection as a QItemSelection object |
385,387 | def search(request, abbr):
if not request.GET:
return render(request, templatename(),
{: abbr})
search_text = unicode(request.GET[]).encode()
if re.search(r, search_text):
url = % abbr
url += urllib.urlencode([(, search_text)])
return redire... | Context:
- search_text
- abbr
- metadata
- found_by_id
- bill_results
- more_bills_available
- legislators_list
- nav_active
Tempaltes:
- billy/web/public/search_results_no_query.html
- billy/web/public/search_results_bills_legislators... |
385,388 | def predict(self, data, initial_args=None):
request_args = self._create_request_args(data, initial_args)
response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
return self._handle_response(response) | Return the inference from the specified endpoint.
Args:
data (object): Input data for which you want the model to provide inference.
If a serializer was specified when creating the RealTimePredictor, the result of the
serializer is sent as input data. Otherwise the d... |
385,389 | def remove_parenthesis_around_tz(cls, timestr):
parenthesis = cls.TIMEZONE_PARENTHESIS.match(timestr)
if parenthesis is not None:
return parenthesis.group(1) | get rid of parenthesis around timezone: (GMT) => GMT
:return: the new string if parenthesis were found, `None` otherwise |
385,390 | def create(epsilon: typing.Union[Schedule, float]):
return GenericFactory(EpsGreedy, arguments={: epsilon}) | Vel factory function |
385,391 | def _divide_and_round(a, b):
q, r = divmod(a, b)
r *= 2
greater_than_half = r > b if b > 0 else r < b
if greater_than_half or r == b and q % 2 == 1:
q += 1
return q | divide a by b and round result to the nearest integer
When the ratio is exactly half-way between two integers,
the even integer is returned. |
385,392 | def __get_resource_entry_data(self, bundleId, languageId, resourceKey,
fallback=False):
url = self.__get_base_bundle_url() + + bundleId + \
+ languageId + + resourceKey
params = {: } if fallback else None
response = self.__perform... | ``GET /{serviceInstanceId}/v2/bundles/{bundleId}/{languageId}
/{resourceKey}``
Gets the resource entry information. |
385,393 | def check_ellipsis(text):
err = "typography.symbols.ellipsis"
msg = u" is an approximation, use the ellipsis symbol ."
regex = "\.\.\."
return existence_check(text, [regex], err, msg, max_errors=3,
require_padding=False, offset=0) | Use an ellipsis instead of three dots. |
385,394 | def __get_merged_api_info(self, services):
base_paths = sorted(set(s.api_info.base_path for s in services))
if len(base_paths) != 1:
raise api_exceptions.ApiConfigurationError(
.format(base_paths))
names_versions = sorted(set(
(s.api_info.name, s.api_info.api_version) for s in s... | Builds a description of an API.
Args:
services: List of protorpc.remote.Service instances implementing an
api/version.
Returns:
The _ApiInfo object to use for the API that the given services implement. |
385,395 | def text_search(self, anchor, byte=False):
if isinstance(anchor, six.text_type):
if byte:
raise GrabMisuseError(
)
else:
return anchor in self.unicode_body()
if not isinstance(anchor, six.text_type):... | Search the substring in response body.
:param anchor: string to search
:param byte: if False then `anchor` should be the
unicode string, and search will be performed in
`response.unicode_body()` else `anchor` should be the byte-string
and search will be performed in ... |
385,396 | def do_loop_turn(self):
self.check_and_del_zombie_modules()
if self.watch_for_new_conf(timeout=0.05):
logger.info("I got a new configuration...")
self.setup_new_conf()
_t0 = time.time()
self.get_objects_... | Receiver daemon main loop
:return: None |
385,397 | def find(self, obj, forced_type=None,
cls=anyconfig.models.processor.Processor):
return find(obj, self.list(), forced_type=forced_type, cls=cls) | :param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param forced_type: Forced processor type to find
:param cls: A class object to compare with 'ptype'
:return: an instance of processor class to proce... |
385,398 | def _prepare_connection(**nxos_api_kwargs):
nxos_api_kwargs = clean_kwargs(**nxos_api_kwargs)
init_kwargs = {}
for karg, warg in six.iteritems(nxos_api_kwargs):
if karg in RPC_INIT_KWARGS:
init_kwargs[karg] = warg
if not in init_kwargs:
init_kwargs[] =
if not... | Prepare the connection with the remote network device, and clean up the key
value pairs, removing the args used for the connection init. |
385,399 | def total_statements(self, filename=None):
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total... | Return the total number of statements for the file
`filename`. If `filename` is not given, return the total
number of statements for all files. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.