Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
367,000 | def main():
arguments = docopt(__doc__, version=)
src_name = arguments[]
src_format = arguments[]
indent = arguments[]
if isinstance(indent, str) and indent.lower() == :
indent = None
elif isinstance(indent, str):
indent = int(indent)
else:
indent = 4
wit... | Get an info report for a tile. Format is same as input tile but with
min/max values for values under 'data'. |
367,001 | def init_app(self, app):
self.init_config(app)
if not in app.extensions:
Mail(app)
if app.config.get(, False) or app.debug:
email_dispatched.connect(print_email)
app.extensions[] = self | Flask application initialization.
The initialization will:
* Set default values for the configuration variables.
* Initialise the Flask mail extension.
* Configure the extension to avoid the email sending in case of debug
or ``MAIL_SUPPRESS_SEND`` config variable set. In ... |
367,002 | def _tarjan_head(ctx, v):
ctx.index[v] = len(ctx.index)
ctx.lowlink[v] = ctx.index[v]
ctx.S.append(v)
ctx.S_set.add(v)
it = iter(ctx.g.get(v, ()))
ctx.T.append((it,False,v,None)) | Used by @tarjan and @tarjan_iter. This is the head of the
main iteration |
367,003 | def htmlABF(ID,group,d,folder,overwrite=False):
fname=folder+"/swhlab4/%s_index.html"%ID
if overwrite is False and os.path.exists(fname):
return
html=TEMPLATES[]
html=html.replace("~ID~",ID)
html=html.replace("~CONTENT~",htmlABFcontent(ID,group,d))
print(" <- writing [%s]"%os.path.b... | given an ID and the dict of files, generate a static html for that abf. |
367,004 | def translate_file(
estimator, subtokenizer, input_file, output_file=None,
print_all_translations=True):
batch_size = _DECODE_BATCH_SIZE
sorted_inputs, sorted_keys = _get_sorted_inputs(input_file)
num_decode_batches = (len(sorted_inputs) - 1) // batch_size + 1
def input_generator():
... | Translate lines in file, and save to output file if specified.
Args:
estimator: tf.Estimator used to generate the translations.
subtokenizer: Subtokenizer object for encoding and decoding source and
translated lines.
input_file: file containing lines to translate
output_file: file that stores ... |
367,005 | def info(self):
return {: self._coordinates(),
: self._imageinfo(),
: self._miscinfo(),
: self._unit()
} | Get coordinates, image info, and unit". |
367,006 | def download_remote_script(url):
temp_fh = tempfile.NamedTemporaryFile(, encoding=, suffix=".py", delete=False)
downloader = _ScriptDownloader(url)
logger.info(
"Downloading remote script from %r using (%r downloader) to %r",
url, downloader.name, temp_fh.name)
content = downloader... | Download the content of a remote script to a local temp file. |
367,007 | def match(self, sentence, start=0, _v=None, _u=None):
if sentence.__class__.__name__ == "Sentence":
pass
elif isinstance(sentence, list) or sentence.__class__.__name__ == "Text":
return find(lambda m,s: m is not None, ((self.match(s, start, _v), s) for s in sentence))[0]... | Returns the first match found in the given sentence, or None. |
367,008 | def decode(self, encoded):
encoded = super().decode(encoded)
tokens = [self.itos[index] for index in encoded]
return self.detokenize(tokens) | Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``. |
367,009 | def max_projection(self, axis=2):
if axis >= size(self.value_shape):
raise Exception(
% (axis, 0, size(self.value_shape)-1))
new_value_shape = list(self.value_shape)
del new_value_shape[axis]
return self.map(lambda x: amax(x, axis), valu... | Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along. |
367,010 | def get_storage(self, id_or_uri):
uri = self.URI + "/{}/storage".format(extract_id_from_uri(id_or_uri))
return self._client.get(uri) | Get storage details of an OS Volume.
Args:
id_or_uri: ID or URI of the OS Volume.
Returns:
dict: Storage details |
367,011 | def execute(self):
self.print_info()
self._config.provisioner.converge()
self._config.state.change_state(, True) | Execute the actions necessary to perform a `molecule converge` and
returns None.
:return: None |
367,012 | def main():
parser = cli.Cli()
parser.parse(sys.argv[1:])
return parser.run() | Main entry point for the script. Create a parser, process the command line,
and run it |
367,013 | def state_angle(ket0: State, ket1: State) -> bk.BKTensor:
return fubini_study_angle(ket0.vec, ket1.vec) | The Fubini-Study angle between states.
Equal to the Burrs angle for pure states. |
367,014 | def _parse_tile_part_bit_stream(self, fptr, sod_marker, tile_length):
read_buffer = fptr.read(tile_length)
count = min(tile_length, len(read_buffer))
packet = np.frombuffer(read_buffer, dtype=np.uint8, count=count)
indices = np.where(packet == 0xff)
fo... | Parse the tile part bit stream for SOP, EPH marker segments. |
367,015 | def expectation(pyquil_prog: Program,
pauli_sum: Union[PauliSum, PauliTerm, np.ndarray],
samples: int,
qc: QuantumComputer) -> float:
if isinstance(pauli_sum, np.ndarray):
wf = WavefunctionSimulator().wavefunction(pyqu... | Compute the expectation value of pauli_sum over the distribution generated from pyquil_prog.
:param pyquil_prog: The state preparation Program to calculate the expectation value of.
:param pauli_sum: PauliSum representing the operator of which to calculate the expectation
value or a numpy m... |
367,016 | def p_created_1(self, p):
try:
if six.PY2:
value = p[2].decode(encoding=)
else:
value = p[2]
self.builder.set_created_date(self.document, value)
except CardinalityError:
self.more_than_one_error(, p.lineno(1)) | created : CREATED DATE |
367,017 | def parse_item(lines):
info = {}
for line in lines:
key, value = line.split(, 1)
if key in LIST_KEYS:
info.setdefault(key, []).append(value)
else:
assert key not in info
info[key] = value
if in info or in info:
yield info | Given the lines that form a subtag entry (after joining wrapped lines
back together), parse the data they contain.
Returns a generator that yields once if there was any data there
(and an empty generator if this was just the header). |
367,018 | def compute_training_sizes(train_perc, class_sizes, stratified=True):
size_per_class = np.int64(np.around(train_perc * class_sizes))
if stratified:
print("Different classes in training set are stratified to match smallest class!")
size_per_class = np.minimum(np.min(size_per_clas... | Computes the maximum training size that the smallest class can provide |
367,019 | def _close_and_clean(self, cleanup):
tasks = []
for node in self._nodes:
tasks.append(asyncio.async(node.manager.close_node(node.id)))
if tasks:
done, _ = yield from asyncio.wait(tasks)
for future in done:
try:
fu... | Closes the project, and cleanup the disk if cleanup is True
:param cleanup: Whether to delete the project directory |
367,020 | def section_path_lengths(neurites, neurite_type=NeuriteType.all):
dist = {}
neurite_filter = is_type(neurite_type)
for s in iter_sections(neurites, neurite_filter=neurite_filter):
dist[s] = s.length
def pl2(node):
return sum(dist[n] for n in node.iupst... | Path lengths of a collection of neurites |
367,021 | def _populate_issue(self, graph: TraceGraph, instance_id: int) -> None:
instance = graph._issue_instances[instance_id]
issue = graph._issues[instance.issue_id.local_id]
self._populate_shared_text(graph, instance.message_id)
self._populate_shared_text(graph, instance.filename_id)... | Adds an issue to the trace graph along with relevant information
pertaining to the issue (e.g. instance, fix_info, sources/sinks)
The issue is identified by its corresponding instance's ID in the input
trace graph. |
367,022 | def duration_to_string(duration):
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) | Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string |
367,023 | def _delete(self, obj, **kwargs):
if isinstance(obj, sqlalchemy.orm.query.Query):
obj = obj.one()
obj = self.preprocessing(obj=obj).delete()
self.session.delete(obj)
if kwargs.get(, self.commit) is True:
try:
self.session.commit()
... | Delete the object directly.
.. code-block:: python
DBSession.sacrud(Users)._delete(UserObj)
If you no needed commit session
.. code-block:: python
DBSession.sacrud(Users, commit=False)._delete(UserObj) |
367,024 | def check_assets(self):
if not self.assets_file:
raise ImproperlyConfigured("You must specify the path to the assets.json file via WEBPACK_ASSETS_FILE")
elif not os.path.exists(self.assets_file):
raise ImproperlyConfigured(
"The file `{file}` was not foun... | Throws an exception if assets file is not configured or cannot be found.
:param assets: path to the assets file |
367,025 | def waypoint_set_current_send(self, seq):
if self.mavlink10():
self.mav.mission_set_current_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_set_current_send(self.target_system, self.target_component, seq) | wrapper for waypoint_set_current_send |
367,026 | def show(self, xlim=None, ylim=None, units="thz"):
plt = self.get_plot(xlim, ylim, units=units)
plt.show() | Show the plot using matplotlib.
Args:
xlim: Specifies the x-axis limits. Set to None for automatic
determination.
ylim: Specifies the y-axis limits.
units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1. |
367,027 | def color_array_by_hue_mix(value, palette):
if int(value, 2) > 0:
int_list = [int(i) for i in list(value[2:])]
int_list.reverse()
locs = np.nonzero(int_list)[0]
rgb_vals = [palette[i] for i in locs]
rgb = [0]*len(r... | Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap. |
367,028 | def format_obj_name(obj, delim="<>"):
pname = ""
parent_name = get_parent_name(obj)
if parent_name:
pname = "{}{}{}".format(delim[0], get_parent_name(obj), delim[1])
return "{}{}".format(get_obj_name(obj), pname) | Formats the object name in a pretty way
@obj: any python object
@delim: the characters to wrap a parent object name in
-> #str formatted name
..
from vital.debug import format_obj_name
format_obj_name(vital.debug.Timer)
# -> 'Timer<vital.debug>'
... |
367,029 | def dump(self, obj, key=None):
if key is None:
key =
with preserve_current_directory():
self.__file.cd()
if sys.version_info[0] < 3:
pickle.Pickler.dump(self, obj)
else:
super(Pickler, self).dump(obj)
s... | Write a pickled representation of obj to the open TFile. |
367,030 | def gradients_X(self, dL_dK, X, X2=None):
if use_stationary_cython:
return self._gradients_X_cython(dL_dK, X, X2)
else:
return self._gradients_X_pure(dL_dK, X, X2) | Given the derivative of the objective wrt K (dL_dK), compute the derivative wrt X |
367,031 | def get(self, action, default=None):
try:
return self.__getitem__(action)
except KeyError as error:
return default | Returns given action value.
:param action: Action name.
:type action: unicode
:param default: Default value if action is not found.
:type default: object
:return: Action.
:rtype: QAction |
367,032 | def moveGamepadFocusToNeighbor(self, eDirection, ulFrom):
fn = self.function_table.moveGamepadFocusToNeighbor
result = fn(eDirection, ulFrom)
return result | Changes the Gamepad focus from one overlay to one of its neighbors. Returns VROverlayError_NoNeighbor if there is no
neighbor in that direction |
367,033 | def load_all(self, workers=None, limit=None, n_expected=None):
if not self.has_data:
self._preempt(True)
n_expected = 0
keys = tuple(self.delegate.keys())
if n_expected is not None and len(keys) < n_expected:
self._preempt(True)
... | Load all instances witih multiple threads.
:param workers: number of workers to use to load instances, which
defaults to what was given in the class initializer
:param limit: return a maximum, which defaults to no limit
:param n_expected: rerun the iteration on the data... |
367,034 | def get_whoami(self):
path = Client.urls[]
whoami = self._call(path, )
return whoami | A convenience function used in the event that you need to confirm that
the broker thinks you are who you think you are.
:returns dict whoami: Dict structure contains:
* administrator: whether the user is has admin privileges
* name: user name
* auth_backend: backend ... |
367,035 | def return_estimator(self):
estimator = self.base_learner_origin.return_estimator()
estimator = estimator.set_params(**self.hyperparameters)
return estimator | Returns base learner using its origin and the given hyperparameters
Returns:
est (estimator): Estimator object |
367,036 | def _sideral(date, longitude=0., model=, eop_correction=True, terms=106):
t = date.change_scale().julian_century
theta = 67310.54841 + (876600 * 3600 + 8640184.812866) * t + 0.093104 * t ** 2\
- 6.2e-6 * t ** 3
theta /= 240.
if model == :
theta += equinox(date, eop_cor... | Get the sideral time at a defined date
Args:
date (Date):
longitude (float): Longitude of the observer (in degrees)
East positive/West negative.
model (str): 'mean' or 'apparent' for GMST and GAST respectively
Return:
float: Sideral time in degrees
GMST: Greenwi... |
367,037 | def num_mode_groups(self):
num = self._libinput.libinput_device_tablet_pad_get_num_mode_groups(
self._handle)
if num < 0:
raise AttributeError()
return num | Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has_ring`
and :meth:`~libinput.de... |
367,038 | def p_im(p):
val = p[2].eval()
if val not in (0, 1, 2):
error(p.lineno(1), % val)
p[0] = None
return
p[0] = Asm(p.lineno(1), % val) | asm : IM expr |
367,039 | def istoken(docgraph, node_id, namespace=None):
if namespace is None:
namespace = docgraph.ns
return namespace+ in docgraph.node[node_id] | returns true, iff the given node ID belongs to a token node.
Parameters
----------
node_id : str
the node to be checked
namespace : str or None
If a namespace is given, only look for tokens in the given namespace.
Otherwise, look for tokens in the default namespace of the given
... |
367,040 | def serialize_oaipmh(self, pid, record):
root = etree.Element(
,
nsmap={
None: ,
: ,
: ,
},
attrib={
:
,
}
)
root.append(E.isReferenceQuality(self... | Serialize a single record for OAI-PMH. |
367,041 | def save(self, path):
writer = csv.writer(open(path, , newline=), delimiter=)
rows = list(self.items())
rows.sort(key=lambda x: x[0])
writer.writerows(rows) | Saves this catalogue's data to `path`.
:param path: file path to save catalogue data to
:type path: `str` |
367,042 | def _match(self, **kwargs):
for k in kwargs.keys():
try:
val = getattr(self, k)
except _a11y.Error:
return False
if sys.version_info[:2] <= (2, 6):
if isinstance(val, basestring):
if not... | Method which indicates if the object matches specified criteria.
Match accepts criteria as kwargs and looks them up on attributes.
Actual matching is performed with fnmatch, so shell-like wildcards
work within match strings. Examples:
obj._match(AXTitle='Terminal*')
obj._match(... |
367,043 | def url(self):
return self.get_url(server_url=self._session.server_url, pipeline_name=self.data.name) | Returns url for accessing pipeline entity. |
367,044 | def version(self, id, expand=None):
version = Version(self._options, self._session)
params = {}
if expand is not None:
params[] = expand
version.find(id, params=params)
return version | Get a version Resource.
:param id: ID of the version to get
:type id: str
:param expand: extra information to fetch inside each resource
:type expand: Optional[Any]
:rtype: Version |
367,045 | def start(self, work):
assert threading.current_thread() == threading.main_thread()
assert not self.state.running
self.state.running = True
self.thread = threading.Thread(target=work, args=(self.state,))
self.thread.start()
while self.state.running:
t... | Hand the main thread to the window and continue work in the provided
function. A state is passed as the first argument that contains a
`running` flag. The function is expected to exit if the flag becomes
false. The flag can also be set to false to stop the window event loop
and continue ... |
367,046 | def results_class_wise_average_metrics(self):
event_wise_results = self.results_class_wise_metrics()
event_wise_f_measure = []
event_wise_precision = []
event_wise_recall = []
event_wise_error_rate = []
event_wise_deletion_rate = []
event_wise_... | Class-wise averaged metrics
Returns
-------
dict
results in a dictionary format |
367,047 | def design_stat_cooling(self, value="Cooling"):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError(
.format(value))
if in value:
raise ValueError(... | Corresponds to IDD Field `design_stat_cooling`
Args:
value (str): value for IDD Field `design_stat_cooling`
Accepted values are:
- Cooling
Default value: Cooling
if `value` is None it will not be checked against the
... |
367,048 | async def unmount(self):
self._data = await self._handler.unmount(
system_id=self.node.system_id, id=self.id) | Unmount this block device. |
367,049 | def findXdk( self, name ):
for i in range(self.uiContentsTREE.topLevelItemCount()):
item = self.uiContentsTREE.topLevelItem(i)
if ( item.text(0) == name ):
return item
return None | Looks up the xdk item based on the current name.
:param name | <str>
:return <XdkItem> || None |
367,050 | def return_videos(self, begtime, endtime):
try:
self._orig[]
except KeyError:
raise OSError()
if not self._videos:
raise OSError()
mp4_file = self._videos[:1]
return mp4_file, begtime, endtime | It returns the videos and beginning and end time of the video
segment. The MFF video format is not well documented. As far as I can
see, the manual 20150805 says that there might be multiple .mp4 files
but I only see one .mov file (and no way to specify which video file to
read). In addi... |
367,051 | def add_dhcp_interface(self, interface_id, dynamic_index, zone_ref=None,
vlan_id=None, comment=None):
_interface = {: interface_id, : [{: [
{: True, : dynamic_index}], : vlan_id}],
: comment, : zone_ref}
if in self._engine.type:
_interfa... | Add a DHCP interface on a single FW
:param int interface_id: interface id
:param int dynamic_index: index number for dhcp interface
:param bool primary_mgt: whether to make this primary mgt
:param str zone_ref: zone reference, can be name, href or Zone
:raises EngineCommandFaile... |
367,052 | def set_updated(self):
output = []
for method in self.methods.values():
data = method["last_output"]
if isinstance(data, list):
if self.testing and data:
data[0]["cached_until"] = method.get("cached_until")
out... | Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status. |
367,053 | def _subtask_result(self, idx, value):
self._results[idx] = value
if len(self._results) == self._num_tasks:
self.set_result([
self._results[i]
for i in range(self._num_tasks)
]) | Receive a result from a single subtask. |
367,054 | def get_doc(project, source_code, offset, resource=None, maxfixes=1):
fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes)
pyname = fixer.pyname_at(offset)
if pyname is None:
return None
pyobject = pyname.get_object()
return PyDocExtractor().get_doc(pyobject) | Get the pydoc |
367,055 | def find_usage(self):
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim in self.limits.values():
lim._reset_usage()
self._find_cluster_manual_snapshots()
self._find_cluster_subnet_groups()
self._have_usage = True
... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. |
367,056 | def unrecognized_arguments_error(self, args, parsed, extras):
kwargs = vars(parsed)
failed = list(extras)
runtime, subparser, idx = (self, self.argparser, 0)
while isinstance(runtime, Runtime):
cmd = kwargs.pop(runtime.action_key)
... | This exists because argparser is dumb and naive and doesn't
fail unrecognized arguments early. |
367,057 | def remote_file_exists(self):
url = join(self.base_url, )
return super(AWSDownloader, self).remote_file_exists(url) | Verify whether the file (scene) exists on AWS Storage. |
367,058 | def _posterior(self, x):
yedge = self._nuis_pdf.marginalization_bins()
yc = 0.5 * (yedge[1:] + yedge[:-1])
yw = yedge[1:] - yedge[:-1]
like_array = self.like(x[:, np.newaxis], yc[np.newaxis, :]) * yw
like_array /= like_array.sum()
self._post = like_array.sum(1)... | Internal function to calculate and cache the posterior |
367,059 | def remove_stale_indexes_from_bika_catalog(portal):
logger.info("Removing stale indexes and metadata from bika_catalog ...")
cat_id = "bika_catalog"
indexes_to_remove = [
"getAnalyst",
"getAnalysts",
"getAnalysisService",
"getClientOrderNumber",
"getClientReferen... | Removes stale indexes and metadata from bika_catalog. Most of these
indexes and metadata were used for Samples, but they are no longer used. |
367,060 | def get_dataset(self, key, info):
logger.debug(.format(key.name))
if in key.name:
data = self.geo_data[]
elif in key.name:
data = self.geo_data[]
else:
tic = datetime.now()
data = self.calibrate(self.nc[].isel(time=0),
... | Load dataset designated by the given key from file |
367,061 | def locate(desktop_filename_or_name):
paths = [
os.path.expanduser(),
]
result = []
for path in paths:
for file in os.listdir(path):
if desktop_filename_or_name in file.split(
) or desktop_filename_or_name == file:
result.append(os.path.join(path, file))
else:
file_parsed = parse(... | Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the filename of a .desktop file or the name of... |
367,062 | def _get_channel_state_statelessly(self, grpc_channel, channel_id):
server = self._get_channel_state_from_server (grpc_channel, channel_id)
blockchain = self._get_channel_state_from_blockchain( channel_id)
if (server["current_nonce"] == blockchain["nonce"]):
... | We get state of the channel (nonce, amount, unspent_amount)
We do it by securely combine information from the server and blockchain
https://github.com/singnet/wiki/blob/master/multiPartyEscrowContract/MultiPartyEscrow_stateless_client.md |
367,063 | def privileges(
state, host,
user, privileges,
user_hostname=,
database=, table=,
present=True,
flush=True,
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
if isinstance(privileges, six.string_types):
privileges = [privileges]
i... | Add/remove MySQL privileges for a user, either global, database or table specific.
+ user: name of the user to manage privileges for
+ privileges: list of privileges the user should have
+ user_hostname: the hostname of the user
+ database: name of the database to grant privileges to (defaults to all)
... |
367,064 | def create_server(AssociatePublicIpAddress=None, DisableAutomatedBackup=None, Engine=None, EngineModel=None, EngineVersion=None, EngineAttributes=None, BackupRetentionCount=None, ServerName=None, InstanceProfileArn=None, InstanceType=None, KeyPair=None, PreferredMaintenanceWindow=None, PreferredBackupWindow=None, Secur... | Creates and immedately starts a new server. The server is ready to use when it is in the HEALTHY state. By default, you can create a maximum of 10 servers.
This operation is asynchronous.
A LimitExceededException is thrown when you have created the maximum number of servers (10). A ResourceAlreadyExistsExceptio... |
367,065 | def make_operatorsetid(
domain,
version,
):
operatorsetid = OperatorSetIdProto()
operatorsetid.domain = domain
operatorsetid.version = version
return operatorsetid | Construct an OperatorSetIdProto.
Arguments:
domain (string): The domain of the operator set id
version (integer): Version of operator set id |
367,066 | def to_OrderedDict(self, include_null=True):
if include_null:
return OrderedDict(self.items())
else:
items = list()
for c in self.__table__._columns:
try:
items.append((c.name, self.__dict__[c.name]))
except... | Convert to OrderedDict. |
367,067 | def entries(self):
passwords = []
for store in self.stores:
passwords.extend(store.entries)
return natsort(passwords, key=lambda e: e.name) | A list of :class:`PasswordEntry` objects. |
367,068 | def _fromJSON(cls, jsonobject):
newInstance = cls(None, None)
newInstance.__dict__.update(jsonobject)
return newInstance | Generates a new instance of :class:`maspy.core.Si` from a decoded
JSON object (as generated by :func:`maspy.core.Si._reprJSON()`).
:param jsonobject: decoded JSON object
:returns: a new instance of :class:`Si` |
367,069 | def load_script(zap_helper, **options):
with zap_error_handler():
if not os.path.isfile(options[]):
raise ZAPError(.format(options[]))
if not _is_valid_script_engine(zap_helper.zap, options[]):
engines = zap_helper.zap.script.list_engines
raise ZAPError(.for... | Load a script from a file. |
367,070 | def pop(self, queue_name):
self._only_watch_from(queue_name)
job = self.conn.reserve(timeout=0)
job.delete()
return job.body | Pops a task off the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:returns: The data for the task.
:rtype: string |
367,071 | def font_to_wx_font(font):
if font is None:
return
if type(font) is str:
_font = font.split()
else:
_font = font
name = _font[0]
family = _font[0]
point_size = int(_font[1])
underline = in _font[2:]
bold = in _font
wxfont = wx.Font(point_si... | Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings |
367,072 | def dump_data(data,
filename=None,
file_type=,
klazz=YapconfError,
open_kwargs=None,
dump_kwargs=None):
_check_file_type(file_type, klazz)
open_kwargs = open_kwargs or {: }
dump_kwargs = dump_kwargs or {}
if filename:
... | Dump data given to file or stdout in file_type.
Args:
data (dict): The dictionary to dump.
filename (str, optional): Defaults to None. The filename to write
the data to. If none is provided, it will be written to STDOUT.
file_type (str, optional): Defaults to 'json'. Can be any of
... |
367,073 | def coordinate_reproject(x, y, s_crs, t_crs):
source = crsConvert(s_crs, )
target = crsConvert(t_crs, )
transform = osr.CoordinateTransformation(source, target)
point = transform.TransformPoint(x, y)[:2]
return point | reproject a coordinate from one CRS to another
Parameters
----------
x: int or float
the X coordinate component
y: int or float
the Y coordinate component
s_crs: int, str or :osgeo:class:`osr.SpatialReference`
the source CRS. See :func:`~spatialist.auxil.crsConvert` for ... |
367,074 | def rebalance(self):
if self.args.num_gens < self.args.max_partition_movements:
self.log.warning(
"num-gens ({num_gens}) is less than max-partition-movements"
" ({max_partition_movements}). max-partition-movements will"
" never be reached.".fo... | The genetic rebalancing algorithm runs for a fixed number of
generations. Each generation has two phases: exploration and pruning.
In exploration, a large set of possible states are found by randomly
applying assignment changes to the existing states. In pruning, each
state is given a sc... |
367,075 | def present(name,
user=None,
password=None,
auth=,
encoding=,
locale=None,
runas=None,
waldir=None,
checksums=False):
_cmt = .format(name)
ret = {
: name,
: {},
: True,
: _cmt}
if not __salt__[](name=name):... | Initialize the PostgreSQL data directory
name
The name of the directory to initialize
user
The database superuser name
password
The password to set for the postgres user
auth
The default authentication method for local connections
encoding
The default enc... |
367,076 | def is_parent_of_family(self, id_, family_id):
if self._catalog_session is not None:
return self._catalog_session.is_parent_of_catalog(id_=id_, catalog_id=family_id)
return self._hierarchy_session.is_parent(id_=family_id, parent_id=id_) | Tests if an ``Id`` is a direct parent of a family.
arg: id (osid.id.Id): an ``Id``
arg: family_id (osid.id.Id): the ``Id`` of a family
return: (boolean) - ``true`` if this ``id`` is a parent of
``family_id,`` ``false`` otherwise
raise: NotFound - ``family_id`` is... |
367,077 | def set_static_ip_address(self, context, msg):
args = jsonutils.loads(msg)
macaddr = args.get()
ipaddr = args.get()
LOG.debug(, (
{: macaddr, : ipaddr}))
event_type =
payload = {: macaddr, : ipaddr}
timestamp = time.ctime()
... | Process request for setting rules in iptables.
In cases that static ip address is assigned for a VM, it is needed
to update the iptables rule for that address. |
367,078 | def set_filetype(self, filetype, bufnr=None):
if bufnr:
self._vim.command(str(bufnr) + + filetype)
else:
self._vim.command( + filetype) | Set filetype for a buffer.
Note: it's a quirk of Vim's Python API that using the buffer.options
dictionary to set filetype does not trigger ``FileType`` autocommands,
hence this implementation executes as a command instead.
Args:
filetype (str): The filetype to set.
... |
367,079 | def _check_row_table_name(table_name, row):
if row.table is not None and row.table.name != table_name:
raise TableMismatchError(
"Row %s is a part of %s table. Current table: %s"
% (row.row_key, row.table.name, table_name)
) | Checks that a row belongs to a table.
:type table_name: str
:param table_name: The name of the table.
:type row: :class:`~google.cloud.bigtable.row.Row`
:param row: An instance of :class:`~google.cloud.bigtable.row.Row`
subclasses.
:raises: :exc:`~.table.TableMismatchError` if the... |
367,080 | def maskAt(self, index):
if isinstance(self.mask, bool):
return self.mask
else:
return self.mask[index] | Returns the mask at the index.
It the mask is a boolean it is returned since this boolean representes the mask for
all array elements. |
367,081 | def froze_it(cls):
cls._frozen = False
def frozensetattr(self, key, value):
if self._frozen and not hasattr(self, key):
raise AttributeError("Attribute of class does not exist!"
.format(key, cls.__name__))
else:
object.__setattr__(self, ... | Decorator to prevent from creating attributes in the object ouside __init__().
This decorator must be applied to the final class (doesn't work if a
decorated class is inherited).
Yoann's answer at http://stackoverflow.com/questions/3603502 |
367,082 | def getoutputfiles(self, loadmetadata=True, client=None,requiremetadata=False):
for outputfilename, outputtemplate in self.outputpairs():
yield CLAMOutputFile(self.projectpath, outputfilename, loadmetadata,client,requiremetadata), outputtemplate | Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor. |
367,083 | def warning_handler(self, handler):
if not self.opened():
handler = handler or util.noop
self._warning_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)
self._dll.JLINKARM_SetWarnOutHandler(self._warning_handler) | Setter for the warning handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on warning messages
Returns:
``None`... |
367,084 | def yield_for_all_futures(result):
while True:
if result is None:
break
try:
future = gen.convert_yielded(result)
except gen.BadYieldError:
break
else:
result = yield future
raise gen.Return(re... | Converts result into a Future by collapsing any futures inside result.
If result is a Future we yield until it's done, then if the value inside
the Future is another Future we yield until it's done as well, and so on. |
367,085 | def _cpu(self):
value = int(psutil.cpu_percent())
set_metric("cpu", value, category=self.category)
gauge("cpu", value) | Record CPU usage. |
367,086 | def input_streams(self):
streams = []
for walker, _trigger in self.inputs:
if walker.selector is None or not walker.selector.singular:
continue
streams.append(walker.selector.as_stream())
return streams | Return a list of DataStream objects for all singular input streams.
This function only returns individual streams, not the streams that would
be selected from a selector like 'all outputs' for example.
Returns:
list(DataStream): A list of all of the individual DataStreams that are ... |
367,087 | def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None, url=None):
try:
audio = EasyMP3(filename)
audio.tags = None
audio["artist"] = artist
audio["title"] = title
if year:
audio["date"] = str(year)
... | Attempt to put ID3 tags on a file.
Args:
artist (str):
title (str):
year (int):
genre (str):
artwork_url (str):
album (str):
track_number (str):
filename (str):
url (str): |
367,088 | def num2hexstring(number, size=1, little_endian=False):
size = size * 2
hexstring = hex(number)[2:]
if len(hexstring) % size != 0:
hexstring = ( * size + hexstring)[len(hexstring):]
if little_endian:
hexstring = reverse_hex(hexstring)
return hexstring | Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endian - Encode the hex in little endian form
:return {string} |
367,089 | def deriv(self, p):
return self.power * np.power(p, self.power - 1) | Derivative of the power transform
Parameters
----------
p : array-like
Mean parameters
Returns
--------
g'(p) : array
Derivative of power transform of `p`
Notes
-----
g'(`p`) = `power` * `p`**(`power` - 1) |
367,090 | def plot(self, numPoints=100):
fig = plt.figure()
ax = fig.add_subplot(111, projection=)
x = np.linspace(- self.radius, self.radius, numPoints)
z = np.linspace(- self.height / 2., self.height / 2., numPoints)
Xc, Zc = np.meshgrid(x, z)
Yc = np.sqrt(self.radius ** 2 - Xc ** 2)
... | Specific plotting method for cylinders. |
367,091 | def variable(self, var_name, shape, init, dt=tf.float32, train=None):
dt = tf.as_dtype(dt).base_dtype
if var_name in self.vars:
v = self.vars[var_name]
if v.get_shape() != shape:
raise ValueError(
% (v.get_shape(), shape))
return v
elif callable(... | Adds a named variable to this bookkeeper or returns an existing one.
Variables marked train are returned by the training_variables method. If
the requested name already exists and it is compatible (same shape, dt and
train) then it is returned. In case of an incompatible type, an exception is
thrown.
... |
367,092 | def cols_to_numeric(df, col_list,dest = False):
if not dest:
return _pd.DataFrame({col_name:col_to_numeric(df,col_name) for col_name in col_list})
for col_name in col_list:
col_to_numeric(df,col_name,dest) | Coerces a list of columns to numeric
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
367,093 | def read_name(self):
result =
off = self.offset
next = -1
first = off
while 1:
len = ord(self.data[off])
off += 1
if len == 0:
break
t = len & 0xC0
if t == 0x00:
result = .join(... | Reads a domain name from the packet |
367,094 | def sync_handler(self, args):
t provide delete operation.
cmd|s3,local|s3,local', args)
source = args[1]
target = args[2]
self.s3handler().sync_files(source, target) | Handler for sync command.
XXX Here we emulate sync command with get/put -r -f --sync-check. So
it doesn't provide delete operation. |
367,095 | def best_structures(uniprot_id, outname=None, outdir=None, seq_ident_cutoff=0.0, force_rerun=False):
outfile =
if not outdir:
outdir =
if not outname and outdir:
outname = uniprot_id
if outname:
outname = op.join(outdir, outname)
outfile = .format(outname)
... | Use the PDBe REST service to query for the best PDB structures for a UniProt ID.
More information found here: https://www.ebi.ac.uk/pdbe/api/doc/sifts.html
Link used to retrieve results: https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/:accession
The list of PDB structures mapping to a UniProt acces... |
367,096 | def get_intent(self,
name,
language_code=None,
intent_view=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
if ... | Retrieves the specified intent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.IntentsClient()
>>>
>>> name = client.intent_path('[PROJECT]', '[INTENT]')
>>>
>>> response = client.get_intent(name)
Arg... |
367,097 | def _Open(self, path_spec, mode=):
if not path_spec.HasParent():
raise errors.PathSpecError(
)
if path_spec.parent.type_indicator != (
definitions.TYPE_INDICATOR_APFS_CONTAINER):
raise errors.PathSpecError(
)
apfs_container_file_system = resolver.Resolver.OpenF... | Opens the file system defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the APFS volume could not be retrieved or unlocked.
OSError: if... |
367,098 | def rename_pickled_ontology(filename, newname):
pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle"
newpickledfile = ONTOSPY_LOCAL_CACHE + "/" + newname + ".pickle"
if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE:
os.rename(pickledfile, newpickledfile)
return True
else:
return None | try to rename a cached ontology |
367,099 | def dirname(hdfs_path):
scheme, netloc, path = parse(hdfs_path)
return unparse(scheme, netloc, os.path.dirname(path)) | Return the directory component of ``hdfs_path``. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.