Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
15,900 | def threshold_otsu(image, multiplier=1.0):
otsu_value = skimage.filters.threshold_otsu(image)
return image > otsu_value * multiplier | Return image thresholded using Otsu's method. |
15,901 | def has_changed_since_last_deploy(file_path, bucket):
msg = "Checking if {0} has changed since last deploy.".format(file_path)
logger.debug(msg)
with open(file_path) as f:
data = f.read()
file_md5 = hashlib.md5(data.encode()).hexdigest()
logger.debug("file_md5 is {0}".format(fi... | Checks if a file has changed since the last time it was deployed.
:param file_path: Path to file which should be checked. Should be relative
from root of bucket.
:param bucket_name: Name of S3 bucket to check against.
:returns: True if the file has changed, else False. |
15,902 | def mmGetMetricSequencesPredictedActiveCellsShared(self):
self._mmComputeTransitionTraces()
numSequencesForCell = defaultdict(lambda: 0)
for predictedActiveCells in (
self._mmData["predictedActiveCellsForSequence"].values()):
for cell in predictedActiveCells:
numSequencesForCe... | Metric for number of sequences each predicted => active cell appears in
Note: This metric is flawed when it comes to high-order sequences.
@return (Metric) metric |
15,903 | def latex(self):
s = (
)
if len(self.authors) > 1:
authors = .join([str(a.given_name) +
+ str(a.surname)
for a in self.authors[0:-1]])
authors += ( +
str(self.authors[... | Return LaTeX representation of the abstract. |
15,904 | def get_default_config(self):
config = super(LibratoHandler, self).get_default_config()
config.update({
: ,
: ,
: False,
: 300,
: 60,
: [],
})
return config | Return the default config for the handler |
15,905 | def QCapsulate(self, widget, name, blocking = False, nude = False):
class QuickWindow(QtWidgets.QMainWindow):
class Signals(QtCore.QObject):
close = QtCore.Signal()
show = QtCore.Signal()
def __init__(self, blocking = False, parent = None, nud... | Helper function that encapsulates QWidget into a QMainWindow |
15,906 | def rand_article(num_p=(4, 10), num_s=(2, 15), num_w=(5, 40)):
article = list()
for _ in range(random.randint(*num_p)):
p = list()
for _ in range(random.randint(*num_s)):
s = list()
for _ in range(random.randint(*num_w)):
s.append(
... | Random article text.
Example::
>>> rand_article()
... |
15,907 | def main():
if in sys.argv:
print(main.__doc__)
sys.exit()
if len(sys.argv) <= 1:
print(main.__doc__)
print()
sys.exit()
FIG = {}
FIG[] = 1
pmagplotlib.plot_init(FIG[], 6, 6)
norm = 1
in_file = pmag.get_named_arg("-f", "measurements.txt")
... | NAME
lowrie_magic.py
DESCRIPTION
plots intensity decay curves for Lowrie experiments
SYNTAX
lowrie_magic.py -h [command line options]
INPUT
takes measurements formatted input files
OPTIONS
-h prints help message and quits
-f FILE: specify input file, def... |
15,908 | def path_join(*args):
args = (paramiko.py3compat.u(arg) for arg in args)
return os.path.join(*args) | Wrapper around `os.path.join`.
Makes sure to join paths of the same type (bytes). |
15,909 | def snr_from_loglr(loglr):
singleval = isinstance(loglr, float)
if singleval:
loglr = numpy.array([loglr])
numpysettings = numpy.seterr(invalid=)
snrs = numpy.sqrt(2*loglr)
numpy.seterr(**numpysettings)
snrs[numpy.isnan(snrs)] = 0.
if singleval:
snrs = snrs[0]
r... | Returns SNR computed from the given log likelihood ratio(s). This is
defined as `sqrt(2*loglr)`.If the log likelihood ratio is < 0, returns 0.
Parameters
----------
loglr : array or float
The log likelihood ratio(s) to evaluate.
Returns
-------
array or float
The SNRs compu... |
15,910 | def _infer_sig_len(file_name, fmt, n_sig, dir_name, pb_dir=None):
if pb_dir is None:
file_size = os.path.getsize(os.path.join(dir_name, file_name))
else:
file_size = download._remote_file_size(file_name=file_name,
pb_dir=pb_dir)
sig_len = ... | Infer the length of a signal from a dat file.
Parameters
----------
file_name : str
Name of the dat file
fmt : str
WFDB fmt of the dat file
n_sig : int
Number of signals contained in the dat file
Notes
-----
sig_len * n_sig * bytes_per_sample == file_size |
15,911 | def expect_bounded(__funcname=_qualified_name, **named):
def _make_bounded_check(bounds):
(lower, upper) = bounds
if lower is None:
def should_fail(value):
return value > upper
predicate_descr = "less than or equal to " + str(upper)
elif upper is ... | Preprocessing decorator verifying that inputs fall INCLUSIVELY between
bounds.
Bounds should be passed as a pair of ``(min_value, max_value)``.
``None`` may be passed as ``min_value`` or ``max_value`` to signify that
the input is only bounded above or below.
Examples
--------
>>> @expect_... |
15,912 | def _parse_area(self, area_xml):
area = Area(self._lutron,
name=area_xml.get(),
integration_id=int(area_xml.get()),
occupancy_group_id=area_xml.get())
for output_xml in area_xml.find():
output = self._parse_output(output_xml)
area.add_output(outpu... | Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done. |
15,913 | def update_firmware(self, filename, component_type):
fw_img_processor = firmware_controller.FirmwareImageUploader(filename)
LOG.debug(self._(), filename)
cookie = fw_img_processor.upload_file_to((self.host, self.port),
self.timeout)
... | Updates the given firmware on the server for the given component.
:param filename: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen prior to this invocation.
:param component_type: Type of c... |
15,914 | def read_file_snippets(file, snippet_store):
start_reg = re.compile("(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)")
end_reg = re.compile("(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)")
open_snippets = {}
with open(file, encoding="utf-8") as w:
lines = w.readlines()
for line in lines:
pri... | Parse a file and add all snippets to the snippet_store dictionary |
15,915 | def write_timestamp(self, t, pack=Struct().pack):
self._output_buffer.extend(pack(long(timegm(t.timetuple()))))
return self | Write out a Python datetime.datetime object as a 64-bit integer
representing seconds since the Unix UTC epoch. |
15,916 | def read_hypergraph(string):
hgr = hypergraph()
dom = parseString(string)
for each_node in dom.getElementsByTagName("node"):
hgr.add_node(each_node.getAttribute())
for each_node in dom.getElementsByTagName("hyperedge"):
hgr.add_hyperedge(each_node.getAttribute())
dom =... | Read a graph from a XML document. Nodes and hyperedges specified in the input will be added
to the current graph.
@type string: string
@param string: Input string in XML format specifying a graph.
@rtype: hypergraph
@return: Hypergraph |
15,917 | def _to_list(obj):
ret = {}
for attr in __attrs:
if hasattr(obj, attr):
ret[attr] = getattr(obj, attr)
return ret | Convert snetinfo object to list |
15,918 | def determine_inside_container(self):
tokenum, value = self.current.tokenum, self.current.value
ending_container = False
starting_container = False
if tokenum == OP:
self.containers.pop()
ending_container = True
... | Set self.in_container if we're inside a container
* Inside container
* Current token starts a new container
* Current token ends all containers |
15,919 | def show_bare_metal_state_output_bare_metal_state(self, **kwargs):
config = ET.Element("config")
show_bare_metal_state = ET.Element("show_bare_metal_state")
config = show_bare_metal_state
output = ET.SubElement(show_bare_metal_state, "output")
bare_metal_state = ET.SubEl... | Auto Generated Code |
15,920 | def get_all_responses(self, service_name, receive_timeout_in_seconds=None):
handler = self._get_handler(service_name)
return handler.get_all_responses(receive_timeout_in_seconds) | Receive all available responses from the service as a generator.
:param service_name: The name of the service from which to receive responses
:type service_name: union[str, unicode]
:param receive_timeout_in_seconds: How long to block without receiving a message before raising
... |
15,921 | async def create_new_sticker_set(self, user_id: base.Integer, name: base.String, title: base.String,
png_sticker: typing.Union[base.InputFile, base.String], emojis: base.String,
contains_masks: typing.Union[base.Boolean, None] = None,
... | Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
Source: https://core.telegram.org/bots/api#createnewstickerset
:param user_id: User identifier of created sticker set owner
:type user_id: :obj:`base.Integer`
:param name: S... |
15,922 | def visit_repr(self, node, parent):
newnode = nodes.Repr(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode | visit a Backquote node by returning a fresh instance of it |
15,923 | def orderrun_detail(dk_api, kitchen, pd):
if DKCloudCommandRunner.SUMMARY in pd:
display_summary = True
else:
display_summary = False
pd[DKCloudCommandRunner.SUMMARY] = True
rc = dk_api.orderrun_detail(kitchen, pd)
s =
if not rc.... | returns a string.
:param dk_api: -- api object
:param kitchen: string
:param pd: dict
:rtype: DKReturnCode |
15,924 | def get_txn_outputs(raw_tx_hex, output_addr_list, coin_symbol):
s expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
[{: 12345, : }, ...]
Uses @vbuterin
... | Used to verify a transaction hex does what's expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
[{'value': 12345, 'address': '1abc...'}, ...]
Uses @vbuterin's ... |
15,925 | def bootstrapSampleFromData(data,weights=None,seed=0):
RNG = np.random.RandomState(seed)
N = data.shape[0]
if weights is not None:
cutoffs = np.cumsum(weights)
else:
cutoffs = np.linspace(0,1,N)
indices = np.searchsorted(cutoffs,RNG.uniform(size=N))
ne... | Samples rows from the input array of data, generating a new data array with
an equal number of rows (records). Rows are drawn with equal probability
by default, but probabilities can be specified with weights (must sum to 1).
Parameters
----------
data : np.array
An array of data, with eac... |
15,926 | def __error_middleware(self, res, res_json):
if(res.status_code in [400, 401, 402, 403, 404, 405, 406, 409]):
err_dict = res_json.get(, {})
raise UpCloudAPIError(error_code=err_dict.get(),
error_message=err_dict.get())
return res_json | Middleware that raises an exception when HTTP statuscode is an error code. |
15,927 | def mean(self, axis=None, keepdims=False):
return self._stat(axis, name=, keepdims=keepdims) | Return the mean of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boolean, optional, default=False
Keep axis remaining aft... |
15,928 | def parse_vote_data(self, vote_data):
if not in vote_data.keys():
logger.debug(,
vote_data[])
return
dossier_pk = self.get_dossier(vote_data[])
if not dossier_pk:
logger.debug(,
vote_data[])
retu... | Parse data from parltrack votes db dumps (1 proposal) |
15,929 | def parse_buffer(buffer, mode="exec", flags=[], version=None, engine=None):
if version is None:
version = sys.version_info[0:2]
if engine is None:
engine = pythonparser_diagnostic.Engine()
lexer = pythonparser_lexer.Lexer(buffer, version, engine)
if mode in ("single", "eval"):
... | Like :meth:`parse`, but accepts a :class:`source.Buffer` instead of
source and filename, and returns comments as well.
:see: :meth:`parse`
:return: (:class:`ast.AST`, list of :class:`source.Comment`)
Abstract syntax tree and comments |
15,930 | def restore(file_name, jail=None, chroot=None, root=None):
***
return __salt__[](
_pkg(jail, chroot, root) + [, , file_name],
output_loglevel=,
python_shell=False
) | Reads archive created by pkg backup -d and recreates the database.
CLI Example:
.. code-block:: bash
salt '*' pkg.restore /tmp/pkg
jail
Restore database to the specified jail. Note that this will run the
command within the jail, and so the path to the file from which the pkg
... |
15,931 | def contour(self, win, ngr=20, layers=0, levels=20, layout=True, labels=True,
decimals=0, color=None, newfig=True, figsize=None, legend=True):
x1, x2, y1, y2 = win
if np.isscalar(ngr):
nx = ny = ngr
else:
nx, ny = ngr
layers = np.... | Contour plot
Parameters
----------
win : list or tuple
[x1, x2, y1, y2]
ngr : scalar, tuple or list
if scalar: number of grid points in x and y direction
if tuple or list: nx, ny, number of grid points in x and y direction
layers ... |
15,932 | def get_value(file, element):
*
try:
root = ET.parse(file)
element = root.find(element)
return element.text
except AttributeError:
log.error("Unable to find element matching %s", element)
return False | Returns the value of the matched xpath element
CLI Example:
.. code-block:: bash
salt '*' xml.get_value /tmp/test.xml ".//element" |
15,933 | def prepare_attrib_mapping(self, primitive):
buffer_info = []
for name, accessor in primitive.attributes.items():
info = VBOInfo(*accessor.info())
info.attributes.append((name, info.components))
if buffer_info and buffer_info[-1].buffer_view == info.buffer_v... | Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive |
15,934 | def optimize(self, optimizer=None, start=None, messages=False, max_iters=1000, ipython_notebook=True, clear_after_finish=False, **kwargs):
if self.is_fixed or self.size == 0:
print()
return
if not self.update_model():
print("updates were off, setting updates... | Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.
kwargs are passed to the optimizer. They can be:
:param max_iters: maximum number of function evaluations
:type max_iters: int
:messages: True: Display messages during optimisation, "... |
15,935 | def _varian(self, varian):
if varian == self.bentuk_tidak_baku:
nama = "Bentuk tidak baku"
elif varian == self.varian:
nama = "Varian"
else:
return
return nama + + .join(varian) | Mengembalikan representasi string untuk varian entri ini.
Dapat digunakan untuk "Varian" maupun "Bentuk tidak baku".
:param varian: List bentuk tidak baku atau varian
:type varian: list
:returns: String representasi varian atau bentuk tidak baku
:rtype: str |
15,936 | def as_encodable(self, index_name):
if self.facets:
encoded_facets = {}
for name, facet in self.facets.items():
encoded_facets[name] = facet.encodable
self._json_[] = encoded_facets
if self._ms:
sv_val = {
... | :param index_name: The name of the index for the query
:return: A dict suitable for passing to `json.dumps()` |
15,937 | def draw_rect(grid, attr, dc, rect):
dc.SetBrush(wx.Brush(wx.Colour(15, 255, 127), wx.SOLID))
dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))
dc.DrawRectangleRect(rect) | Draws a rect |
15,938 | def tica(data=None, lag=10, dim=-1, var_cutoff=0.95, kinetic_map=True, commute_map=False, weights=,
stride=1, remove_mean=True, skip=0, reversible=True, ncov_max=float(), chunksize=None, **kwargs):
r
from pyemma.coordinates.transform.tica import TICA
from pyemma.coordinates.estimation.koopman impor... | r""" Time-lagged independent component analysis (TICA).
TICA is a linear transformation method. In contrast to PCA, which finds
coordinates of maximal variance, TICA finds coordinates of maximal
autocorrelation at the given lag time. Therefore, TICA is useful in order
to find the *slow* components in a... |
15,939 | def getOverlayTransformAbsolute(self, ulOverlayHandle):
fn = self.function_table.getOverlayTransformAbsolute
peTrackingOrigin = ETrackingUniverseOrigin()
pmatTrackingOriginToOverlayTransform = HmdMatrix34_t()
result = fn(ulOverlayHandle, byref(peTrackingOrigin), byref(pmatTrack... | Gets the transform if it is absolute. Returns an error if the transform is some other type. |
15,940 | def series_resistors(target,
pore_area=,
throat_area=,
pore_conductivity=,
throat_conductivity=,
conduit_lengths=,
conduit_shape_factors=):
r
return generic_conductance(target=target, tr... | r"""
Calculate the electrical conductance of conduits in network, where a
conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated... |
15,941 | def convert_row(self, keyed_row, schema, fallbacks):
for key, value in list(keyed_row.items()):
field = schema.get_field(key)
if not field:
del keyed_row[key]
if key in fallbacks:
value = _uncast_value(value, field=field)
e... | Convert row to SQL |
15,942 | def create_class(self):
if self.target_language in [, ]:
n_indents = 1 if self.target_language == else 0
class_head_temp = self.temp(.format(
self.prefix), n_indents=n_indents, skipping=True)
self.class_head = class_head_temp.format(**self.__dict__)
... | Build the estimator class.
Returns
-------
:return : string
The built class as string. |
15,943 | def part(self, target, reason=None):
if reason:
target += + reason
self.send_line( % target) | quit a channel |
15,944 | def capture(self, pattern=None, negate=False, workers=None, negate_workers=False,
params=None, success=False, error=True, stats=False):
request = clearly_pb2.CaptureRequest(
tasks_capture=clearly_pb2.PatternFilter(pattern=pattern or ,
... | Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in... |
15,945 | def gcmt_to_simple_array(self, centroid_location=True):
catalogue = np.zeros([self.get_number_tensors(), 29], dtype=float)
for iloc, tensor in enumerate(self.gcmts):
catalogue[iloc, 0] = iloc
if centroid_location:
catalogue[iloc, 1] = float(tensor.centroi... | Converts the GCMT catalogue to a simple array of
[ID, year, month, day, hour, minute, second, long., lat., depth, Mw,
strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth,
b-eigenvalue, p-plunge, p-azimuth, p-eigenvalue, t-plunge, t-azimuth,
t-eigenvalue, moment, f_clvd, erel] |
15,946 | def get_one_file_in(dirname):
files = os.listdir(dirname)
if len(files) > 1:
raise Failure( %
(dirname, .join(sorted(files))))
elif not files:
raise Failure( % dirname)
return os.path.join(dirname, files[0]) | Return the pathname of the one file in a directory.
Raises if the directory has no files or more than one file. |
15,947 | def generate_covalent_bond_graph(covalent_bonds):
bond_graph=networkx.Graph()
for inter in covalent_bonds:
bond_graph.add_edge(inter.a, inter.b)
return bond_graph | Generates a graph of the covalent bond network described by the interactions.
Parameters
----------
covalent_bonds: [CovalentBond]
List of `CovalentBond`.
Returns
-------
bond_graph: networkx.Graph
A graph of the covalent bond network. |
15,948 | def describe(self, *cols):
if len(cols) == 1 and isinstance(cols[0], list):
cols = cols[0]
jdf = self._jdf.describe(self._jseq(cols))
return DataFrame(jdf, self.sql_ctx) | Computes basic statistics for numeric and string columns.
This include count, mean, stddev, min, and max. If no columns are
given, this function computes statistics for all numerical or string columns.
.. note:: This function is meant for exploratory data analysis, as we make no
gu... |
15,949 | def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw):
builder = reconciler.GDNSReconcilerBuilder(
config, metrics, rrset_channel, changes_channel, **kw)
return builder.build_reconciler() | Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementatio... |
15,950 | def tensor_info_proto_maps_match(map_a, map_b):
iter_a = sorted(parse_tensor_info_map(map_a).items())
iter_b = sorted(parse_tensor_info_map(map_b).items())
if len(iter_a) != len(iter_b):
return False
for info_a, info_b in zip(iter_a, iter_b):
if info_a[0] != info_b[0]:
return False
if _... | Whether two signature inputs/outputs match in dtype, shape and sparsity.
Args:
map_a: A proto map<string,TensorInfo>.
map_b: A proto map<string,TensorInfo>.
Returns:
A boolean whether `map_a` and `map_b` tensors have the same dtype, shape and
sparsity. |
15,951 | def _get_headers(environ):
for key, value in environ.items():
key = str(key)
if key.startswith("HTTP_") and key not in (
"HTTP_CONTENT_TYPE",
"HTTP_CONTENT_LENGTH",
):
yield key[5:].replace("_", "-").title(), value
elif key in ("CONTENT_T... | Returns only proper HTTP headers. |
15,952 | def get_cameras_properties(self):
resource = "cameras"
resource_event = self.publish_and_get_event(resource)
if resource_event:
self._last_refresh = int(time.time())
self._camera_properties = resource_event.get() | Return camera properties. |
15,953 | def datalog(self, parameter, run, maxrun=None, det_id=):
"Retrieve datalogs for given parameter, run(s) and detector"
parameter = parameter.lower()
if maxrun is None:
maxrun = run
with Timer():
return self._datalog(parameter, run, maxrun, det_id) | Retrieve datalogs for given parameter, run(s) and detector |
15,954 | def gain(abf):
Ys=np.nan_to_num(swhlab.ap.getAvgBySweep(abf,))
Xs=abf.clampValues(abf.dataX[int(abf.protoSeqX[1]+.01)])
swhlab.plot.new(abf,title="gain function",xlabel="command current (pA)",
ylabel="average inst. freq. (Hz)")
pylab.plot(Xs,Ys,,ms=20,alpha=.5,color=)
pylab.... | easy way to plot a gain function. |
15,955 | def host_inventory_get(hostids, **kwargs):
s docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring)
:return: Array with host interfaces details, False if no convenient host interfaces found or on failure.
CLI Example:
.. code-b... | Retrieve host inventory according to the given parameters.
See: https://www.zabbix.com/documentation/2.4/manual/api/reference/host/object#host_inventory
.. versionadded:: 2019.2.0
:param hostids: Return only host interfaces used by the given hosts.
:param _connection_user: Optional - zabbix user (can ... |
15,956 | async def delete(self, _id=None):
if not _id:
return {"error":400,
"reason":"Missed required fields"}
document = await self.collection.find_one({"id": _id})
if not document:
return {"error":404,
"reason":"Not found"}
deleted_count = await self.collection.delete_one(
{"id": _id}).d... | Delete entry from database table.
Accepts id.
delete(id) => 1 (if exists)
delete(id) => {"error":404, "reason":"Not found"} (if does not exist)
delete() => {"error":400, "reason":"Missed required fields"} |
15,957 | def get_raw_mempool(self, id=None, endpoint=None):
return self._call_endpoint(GET_RAW_MEMPOOL, id=id, endpoint=endpoint) | Returns the tx that are in the memorypool of the endpoint
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the error encountered in the RPC call |
15,958 | def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"):
cmd_args = []
if options is not None:
cmd_args.extend([, options])
cmd_args.extend([device, mountpoint])
try:
subprocess.check_output(cmd_args)
except subprocess.CalledProcessError as e:
log(.... | Mount a filesystem at a particular mountpoint |
15,959 | def _watch_file(self, filepath, trigger_event=True):
is_new = filepath not in self._watched_files
if trigger_event:
if is_new:
self.trigger_created(filepath)
else:
self.trigger_modified(filepath)
try:
self._watched_file... | Adds the file's modified time into its internal watchlist. |
15,960 | def get_or_none(cls, **filter_kwargs):
try:
video = cls.objects.get(**filter_kwargs)
except cls.DoesNotExist:
video = None
return video | Returns a video or None. |
15,961 | def PrintIndented(self, file, ident, code):
for entry in code:
print >>file, % (ident, entry) | Takes an array, add indentation to each entry and prints it. |
15,962 | def move(self, direction, absolute=False, pad_name=None, refresh=True):
cursor_line = [ ]
scroll_only = [ ]
if not pad_name:
pad_name = self.current_pad
pad = self.pads[pad_name]
if pad_name == and self.no_streams:
... | Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
Behaviour is affected by cursor_line and scroll_only below
absolute : (bool) |
15,963 | def token_info(token, refresh=True, refresh_cb=None, session=None):
session = session or HTTP_SESSION
params = dict(access_token=token.access_token)
resp = session.get(TOKEN_INFO_URL, params=params)
if resp.status_code != 200:
if refresh:
token = refresh_token(token, session=ses... | :param OAuthToken token
:param bool refresh:
whether to attempt to refresh the OAuth token if it expired.
default is `True`.
:param refresh_cb:
If specified, a callable object which is given the new token
in parameter if it has been refreshed.
:param requests.Session session:
... |
15,964 | def p_unrelate_statement_2(self, p):
p[0] = UnrelateNode(from_variable_name=p[2],
to_variable_name=p[4],
rel_id=p[6],
phrase=p[8]) | statement : UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase |
15,965 | def get_config( config_path=CONFIG_PATH ):
parser = SafeConfigParser()
parser.read( config_path )
config_dir = os.path.dirname(config_path)
immutable_key = False
key_id = None
blockchain_id = None
hostname = socket.gethostname()
wallet = None
if parser.has_section():
... | Get the config |
15,966 | def draw(self, **kwargs):
x = self.n_feature_subsets_
means = self.cv_scores_.mean(axis=1)
sigmas = self.cv_scores_.std(axis=1)
self.ax.fill_between(x, means - sigmas, means+sigmas, alpha=0.25)
self.ax.plot(x, means, )
self... | Renders the rfecv curve. |
15,967 | def reset(cwd,
opts=,
git_opts=,
user=None,
password=None,
identity=None,
ignore_retcode=False,
output_encoding=None):
s own argument parsing.
git_opts
Any additional options to add to git command itself (not the ``reset``
su... | Interface to `git-reset(1)`_, returns the stdout from the git command
cwd
The path to the git checkout
opts
Any additional options to add to the command line, in a single string
.. note::
On the Salt CLI, if the opts are preceded with a dash, it is
necessary to... |
15,968 | def _take_forced_measurement(self):
self._bus.write_byte_data(self._i2c_add, 0xF4, self.ctrl_meas_reg)
while self._bus.read_byte_data(self._i2c_add, 0xF3) & 0x08:
sleep(0.005) | Take a forced measurement.
In forced mode, the BME sensor goes back to sleep after each
measurement and we need to set it to forced mode once at this point,
so it will take the next measurement and then return to sleep again.
In normal mode simply does new measurements periodically. |
15,969 | def _nan_minmax_object(func, fill_value, value, axis=None, **kwargs):
valid_count = count(value, axis=axis)
filled_value = fillna(value, fill_value)
data = getattr(np, func)(filled_value, axis=axis, **kwargs)
if not hasattr(data, ):
data = dtypes.fill_value(value.dtype) if valid_count == ... | In house nanmin and nanmax for object array |
15,970 | def BuildChecks(self, request):
result = []
if request.HasField("start_time") or request.HasField("end_time"):
def FilterTimestamp(file_stat, request=request):
return file_stat.HasField("st_mtime") and (
file_stat.st_mtime < request.start_time or
file_stat.st_mtime > ... | Parses request and returns a list of filter callables.
Each callable will be called with the StatEntry and returns True if the
entry should be suppressed.
Args:
request: A FindSpec that describes the search.
Returns:
a list of callables which return True if the file is to be suppressed. |
15,971 | def show_script_error(self, parent):
if self.service.scriptRunner.error != :
dlg = Gtk.MessageDialog(type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK,
message_format=self.service.scriptRunner.error)
self.service.scriptRunner.error =
... | Show the last script error (if any) |
15,972 | def print_tree(self) -> str:
if self.ast:
return self.ast.print_tree(ast_obj=self.ast)
else:
return "" | Convert AST object to tree view of BEL AST
Returns:
printed tree of BEL AST |
15,973 | def __arguments(self, ttype, tvalue):
if ttype == "identifier":
test = get_command_instance(tvalue.decode("ascii"), self.__curcommand)
self.__curcommand.check_next_arg("test", test)
self.__expected = test.get_expected_first()
self.__curcommand = test
... | Arguments parsing method
Entry point for command arguments parsing. The parser must
call this method for each parsed command (either a control,
action or test).
Syntax:
*argument [ test / test-list ]
:param ttype: current token type
:param tvalue: current t... |
15,974 | def exec_event_handler(self, event, transactional=False):
callbacks = self._options.get(, {})
handler = callbacks.get(event)
if not handler:
raise Exception()
handler.start(transactional=transactional) | Execute the Async set to be run on event. |
15,975 | def _http_resp_rate_limited(response):
parsed = parse.urlparse(response.request.url)
duration = int(response.headers.get(, 3))
LOGGER.warning(,
parsed.netloc, duration)
return asyncio.sleep(duration) | Extract the ``Retry-After`` header value if the request was rate
limited and return a future to sleep for the specified duration.
:param tornado.httpclient.HTTPResponse response: The response
:rtype: tornado.concurrent.Future |
15,976 | def exit(self, status=0, message=None):
self.exited = True
if message is not None:
self.mesgs.extend(message.split())
raise s_exc.BadSyntax(mesg=message, prog=self.prog, status=status) | Argparse expects exit() to be a terminal function and not return.
As such, this function must raise an exception which will be caught
by Cmd.hasValidOpts. |
15,977 | def env_float(name, required=False, default=empty):
value = get_env_value(name, required=required, default=default)
if value is empty:
raise ValueError(
"`env_float` requires either a default value to be specified, or for "
"the variable to be present in the environment"
... | Pulls an environment variable out of the environment and casts it to an
float. If the name is not present in the environment and no default is
specified then a ``ValueError`` will be raised. Similarly, if the
environment value is not castable to an float, a ``ValueError`` will be
raised.
:param nam... |
15,978 | def flatten(self) -> bk.BKTensor:
N = self.qubit_nb
R = self.rank
return bk.reshape(self.tensor, [2**N]*R) | Return tensor with with qubit indices flattened |
15,979 | def cli(env, is_open):
ticket_mgr = SoftLayer.TicketManager(env.client)
table = formatting.Table([
, , , , , ,
])
tickets = ticket_mgr.list_tickets(open_status=is_open, closed_status=not is_open)
for ticket in tickets:
user = formatting.blank()
if ticket.get():
... | List tickets. |
15,980 | def decode(self):
fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \
origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20])
assert fmt == 1
length = (len_high << 8) | len_low
self.origin = device_id
self.r... | Decode this report into a list of readings |
15,981 | def max(self):
return int(self._max) if not np.isinf(self._max) else self._max | Returns the maximum value of the domain.
:rtype: `float` or `np.inf` |
15,982 | def set_widgets(self):
clear_layout(self.gridLayoutThreshold)
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
layer_subcategory = self.parent.step_kw_subcategory.\
selected_subcategory()
classification = self.parent.step_kw_classification. \
... | Set widgets on the Threshold tab. |
15,983 | def get_rows(self, sort=False):
ret = []
for _, rows in sorted(self._rows.items()) if sort else self._rows.items():
self._rows_int2date(rows)
ret.extend(rows)
return ret | Returns the rows of this Type2Helper.
:param bool sort: If True the rows are sorted by the pseudo key. |
15,984 | def get_cluster_graph(self, engine="fdp", graph_attr=None, node_attr=None, edge_attr=None):
from graphviz import Digraph
g = Digraph("directory",
engine=engine)
g.attr(label=self.top)
g.node_attr.update(color=,... | Generate directory graph in the DOT language. Directories are shown as clusters
.. warning::
This function scans the entire directory tree starting from top so the resulting
graph can be really big.
Args:
engine: Layout command used. ['dot', 'neato', 'twopi', 'circ... |
15,985 | def _define_absl_flag(self, flag_instance, suppress):
flag_name = flag_instance.name
short_name = flag_instance.short_name
argument_names = [ + flag_name]
if short_name:
argument_names.insert(0, + short_name)
if suppress:
helptext = argparse.SUPPRESS
else:
self.add... | Defines a flag from the flag_instance. |
15,986 | def filesys_decode(path):
if isinstance(path, six.text_type):
return path
fs_enc = sys.getfilesystemencoding() or
candidates = fs_enc,
for enc in candidates:
try:
return path.decode(enc)
except UnicodeDecodeError:
continue | Ensure that the given path is decoded,
NONE when no expected encoding works |
15,987 | def default_output_format(content_type=, apply_globally=False, api=None, cli=False, http=True):
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if apply_globally:
if http:
hug.defaults.output_format = formatter
... | A decorator that allows you to override the default output format for an API |
15,988 | def get_namespace(self, uri):
key = (self, uri)
if key in self.context.namespaces:
return self.context.namespaces[key]
else:
ns = TemplateNamespace(uri, self.context._copy(),
templateuri=uri,
calling... | Return a :class:`.Namespace` corresponding to the given ``uri``.
If the given ``uri`` is a relative URI (i.e. it does not
contain a leading slash ``/``), the ``uri`` is adjusted to
be relative to the ``uri`` of the namespace itself. This
method is therefore mostly useful off of the buil... |
15,989 | def fetch_artifact(self, trial_id, prefix):
local = os.path.join(self.log_dir, trial_id, prefix)
if self.upload_dir:
remote = .join([self.upload_dir, trial_id, prefix])
_remote_to_local_sync(remote, local)
return local | Verifies that all children of the artifact prefix path are
available locally. Fetches them if not.
Returns the local path to the given trial's artifacts at the
specified prefix, which is always just
{log_dir}/{trial_id}/{prefix} |
15,990 | def _input_as_list(self, data):
query, database, output = data
if (not isabs(database)) \
or (not isabs(query)) \
or (not isabs(output)):
raise ApplicationError("Only absolute paths allowed.\n%s" %
.join(data))
... | Takes the positional arguments as input in a list.
The list input here should be [query_file_path, database_file_path,
output_file_path] |
15,991 | def _set_zone(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("zone_name",zone.zone, yang_name="zone", rest_name="zone", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {u: u, u: N... | Setter method for zone, mapped from YANG variable /zoning/defined_configuration/zone (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_zone is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_zone() dir... |
15,992 | def affine_shift_matrix(wrg=(-0.1, 0.1), hrg=(-0.1, 0.1), w=200, h=200):
if isinstance(wrg, tuple):
tx = np.random.uniform(wrg[0], wrg[1]) * w
else:
tx = wrg * w
if isinstance(hrg, tuple):
ty = np.random.uniform(hrg[0], hrg[1]) * h
else:
ty = hrg * h
shift_matrix... | Create an affine transform matrix for image shifting.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
wrg : float or tuple of floats
Range to shift on width axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the d... |
15,993 | def add_node(self, node_id, name, labels):
node = self.graph_db.get_or_create_indexed_node(, , node_id, {: node_id, : name})
try:
node.add_labels(*labels)
except NotImplementedError:
pass | Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported. |
15,994 | def create_function_f_i(self):
return ca.Function(
,
[self.t, self.x, self.y, self.m, self.p, self.c, self.pre_c, self.ng, self.nu],
[self.f_i],
[, , , , , , , , ], [], self.func_opt) | state reinitialization (reset) function |
15,995 | def UV_B(Bg,gw):
UV = []
p = Bwidth(gw)
pp = 2**p
while p:
pp = pp>>1
p = p-1
if Bg&pp:
uv = B012(p,gw-1)
UV.append(uv)
return UV | returns the implications UV based on B
Bg = B(g), g∈2^M
gw = |M|, M is the set of all attributes |
15,996 | def currentEvent(self):
t ended yet, or if there are no
future events, the last one to end.
startTime-endTime').first()
return currentEvent | Return the first event that hasn't ended yet, or if there are no
future events, the last one to end. |
15,997 | def get_matching_service_template_file(service_name, template_files):
if service_name in template_files:
return template_files[service_name]
return None | Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file. |
15,998 | def flags(rule_or_module, variable_name, condition, values = []):
assert isinstance(rule_or_module, basestring)
assert isinstance(variable_name, basestring)
assert is_iterable_typed(condition, basestring)
assert is_iterable(values) and all(isinstance(v, (basestring, type(None))) for v in values)
... | Specifies the flags (variables) that must be set on targets under certain
conditions, described by arguments.
rule_or_module: If contains dot, should be a rule name.
The flags will be applied when that rule is
used to set up build actions.
... |
15,999 | def NDLimitExceeded_NDLimit(self, **kwargs):
config = ET.Element("config")
NDLimitExceeded = ET.SubElement(config, "NDLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
NDLimit = ET.SubElement(NDLimitExceeded, "NDLimit")
NDLimit.text = kwargs.pop()
... | Auto Generated Code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.