Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,500 | def prepare_metadata(devkit_archive, test_groundtruth_path):
return n_train, valid_groundtruth, test_groundtruth, wnid_map | Extract dataset metadata required for HDF5 file setup.
Parameters
----------
devkit_archive : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2010 development kit.
test_groundtruth_path : str or file-like object
The filename o... |
360,501 | def configure_default_logger(
self,
log_freq=,
log_total=30,
log_level=,
log_format=ReportingFormats.DEFAULT.value,
custom_args=
):
log_freq = self.config.get_option(
, ,
None, log_freq
... | default logger that every Prosper script should use!!
Args:
log_freq (str): TimedRotatingFileHandle_str -- https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler
log_total (int): how many log_freq periods between log rotations
log_level (str): minim... |
360,502 | def flush(self):
while not self._queue.empty():
self._queue.get()
self._queue.task_done()
self.close() | Erases queue and set `end-of-queue` message. |
360,503 | def intersect(self, other):
if self.overlaps(other):
newlower_value = max(self.lower_value, other.lower_value)
new_upper_value = min(self._upper_value, other._upper_value)
new_lower, new_upper = self._get_new_lower_upper(other, self.intersect)
return Inte... | Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval`
with the other :class:`~pyinter.Interval` |
360,504 | def perform_evaluation(self):
if not self.max_effect_length:
return []
edge = cadquery.Edge.makeLine(
self.location.origin,
self.location.origin + (self.location.zDir * -(self.max_effect_length + 1))
)
wire = cadquery.W... | Determine which parts lie along the given vector, and what length
:return: effects on the given parts (in order of the distance from
the start point)
:rtype: list(:class:`VectorEffect`) |
360,505 | def _process_docs(self, anexec, docblocks, parent, module, docsearch):
key = "{}.{}".format(parent.name, anexec.name)
if key in docblocks:
docs = self.docparser.to_doc(docblocks[key][0], anexec.name)
anexec.docstart, anexec.docend = (docblocks[key][1], ... | Associates the docstrings from the docblocks with their parameters. |
360,506 | def _parse_retry_after(self, response):
value = response.headers.get()
if not value:
seconds = 0
elif re.match(r, value):
seconds = int(value)
else:
date_tuple = email.utils.parsedate(value)
if date_tuple is None:
... | Parse Retry-After header from response if it is set. |
360,507 | def index_item(self, item):
name_property = getattr(self.__class__, "name_property", None)
if name_property is None:
return None
name = getattr(item, name_property, None)
if name is None:
item.add_error("a %s item has been defined without %s, from: %s"
... | Index an item into our `name_to_item` dictionary.
If an object holding the same item's name/key already exists in the index
then the conflict is managed by the `manage_conflict` method.
:param item: item to index
:type item: alignak.objects.item.Item
:return: item modified
... |
360,508 | def seek_monotonic(self, monotonic, bootid=None):
if isinstance(monotonic, _datetime.timedelta):
monotonic = monotonic.total_seconds()
monotonic = int(monotonic * 1000000)
if isinstance(bootid, _uuid.UUID):
bootid = bootid.hex
return super(Reader, self).s... | Seek to a matching journal entry nearest to `monotonic` time.
Argument `monotonic` is a timestamp from boot in either seconds or a
datetime.timedelta instance. Argument `bootid` is a string or UUID
representing which boot the monotonic time is reference to. Defaults to
current bootid. |
360,509 | def _parse_game_date_and_location(self, boxscore):
scheme = BOXSCORE_SCHEME[]
items = [i.text() for i in boxscore(scheme).items()]
game_info = items[0].split()
time =
date =
stadium =
for line in game_info:
time_match = re.findall(r, line.l... | Retrieve the game's date and location.
The date and location of the game follow a more complicated parsing
scheme and should be handled differently from other tags. Both fields
are separated by a newline character ('\n') with the first line being
the date and the second being the locati... |
360,510 | async def pause_writing(self):
self._restart_writer = False
if self._writer_task:
self._writer_task.remove_done_callback(self.restart_writing)
self._writer_task.cancel()
await self._writer_task
await asyncio.sleep(0, loop=self._loop) | Pause writing. |
360,511 | def forget(self, *keys):
keys = reversed(sorted(keys))
for key in keys:
del self[key]
return self | Remove an item from the collection by key.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection |
360,512 | def spia_matrices_to_excel(spia_matrices: Mapping[str, pd.DataFrame], path: str) -> None:
writer = pd.ExcelWriter(path, engine=)
for relation, df in spia_matrices.items():
df.to_excel(writer, sheet_name=relation, index=False)
writer.save() | Export a SPIA data dictionary into an Excel sheet at the given path.
.. note::
# The R import should add the values:
# ["nodes"] from the columns
# ["title"] from the name of the file
# ["NumberOfReactions"] set to "0" |
360,513 | def generateIdentityKeyPair():
keyPair = Curve.generateKeyPair()
publicKey = IdentityKey(keyPair.getPublicKey())
serialized = \
\
serialized = binascii.unhexlify(serialized.encode())
identityKeyPair = IdentityKeyPair(publicKey... | Generate an identity key pair. Clients should only do this once,
at install time.
@return the generated IdentityKeyPair. |
360,514 | def set_json(self, config_json):
if self.configuration_dict is not None:
raise RuntimeError("Can only set configuration once", self.configuration_dict)
schema = fetch_config()
validictory.validate(config_json, schema)
config_json[] = self.name
config_json[... | Permanently set the JSON configuration
Unable to call twice. |
360,515 | def delete_database(self, name_or_obj):
name = utils.get_name(name_or_obj)
self._database_manager.delete(name) | Deletes the specified database. If no database by that name
exists, no exception will be raised; instead, nothing at all
is done. |
360,516 | def addinputfile(self, project, inputtemplate, sourcefile, **kwargs):
if isinstance( inputtemplate, str) or (sys.version < and isinstance( inputtemplate, unicode)):
data = self.get(project)
inputtemplate = data.inputtemplate(inputtemplate)
elif not isinstance(inputtem... | Add/upload an input file to the CLAM service. Supports proper file upload streaming.
project - the ID of the project you want to add the file to.
inputtemplate - The input template you want to use to add this file (InputTemplate instance)
sourcefile - The file you want to add: string containing... |
360,517 | def _translate_src_oprnd(self, operand):
if isinstance(operand, ReilRegisterOperand):
return self._translate_src_register_oprnd(operand)
elif isinstance(operand, ReilImmediateOperand):
return smtsymbol.Constant(operand.size, operand.immediate)
else:
r... | Translate source operand to a SMT expression. |
360,518 | def scan(self, filetypes=None):
self.logger.debug("Scanning FS content.")
checksums = self.filetype_filter(self._filesystem.checksums(),
filetypes=filetypes)
self.logger.debug("Querying %d objects to VTotal.", len(checksums))
for files ... | Iterates over the content of the disk and queries VirusTotal
to determine whether it's malicious or not.
filetypes is a list containing regular expression patterns.
If given, only the files which type will match with one or more of
the given patterns will be queried against VirusTotal.
... |
360,519 | def quick_search(self, name, platform=None, sort_by=None, desc=True):
if platform is None:
query_filter = "name:{0}".format(name)
else:
query_filter = "name:{0},platforms:{1}".format(name, platform)
search_params = {"filter": query_filter}
if sort_by is... | Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:return: pybomb.clients.Response |
360,520 | def progressbar(total, pos, msg=""):
width = get_terminal_size()[0] - 40
rel_pos = int(float(pos) / total * width)
bar = .join(["=" * rel_pos, "." * (width - rel_pos)])
digits_total = len(str(total))
fmt_width = "%0" + str(digits_total) + "d"
fmt = "\r[" + fmt_width + "/" + fmt_width ... | Given a total and a progress position, output a progress bar
to stderr. It is important to not output anything else while
using this, as it relies soley on the behavior of carriage
return (\\r).
Can also take an optioal message to add after the
progressbar. It must not contain newlines.
The pr... |
360,521 | def lower_case(f):
if hasattr(f, "lower_cased"):
return f
@wraps(f)
def wrapper(*args, **kwargs):
f.lower_cased = True
return f(*args, **kwargs).lower()
return wrapper | Decorator specifically for turning mssql AST into lowercase |
360,522 | def parse(self):
self._parse(self.method)
return list(set([deco for deco in self.decos if deco])) | Return the list of string of all the decorators found |
360,523 | def get_cfn_attribute(self, attribute_name):
from moto.cloudformation.exceptions import UnformattedGetAttTemplateException
not_implemented_yet = [
,
,
,
]
if attribute_name == :
return self.dns_name
elif attribute_name == :... | Implemented attributes:
* DNSName
* LoadBalancerName
Not implemented:
* CanonicalHostedZoneID
* LoadBalancerFullName
* SecurityGroups
This method is similar to models.py:FakeLoadBalancer.get_cfn_attribute() |
360,524 | def copy(src, trg, transform=None):
source = open(src[0], src[1])
target = open(trg[0], trg[1], autocommit=1000)
for item in source.get():
item = dict(item)
if in item:
del item[]
if transform:
item = transform(item)
target.put(trg[0](item))
... | copy items with optional fields transformation |
360,525 | def _add_skyline(self, rect):
skylineq = collections.deque([])
for sky in self._skyline:
if sky.right <= rect.left or sky.left >= rect.right:
self._merge_skyline(skylineq, sky)
continue
if sky.left < rect.left and sky.right > re... | Arguments:
seg (Rectangle): |
360,526 | def on_response(self, ch, method, props, body):
logger.info("on response => {}".format(body))
corr_id = props.correlation_id
self.accept(corr_id, body) | All RPC response will call this method, so change the isAccept to True in this method
所有的RPC请求回调都会调用该方法,在该方法内修改对应corr_id已经接受消息的isAccept值和返回结果 |
360,527 | def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]:
E0 = np.atleast_1d(E0)
Q0 = np.atleast_1d(Q0)
assert E0.ndim == Q0.ndim == 1
assert (Q0.size == 1 or Q0.size == E0.size)
Phi = Q0/(2*pi*E0**3) * E[:, None] * np.exp(-E[:, None]/E0)
Q = np.trapz(Phi,... | input:
------
E: 1-D vector of energy bins [eV]
E0: characteristic energy (scalar or vector) [eV]
Q0: flux coefficient (scalar or vector) (to yield overall flux Q)
output:
-------
Phi: differential number flux
Q: total flux
Tanaka 2006 Eqn. 1
http://odin.gi.alaska.edu/lumm/Pape... |
360,528 | def default_pixmap(self, value):
if value is not None:
assert type(value) is QPixmap, " attribute: type is not !".format(
"default_pixmap", value)
self.__default_pixmap = value | Setter for **self.__default_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap |
360,529 | def append(self, key, value):
self.__items.append((key, value))
try:
dict_getitem(self, key).append(value)
except KeyError:
dict_setitem(self, key, [value]) | Adds a (name, value) pair, doesn't overwrite the value if it already
exists. |
360,530 | def influx_count_(self, measurement):
try:
q = "select count(*) from " + measurement
self.start("Querying: count ...")
datalen = self.influx_cli.query(q)
self.end("Finished querying")
numrows = int(datalen[measurement][datalen[measurement].key... | Count the number of rows for a measurement |
360,531 | def with_columns(self, *labels_and_values):
if len(labels_and_values) == 1:
labels_and_values = labels_and_values[0]
if isinstance(labels_and_values, collections.abc.Mapping):
labels_and_values = list(labels_and_values.items())
if not isinstance(labels_and_values... | Return a table with additional or replaced columns.
Args:
``labels_and_values``: An alternating list of labels and values or
a list of label-value pairs. If one of the labels is in
existing table, then every value in the corresponding column is
set t... |
360,532 | def join_key_value(key, value, separator=):
r
return escape(key) \
+ separator \
+ re.sub(r, lambda m: r * m.end(), _base_escape(value)) | r"""
Join a key and value together into a single line suitable for adding to a
simple line-oriented ``.properties`` file. No trailing newline is added.
>>> join_key_value('possible separators', '= : space')
'possible\\ separators=\\= \\: space'
:param key: the key
:type key: text string
:... |
360,533 | def get_question(self, number: str=None) -> dict:
try:
response = self.__session.get(
self.__url + , timeout=0.5, verify=False)
soup = BeautifulSoup(response.text, )
questions = {}
for tag in soup.find_all():
... | 取得課程中的所有題目資訊 |
360,534 | def _is_finished_dumping(directory):
run_info = os.path.join(directory, "RunInfo.xml")
hi_seq_checkpoint = "Basecalling_Netcopy_complete_Read%s.txt" % \
_expected_reads(run_info)
to_check = ["Basecalling_Netcopy_complete_SINGLEREAD.txt",
"Basecalli... | Determine if the sequencing directory has all files.
The final checkpoint file will differ depending if we are a
single or paired end run. |
360,535 | def fetchall(self):
if self._state == self._STATE_NONE:
raise Exception("No query yet")
if not self._data:
return []
else:
result, self._data = self._data, []
self._rownumber += len(result)
return result | Fetch all (remaining) rows of a query result, returning them as a sequence of sequences
(e.g. a list of tuples). |
360,536 | def remove_router_from_hosting_device(self, client, hosting_device_id,
router_id):
res_path = hostingdevice.HostingDevice.resource_path
return client.delete((res_path + DEVICE_L3_ROUTERS + "/%s") % (
hosting_device_id, router_id)) | Remove a router from hosting_device. |
360,537 | def add_reads(self, reads):
if len(reads) == 0:
return self
new_reads = self.reads.union(reads)
if len(new_reads) > len(self.reads):
return VariantSequence(
prefix=self.prefix,
alt=self.alt,
suffix=self.suffix,
... | Create another VariantSequence with more supporting reads. |
360,538 | def create_thumb(self):
thumbnail_figure = self.copy_thumbnail_figure()
if thumbnail_figure is not None:
if isinstance(thumbnail_figure, six.string_types):
pic = thumbnail_figure
else:
pic = self.pictures[thumbnail_figure]
self... | Create the thumbnail for html output |
360,539 | def get_weather_forecast(self, latitude, longitude, start, end,
frequency=1, reading_type=None):
params = {}
if frequency not in [1, 3]:
raise ValueError("Reading frequency must be 1 or 3")
params[] = + str(frequency)
params[] = latit... | Return the weather forecast for a given location for specific
datetime specified in UTC format.
::
results = ws.get_weather_forecast(lat, long, start, end)
for w in results['hits']:
print w['start_datetime_local']
print w['reading_type'], '=', w[... |
360,540 | def evalall(self, loc=None, defaults=None):
self.check()
if defaults is None:
defaults = cma_default_options
if in loc:
popsize = self(, defaults[], loc)
for k in list(self.keys()):
k = self.corrected_key(k)
... | Evaluates all option values in environment `loc`.
:See: `eval()` |
360,541 | def aes_ecb_decrypt(self, key_handle, ciphertext):
return pyhsm.aes_ecb_cmd.YHSM_Cmd_AES_ECB_Decrypt( \
self.stick, key_handle, ciphertext).execute() | AES ECB decrypt using a key handle.
@warning: Please be aware of the known limitations of AES ECB mode before using it!
@param key_handle: Key handle to use for AES ECB decryption
@param ciphertext: Data to decrypt
@type key_handle: integer or string
@type ciphertext: string
... |
360,542 | def get_user_data_iobject(user=None,group=None,data_kind=DINGOS_USER_DATA_TYPE_NAME):
logger.debug("Get user settings called")
if not user.is_authenticated():
user = None
try:
user_config = UserData.objects.get(user=user,group=group,data_kind=data_kind)
... | Returns either stored settings of a given user or default settings.
This behavior reflects the need for views to have some settings at
hand when running. The settings are returned as dict object. |
360,543 | def get_sockinfo (host, port=None):
family, socktype = socket.AF_INET, socket.SOCK_STREAM
return socket.getaddrinfo(host, port, family, socktype) | Return socket.getaddrinfo for given host and port. |
360,544 | def add_chain(self, group_name, component_map):
self.assert_writeable()
for component, path in component_map.items():
if not path.startswith():
path = .format(path)
component_map[component] = path
self.add_analysis_attributes(group_name, compone... | Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The set of components and corresponding
group names or group p... |
360,545 | def parse_variant_playlist(cls, session_, url, name_key="name",
name_prefix="", check_streams=False,
force_restart=False, name_fmt=None,
start_offset=0, duration=None,
**request_params):
... | Attempts to parse a variant playlist and return its streams.
:param url: The URL of the variant playlist.
:param name_key: Prefer to use this key as stream name, valid keys are:
name, pixels, bitrate.
:param name_prefix: Add this prefix to the stream names.
:par... |
360,546 | def write(self, filename=None, output="dict", attribute_indent=4):
if filename is not None:
location = path_expand(filename)
else:
location = self[][]
self.make_a_copy(location)
f = os.open(location, os.O_CREAT | os.O... | This method writes the dict into various output formats. This includes a dict,
json, and yaml
:param filename: the file in which the dict is written
:param output: is a string that is either "dict", "json", "yaml"
:param attribute_indent: character indentation of nested attributes in |
360,547 | def jupytext_cli(args=None):
try:
jupytext(args)
except (ValueError, TypeError, IOError) as err:
sys.stderr.write( + str(err) + )
exit(1) | Entry point for the jupytext script |
360,548 | def _shift_headings(self, content: str, shift: int) -> str:
def _sub(heading):
new_heading_level = len(heading.group()) + shift
self.logger.debug(f)
if new_heading_level <= 6:
return f
else:
self.logger.debug()
... | Shift Markdown headings in a string by a given value. The shift can
be positive or negative.
:param content: Markdown content
:param shift: Heading shift
:returns: Markdown content with headings shifted by ``shift`` |
360,549 | def from_elan(cls: Type[CorpusT], org_dir: Path, tgt_dir: Path,
feat_type: str = "fbank", label_type: str = "phonemes",
utterance_filter: Callable[[Utterance], bool] = None,
label_segmenter: Optional[LabelSegmenter] = None,
speakers: List[str] = No... | Construct a `Corpus` from ELAN files.
Args:
org_dir: A path to the directory containing the unpreprocessed
data.
tgt_dir: A path to the directory where the preprocessed data will
be stored.
feat_type: A string describing the input speech featu... |
360,550 | def print_line(line):
sys.__stdout__.write("{}\n".format(line))
sys.__stdout__.flush() | Print given line to stdout (i3bar). |
360,551 | def add_remote_provider(self, provider, client, path):
if provider not in constants.SUPPORTED_REMOTE_PROVIDERS:
raise errors.UnsupportedRemoteProviderError(provider)
host = ""
if provider == "etcd":
host = "{0}://{1}:{2}".format(client.protocol, client.host,
... | Adds a remote configuration source.
Remote Providers are searched in the order they are added.
provider is a string value, "etcd", "consul" and "zookeeper" are
currently supported.
client is a client object
path is the path in the k/v store to retrieve configuration
To re... |
360,552 | def get_instance(self, payload):
return AuthCallsCredentialListMappingInstance(
self._version,
payload,
account_sid=self._solution[],
domain_sid=self._solution[],
) | Build an instance of AuthCallsCredentialListMappingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.auth_calls_credential_list_mapping.AuthCallsCredentialListMappingInstance
:rtype: twilio.rest.api.v201... |
360,553 | def bounding_box(self):
w2 = self.width / 2.
h2 = self.height / 2.
cos_angle = np.cos(self.angle)
sin_angle = np.sin(self.angle)
dx1 = abs(w2 * cos_angle - h2 * sin_angle)
dy1 = abs(w2 * sin_angle + h2 * cos_angle)
dx2 = abs(w2 * cos_angle + h2 *... | The minimal bounding box (`~regions.BoundingBox`) enclosing the
exact rectangular region. |
360,554 | def _stream_search(self, query):
for doc in self.solr.search(query, rows=100000000):
if self.unique_key != "_id":
doc["_id"] = doc.pop(self.unique_key)
yield doc | Helper method for iterating over Solr search results. |
360,555 | def write_file(self, filename, distance=6, velocity=8, charge=3):
with open(filename, "w") as f:
f.write(self.get_string(distance=distance, velocity=velocity,
charge=charge)) | Writes LammpsData to file.
Args:
filename (str): Filename.
distance (int): No. of significant figures to output for
box settings (bounds and tilt) and atomic coordinates.
Default to 6.
velocity (int): No. of significant figures to output for
... |
360,556 | def visit_ImportFrom(self, node):
if node.level:
raise PythranSyntaxError("Relative import not supported", node)
if not node.module:
raise PythranSyntaxError("import from without module", node)
module = node.module
current_module = MODULES
... | Check validity of imported functions.
Check:
- no level specific value are provided.
- a module is provided
- module/submodule exists in MODULES
- imported function exists in the given module/submodule |
360,557 | def get_atom_sequence_to_rosetta_map(self):
A 45
if not self.rosetta_to_atom_sequence_maps and self.rosetta_sequences:
raise Exception()
atom_sequence_to_rosetta_mapping = {}
for chain_id, mapping in self.rosetta_to_atom_sequence_maps.iteritems():
chain_mapping... | Uses the Rosetta->ATOM injective map to construct an injective mapping from ATOM->Rosetta.
We do not extend the injection to include ATOM residues which have no corresponding Rosetta residue.
e.g. atom_sequence_to_rosetta_mapping[c].map.get('A 45 ') will return None if there is no corresponding... |
360,558 | def list_items(self, sort_key=None, reverse=False):
items = list(self.items.values())
if sort_key:
items.sort(key=sort_key, reverse=reverse)
return items | Return a list of cart items.
Parameters
----------
sort_key : func
A function to customize the list order, same as the 'key'
argument to the built-in :func:`sorted`.
reverse: bool
If set to True, the sort order will be reversed.
Returns
... |
360,559 | def get_event(self, param):
if param is None:
return None
if isinstance(param, str):
url = self.build_url(
self._endpoints.get().format(id=self.calendar_id,
ide=param))
params = None
... | Returns an Event instance by it's id
:param param: an event_id or a Query instance
:return: event for the specified info
:rtype: Event |
360,560 | def save(self, *args, **kwargs):
if self.created is None:
self.created = tz_now()
if self.modified is None:
self.modified = self.created
super(Thread, self).save(*args, **kwargs) | Fill 'created' and 'modified' attributes on first create |
360,561 | def json_get(serialized_object, field):
if serialized_object is None:
return None
obj = json.loads(serialized_object)
if obj is None:
return None
if isinstance(field, int):
res = obj[field] if 0 <= field < len(obj) else None
else:
res = ob... | This emulates the HSTORE `->` get value operation.
It get value from JSON serialized column by given key and return `null` if not present.
Key can be either an integer for array index access or a string for object field access.
:return: JSON serialized value of key in object |
360,562 | def update(self, default_activity_sid=values.unset,
event_callback_url=values.unset, events_filter=values.unset,
friendly_name=values.unset, multi_task_enabled=values.unset,
timeout_activity_sid=values.unset,
prioritize_queue_order=values.unset):
... | Update the WorkspaceInstance
:param unicode default_activity_sid: The ID of the Activity that will be used when new Workers are created in this Workspace.
:param unicode event_callback_url: The Workspace will publish events to this URL.
:param unicode events_filter: Use this parameter to receiv... |
360,563 | def pretty(self):
"sort values and format output for viewing and comparing in test scenarios"
pretty_obj = OrderedDict()
for key, value in sorted(iteritems(self.__dict__)):
if value is None:
pretty_obj[key] = None
elif is_str_or_unicode(value):
... | sort values and format output for viewing and comparing in test scenarios |
360,564 | def sonar_config(self, trigger_pin, echo_pin, cb=None, ping_interval=50, max_distance=200):
if max_distance > 200:
max_distance = 200
max_distance_lsb = max_distance & 0x7f
max_distance_msb = (max_distance >> 7) & 0x7f
data = [trigger_pin, echo_pin, ping_interval, ma... | Configure the pins,ping interval and maximum distance for an HC-SR04 type device.
Single pin configuration may be used. To do so, set both the trigger and echo pins to the same value.
Up to a maximum of 6 SONAR devices is supported
If the maximum is exceeded a message is sent to the console and ... |
360,565 | def histogram(data, bins=None, *args, **kwargs):
import numpy as np
from .histogram1d import Histogram1D, calculate_frequencies
from .binnings import calculate_bins
adaptive = kwargs.pop("adaptive", False)
dtype = kwargs.pop("dtype", None)
if isinstance(data, tuple) and isinstance(data[0]... | Facade function to create 1D histograms.
This proceeds in three steps:
1) Based on magical parameter bins, construct bins for the histogram
2) Calculate frequencies for the bins
3) Construct the histogram object itself
*Guiding principle:* parameters understood by numpy.histogram should be
und... |
360,566 | def MessageToJson(message, including_default_value_fields=False):
js = _MessageToJsonObject(message, including_default_value_fields)
return json.dumps(js, indent=2) | Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular mes... |
360,567 | def run(self):
while not self.stopEvent.isSet():
try:
if 0 < self.observable.countObservers():
currentReaders = self.readerProc()
addedReaders = []
removedReaders = []
if curren... | Runs until stopEvent is notified, and notify
observers of all reader insertion/removal. |
360,568 | def fetcher_factory(conf):
global PROMOTERS
applicable = []
if not PROMOTERS:
PROMOTERS = load_promoters()
for promoter in PROMOTERS:
if promoter.is_applicable(conf):
applicable.append((promoter.PRIORITY, promoter))
if applicable:
best_match = sorted(applicab... | Return initialized fetcher capable of processing given conf. |
360,569 | def p_identlist(self, t):
if len(t)==5 :
t[0] = t[1]+t[2]+t[3]+t[4]
elif len(t)==4 :
t[0] = t[1]+t[2]+t[3]
elif len(t)==3 :
t[0] = t[1]+t[2]
elif len(t)==2 :
t[0]=t[1]
else:
print("Syntax error at ") | identlist : IDENT
| NOT IDENT
| IDENT AND identlist
| NOT IDENT AND identlist |
360,570 | def strip_hidden(key_tuples, visibilities):
result = []
for key_tuple in key_tuples:
if len(key_tuple) != len(visibilities):
raise ValueError(
"length of key tuple {} is not equal to length of visibilities {}".format(
key_tuple, visibilities
... | Filter each tuple according to visibility.
Args:
key_tuples: A sequence of tuples of equal length (i.e. rectangular)
visibilities: A sequence of booleans equal in length to the tuples contained in key_tuples.
Returns:
A sequence equal in length to key_tuples where the items are tuples ... |
360,571 | def _print_cline(self, buf, i, icol):
for cl in self.clinebuf:
if cl[0] == i:
buf.write(
.format(cl=cl[1], icol=icol))
self.clinebuf = [x for x in self.clinebuf if x[0] != i] | Print clines after multirow-blocks are finished |
360,572 | def dump(obj, fp, **user_kwargs):
return json.dump(obj, fp, **_encoder_kwargs(user_kwargs)) | Serialize ``obj`` as a JSON-formatted stream and write to ``fp`` (a
``.write()``-supporting file-like object. |
360,573 | def get(ctx, resource, id):
session, api_url, project_id = build_client_from_context(ctx)
url = .join([api_url, resource, id])
r = session.get(url)
if r.status_code != 200:
raise failed_request_exception(, r)
response = json.loads(r.text)
if resource == :
pretty_print_model... | Gets all of the information (fields) for a given device model or
instance. |
360,574 | def ffill(self, dim, limit=None):
from .missing import ffill, _apply_over_vars_with_dim
new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit)
return new | Fill NaN values by propogating values forward
*Requires bottleneck.*
Parameters
----------
dim : str
Specifies the dimension along which to propagate values when
filling.
limit : int, default None
The maximum number of consecutive NaN values ... |
360,575 | def share(self, fmto, **kwargs):
kwargs.setdefault(, self._texts_to_remove)
super(Text, self).share(fmto, **kwargs) | Share the settings of this formatoption with other data objects
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to share the attributes with
``**kwargs``
Any other keyword argument that shall be passed to the update
method ... |
360,576 | def isoratio_init(self,isos):
FeFeFe-56Fe-58
if len(isos) == 2:
dumb = []
dumb = isos[0].split()
dumb.append(isos[1].split()[0])
dumb.append(isos[1].split()[1])
isos = dumb
ssratio = old_div(self.habu[isos[0].ljust(2).lower() + str(int(... | This file returns the isotopic ratio of two isotopes specified
as iso1 and iso2. The isotopes are given as, e.g.,
['Fe',56,'Fe',58] or ['Fe-56','Fe-58'] (for compatibility)
-> list. |
360,577 | def calls(self, truncate=False):
if self.pg_stat_statement():
if truncate:
select =
else:
select =
return self.execute(sql.CALLS.format(select=select))
else:
return [self.get_missing_pg_stat_statement_error()] | Show 10 most frequently called queries. Requires the pg_stat_statements
Postgres module to be installed.
Record(
query='BEGIN;',
exec_time=datetime.timedelta(0, 0, 288174),
prop_exec_time='0.0%',
ncalls='845590',
sync_io_time=datetime.timedelt... |
360,578 | def get_lr(self, score):
lr_curves_cache = np.array([s[0] for s in self.lr_curves])
idx = np.argmin(abs(score - lr_curves_cache))
numer_val = self.lr_curves[idx][1][0]
denum_val = self.lr_curves[idx][1][1]
... | Compute a :float: likelihood ratio from a provided similarity score when compared
to two probability density functions which are computed and pre-loaded during init.
The numerator indicates the probability density that a particular similarity score
corresponds to a 'good' addon donor, i.e. a cl... |
360,579 | def checkbox_field(*args, **kwargs):
checkbox_field = wtforms.BooleanField(*args, **kwargs)
checkbox_field.input_type =
return checkbox_field | Checkbox field |
360,580 | def __find_reports(self, report_type, usage_page, usage_id = 0):
"Find input report referencing HID usage control/data item"
if not self.is_opened():
raise HIDError("Device must be opened")
results = list()
if usage_page:
for report_id in self.repor... | Find input report referencing HID usage control/data item |
360,581 | def set_shaders(self, vert, frag):
self._linked = False
vert_handle = gl.glCreateShader(gl.GL_VERTEX_SHADER)
frag_handle = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
for code, handle, type_ in [(vert, vert_handle, ),
(frag, fra... | This function takes care of setting the shading code and
compiling+linking it into a working program object that is ready
to use. |
360,582 | def isnumber(*args):
return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args)) | Checks if value is an integer, long integer or float.
NOTE: Treats booleans as numbers, where True=1 and False=0. |
360,583 | def _extend_word(self, word, length, prefix=0, end=False, flatten=False):
if len(word) == length:
if end and "<" not in self[word[-1]]:
raise GenerationError(word + " cannot be extended")
else:
return word
else:
exclude = {"<... | Extend the given word with a random suffix up to length.
:param length: the length of the extended word; >= len(word);
:param prefix: if greater than 0, the maximum length of the prefix to
consider to choose the next character;
:param end: if True, the generated word ends... |
360,584 | def get_limits(self):
if self.limits != {}:
return self.limits
limits = {}
limits[] = AwsLimit(
,
self,
40,
self.warning_threshold,
self.critical_threshold,
limit_type=
)
limits[] = AwsLi... | Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict |
360,585 | def find_by_index(self, cls, index_name, value):
query_args = {
index_name + : DynamoMappings.map_index_val(value),
: gsi_name(index_name)
}
final_results = []
for db_result in self.get_class_table(cls).query_2(**query_args):
obj = cls.from_d... | Required functionality. |
360,586 | def execute(self, query, args, consistency):
prep_query = prepare(query, args)
def _execute(client):
exec_d = client.execute_cql3_query(prep_query,
ttypes.Compression.NONE, consistency)
if self._disconnect_on_cancel:
... | Execute a CQL query against the server.
:param query: The CQL query to execute
:type query: str.
:param args: The arguments to substitute
:type args: dict.
:param consistency: The consistency level
:type consistency: ConsistencyLevel
In order to avoid unpleasa... |
360,587 | def send(self, msg, timeout=None, tries=None):
if not self.connected():
yield self.connect()
pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
yield self.stream.write(pack) | Send a message to an IPC socket
If the socket is not currently connected, a connection will be established.
:param dict msg: The message to be sent
:param int timeout: Timeout when sending message (Currently unimplemented) |
360,588 | def get_queryset(self):
qs = super(PrefetchForIncludesHelperMixin, self).get_queryset()
if not hasattr(self, ):
return qs
includes = self.request.GET.get(, ).split()
for inc in includes + []:
prefetches = self.prefetch_for_includes.get(inc)
i... | This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is called with ?include=author it will prefetch... |
360,589 | def is_dir_exists(dirpath):
if dirpath is None or not os.path.exists(dirpath) or not os.path.isdir(dirpath):
return False
else:
return True | Check the existence of folder path. |
360,590 | def proxify_routine(routine, impl=None):
impl = routine if impl is None else impl
is_method = ismethod(routine)
if is_method:
function = get_method_function(routine)
else:
function = routine
wrap_function = not hasattr(function, )
try:
arg... | Proxify a routine with input impl.
:param routine: routine to proxify.
:param impl: new impl to use. If None, use routine. |
360,591 | def max(self, axis=None, dtype=None, out=None, keepdims=False):
return self.elem.__array_ufunc__(
np.maximum, , self.elem,
axis=axis, dtype=dtype, out=(out,), keepdims=keepdims) | Return the maximum of ``self``.
See Also
--------
numpy.amax
min |
360,592 | def match_relative_fit(imglist, reference_catalog):
log.info("------------------- STEP 5b: (match_relative_fit) Cross matching and fitting ---------------------------")
match = tweakwcs.TPMatch(searchrad=75, separation=0.1,
tolerance=2, use2dhist=True)
... | Perform cross-matching and final fit using 2dHistogram matching
Parameters
----------
imglist : list
List of input image `~tweakwcs.tpwcs.FITSWCS` objects with metadata and source catalogs
reference_catalog : Table
Astropy Table of reference sources for this field
Returns
----... |
360,593 | def save(self, expected_value=None, return_values=None):
return self.table.layer2.update_item(self, expected_value,
return_values) | Commits pending updates to Amazon DynamoDB.
:type expected_value: dict
:param expected_value: A dictionary of name/value pairs that
you expect. This dictionary should have name/value pairs
where the name is the name of the attribute and the value is
either the value... |
360,594 | def safe(self,x):
x[np.isinf(x)] = 1
x[np.isnan(x)] = 1
return x | removes nans and infs from outputs. |
360,595 | def get_all_cpv_use(cp):
cpv = _get_cpv(cp)
portage = _get_portage()
use = None
_porttree().dbapi.settings.unlock()
try:
_porttree().dbapi.settings.setcpv(cpv, mydb=portage.portdb)
use = portage.settings[].split()
use_expand_hidden = portage.settings["USE_EXPAND_HIDDEN"]... | .. versionadded:: 2015.8.0
Uses portage to determine final USE flags and settings for an emerge.
@type cp: string
@param cp: eg cat/pkg
@rtype: lists
@return use, use_expand_hidden, usemask, useforce |
360,596 | def _setup_environ(self):
_pam_env_watcher.check()
_etc_env_watcher.check()
env = dict(self.extra_env or {})
if self.env:
env.update(self.env)
self._env = TemporaryEnvironment(env) | Apply changes from /etc/environment files before creating a
TemporaryEnvironment to snapshot environment state prior to module run. |
360,597 | def add_validate(subparsers):
validate_parser = subparsers.add_parser(
, help=add_validate.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
validate_parser.set_defaults(func=validate_parser.print_help)
validate_subparsers = validate_parser.add_subparsers(title=)
validate_a... | Validate Spinnaker setup. |
360,598 | def stop(self):
if self.closed:
raise ConnectionClosed()
if self.read_watcher.active:
self.read_watcher.stop()
if self.write_watcher.active:
self.write_watcher.stop() | Stop watching the socket. |
360,599 | def softmax_cross_entropy_with_logits(sentinel=None,
labels=None,
logits=None,
dim=-1):
if sentinel is not None:
name = "softmax_cross_entropy_with_logits"
raise ValueError("Only call `%s` w... | Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.