Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
346,300 | def left_join_where(self, table, one, operator, two):
return self.join_where(table, one, operator, two, "left") | Add a "left join where" clause to the query
:param table: The table to join with, can also be a JoinClause instance
:type table: str or JoinClause
:param one: The first column of the join condition
:type one: str
:param operator: The operator of the join condition
:typ... |
346,301 | def singleton(klass):
instances = {}
def getinstance(*args, **kwargs):
if klass not in instances:
instances[klass] = klass(*args, **kwargs)
return instances[klass]
return wraps(klass)(getinstance) | Create singleton from class |
346,302 | def open_camera(
self, input_source: str, extra_cmd: Optional[str] = None
) -> Coroutine:
command = ["-an", "-c:v", "mjpeg"]
return self.open(
cmd=command,
input_source=input_source,
output="-f mpjpeg -",
extra_cmd=extra_cmd,
... | Open FFmpeg process as mjpeg video stream.
Return A coroutine. |
346,303 | def get_py_impl():
if hasattr(sys, ):
pyimpl =
elif sys.platform.startswith():
pyimpl =
elif sys.platform == :
pyimpl =
else:
pyimpl =
return pyimpl | Return what kind of Python this is |
346,304 | def list_indexes(self, session=None):
codec_options = CodecOptions(SON)
coll = self.with_options(codec_options=codec_options,
read_preference=ReadPreference.PRIMARY)
read_pref = ((session and session._txn_read_preference())
or ReadPr... | Get a cursor over the index documents for this collection.
>>> for index in db.test.list_indexes():
... print(index)
...
SON([(u'v', 1), (u'key', SON([(u'_id', 1)])),
(u'name', u'_id_'), (u'ns', u'test.test')])
:Parameters:
- `session` (opti... |
346,305 | def get(cls, name: sym.Symbol) -> "Optional[Namespace]":
return cls._NAMESPACES.deref().entry(name, None) | Get the namespace bound to the symbol `name` in the global namespace
cache. Return the namespace if it exists or None otherwise.. |
346,306 | def processWhileRunning(self):
work = self.step()
for result, more in work:
yield result
if not self.running:
break
if more:
delay = 0.1
else:
delay = 10.0
yield task.deferLater(reactor, ... | Run tasks until stopService is called. |
346,307 | def dispatch_url(self, url_string):
url, url_adapter, query_args = self.parse_url(url_string)
try:
endpoint, kwargs = url_adapter.match()
except NotFound:
raise NotSupported(url_string)
except RequestRedirect as e:
new_url = "{0.new_url}?{1}"... | Dispatch the URL string to the target endpoint function.
:param url_string: the origin URL string.
:returns: the return value of calling dispatched function. |
346,308 | def fit(
self,
durations,
event_observed=None,
timeline=None,
entry=None,
label="NA_estimate",
alpha=None,
ci_labels=None,
weights=None,
):
self._censoring_type = CensoringType.RIGHT
check_nans_or_infs(durations)
... | Parameters
-----------
durations: an array, or pd.Series, of length n
duration subject was observed for
timeline: iterable
return the best estimate at the values in timelines (positively increasing)
event_observed: an array, or pd.Series, of length n
Tru... |
346,309 | def format_response(self, response):
return response.json(object_pairs_hook=collections.OrderedDict if self.preserve_order else None) | Extracts JSON data from the response
:param requests.Response response:
The original response from :mod:`requests`
:return:
The response's JSON content
:rtype:
:class:`dict` if ``preserve_order`` is ``False``
:rtype:
:class:`collections.Or... |
346,310 | def visit_delete(self, node):
return "del %s" % ", ".join(child.accept(self) for child in node.targets) | return an astroid.Delete node as string |
346,311 | def flush_body(self) -> bool:
if self._body is None:
return False
elif isinstance(self._body, bytes):
self.write(self._body)
return True
return False | 发送内容体 |
346,312 | def ensure(data_type, check_value, default_value=None):
if default_value is not None and not isinstance(default_value, data_type):
raise ValueError("default_value must be the value in the given data "
"type.")
elif isinstance(check_value, data_type):
return check_va... | function to ensure the given check value is in the given data type, if yes,
return the check value directly, otherwise return the default value
:param data_type: different data type: can be int, str, list, tuple etc,
must be python supportable data type or new defined data type
:param check_value: di... |
346,313 | def institute_num_pattern_to_regex(pattern):
simple_replacements = [
(, r),
(, r),
(, r),
(, r),
(, r),
(, r),
(, r),
(, r),
(r, r)]
for repl in simple_replacements:
pattern = pattern.replace(repl[0], repl[1])
... | Given a numeration pattern from the institutes preprint report
numbers KB, convert it to turn it into a regexp string for
recognising such patterns in a reference line.
Change:
\ -> \\
9 -> \d
a -> [A-Za-z]
v -> [Vv] # Tony for arXiv vN
... |
346,314 | def resource_show(resource_id, extra_args=None, cibfile=None):
*galera/tmp/cib_for_galera.cib
return item_show(item=, item_id=resource_id, extra_args=extra_args, cibfile=cibfile) | Show a resource via pcs command
resource_id
name of the resource
extra_args
additional options for the pcs command
cibfile
use cibfile instead of the live CIB
CLI Example:
.. code-block:: bash
salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_g... |
346,315 | def _set_apply_exp_traffic_class_map_name(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=apply_exp_traffic_class_map_name.apply_exp_traffic_class_map_name, is_container=, presence=False, yang_name="apply-exp-traffic-class-map-name", rest_name="exp-tr... | Setter method for apply_exp_traffic_class_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_traffic_class_map_name (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_apply_exp_traffic_class_map_name is considered as a private
method. Backends looking... |
346,316 | def import_object_ns(name_space, import_str, *args, **kwargs):
import_value = "%s.%s" % (name_space, import_str)
try:
return import_class(import_value)(*args, **kwargs)
except ImportError:
return import_class(import_str)(*args, **kwargs) | Tries to import object from default namespace.
Imports a class and return an instance of it, first by trying
to find the class in a default namespace, then failing back to
a full path if not found in the default namespace. |
346,317 | def generate_address_2(from_: Union[str, bytes], salt: Union[str, bytes], init_code: [str, bytes]) -> str:
from_ = HexBytes(from_)
salt = HexBytes(salt)
init_code = HexBytes(init_code)
assert len(from_) == 20, "Address %s is not valid. Must be 20 bytes" % from_
assert len(salt) == 32, "Salt %... | Generates an address for a contract created using CREATE2.
:param from_: The address which is creating this new address (need to be 20 bytes)
:param salt: A salt (32 bytes)
:param init_code: A init code of the contract being created
:return: Address of the new contract |
346,318 | def loadu(self, url, **kwargs):
return self.load(self.open(url, **kwargs), **kwargs) | opens url and passes to load()
kwargs are passed to both open and load |
346,319 | def measure(*qubits: raw_types.Qid,
key: Optional[str] = None,
invert_mask: Tuple[bool, ...] = ()
) -> gate_operation.GateOperation:
for qubit in qubits:
if isinstance(qubit, np.ndarray):
raise ValueError(
... | Returns a single MeasurementGate applied to all the given qubits.
The qubits are measured in the computational basis.
Args:
*qubits: The qubits that the measurement gate should measure.
key: The string key of the measurement. If this is None, it defaults
to a comma-separated list o... |
346,320 | def resolve_symbols(self, tree, database, link_resolver):
self.typed_symbols = self.__get_empty_typed_symbols()
all_syms = OrderedSet()
for sym_name in self.symbol_names:
sym = database.get_symbol(sym_name)
self.__query_extra_symbols(
sym, all_sym... | When this method is called, the page's symbol names are queried
from `database`, and added to lists of actual symbols, sorted
by symbol class. |
346,321 | def send_ssdp_broadcast():
for i, ssdp_query in enumerate(SSDP_QUERIES):
sock = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.settimeout(2)
sock.sendto(ssdp_query.encode(), (SSDP_ADDR, SSDP_PORT))
res = []
... | Send SSDP broadcast message to discover UPnP devices.
Returns a list of dictionaries with "address" (IP, PORT) and "URL"
of SCPD XML for all discovered devices. |
346,322 | def paragraphs(value):
result = "\n\n".join(
"<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n")))
for p in _PARAGRAPH_RE.split(escape(value))
)
return result | Blank lines delimitates paragraphs. |
346,323 | def cardChunk(key, chunk):
for line in chunk:
values = []
sline = line.strip().split()
for idx in range(1, len(sline)):
values.append(sline[idx])
return {: sline[0],
: values} | Parse Card Chunk Method |
346,324 | def refs_equal(olditem, newitem):
oldrefs = olditem.references
newrefs = newitem.references
ref_equal = lambda oldref, newref: True if (len(oldref) == len(newref)) and all(
x in oldref for x in newref) else False
if len(oldrefs) == len(newrefs) and all(
... | tests for exactly identical references |
346,325 | def _prep_save(self):
log.info("Preparing bulk save.")
self.graph.update_bulk_saver(self.bulk_saver)
log.info(
"Dropped %d unused preconditions, %d are missing",
sum(len(v) for v in self.summary["precondition_entries"].values()),
len(self.summary["mi... | Prepares the bulk saver to load the trace graph info into the
database. |
346,326 | def _retrieve_all_teams(self, year):
team_data_dict = {}
if not year:
year = utils._find_year_for_season()
doc = pq(STANDINGS_URL % year)
div_prefix =
standings = utils._get_stats_table(doc, div_prefix)
doc = pq(TEAM_STATS_URL % year)
div_pr... | Find and create Team instances for all teams in the given season.
For a given season, parses the specified MLB stats table and finds all
requested stats. Each team then has a Team instance created which
includes all requested stats and a few identifiers, such as the team's
name and abbr... |
346,327 | def _resolve_subkeys(key, separator="."):
parts = key.split(separator, 1)
if len(parts) > 1:
return parts
else:
return parts[0], None | Resolve a potentially nested key.
If the key contains the ``separator`` (e.g. ``.``) then the key will be
split on the first instance of the subkey::
>>> _resolve_subkeys('a.b.c')
('a', 'b.c')
>>> _resolve_subkeys('d|e|f', separator='|')
('d', 'e|f')
If not, the subkey will be... |
346,328 | def finalize_backward_execution(self):
self.backward_execution = True
last_history_item = self.execution_history.pop_last_item()
assert isinstance(last_history_item, ConcurrencyItem)
last_history_item = self.execution_history.pop_last_item()
assert isi... | Utility function to finalize the backward execution of the concurrency state.
:return: |
346,329 | def rate(self, currency):
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.rate(currency) | Return quotation between the base and another currency |
346,330 | def _write_callback(connection_id, data_buffer, data_length_pointer):
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_socket is None:
return SecurityConst.errSSLInternal
base_socket = wrapped_socket.socket
bytes_to_writ... | SecureTransport write callback. This is called by ST to request that data
actually be sent on the network. |
346,331 | def persist_curves(self, asset_manager_id, business_date, curves, update_existing_curves=True):
self.logger.info(, asset_manager_id, business_date)
url = % (self.endpoint, asset_manager_id, business_date.isoformat())
params = {: update_existing_curves}
curves_json = [curve.to_i... | :param asset_manager_id:
:param business_date:
:param curves:
:param update_existing_rates:
:return: |
346,332 | def invoke(self):
logger.debug(, self)
self.module.makeLoadable()
function, args, kwargs = list(map(dill.loads, (self.function, self.args, self.kwargs)))
return function(*args, **kwargs) | Invoke the captured function with the captured arguments. |
346,333 | def paginate(self, page=1, perpage=10, category=None):
q = db.select(self.table).fields(, , , , , ,
, , , , , )
if category:
q.condition(, category)
results = (q.limit(perpage).offset((page - 1) * perpage)
.order_b... | Paginate the posts |
346,334 | def relative_probability( self, l1, l2, c1, c2 ):
if self.site_energies:
site_delta_E = self.site_energies[ l2 ] - self.site_energies[ l1 ]
else:
site_delta_E = 0.0
if self.nn_energy:
delta_nn = c2 - c1 - 1
site_delta_E += delta_nn * self... | The relative probability for a jump between two sites with specific site types and coordination numbers.
Args:
l1 (Str): Site label for the initial site.
l2 (Str): Site label for the final site.
c1 (Int): Coordination number for the initial site.
c2 (Int): Coordi... |
346,335 | def request(self, method, data=None, nid=None, nid_key=,
api_type="logic", return_response=False):
self._check_authenticated()
nid = nid if nid else self._nid
if data is None:
data = {}
headers = {}
if "session_id" in self.session.cookies:
... | Get data from arbitrary Piazza API endpoint `method` in network `nid`
:type method: str
:param method: An internal Piazza API method name like `content.get`
or `network.get_users`
:type data: dict
:param data: Key-value data to pass to Piazza in the request
:type ... |
346,336 | def convert_predictions_to_image_summaries(hook_args):
decode_hparams = hook_args.decode_hparams
if not decode_hparams.display_decoded_images:
return []
predictions = hook_args.predictions[0]
all_summaries = []
rand_predictions = np.random.choice(predictions, size=10)
for ind, prediction in enume... | Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara |
346,337 | def merge(a, b):
assert quacks_like_dict(a), quacks_like_dict(b)
dst = a.copy()
stack = [(dst, b)]
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else... | Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd':... |
346,338 | def metric(self, metric, thresholds=None):
assert_is_type(thresholds, None, [numeric])
if not thresholds: thresholds = [self.find_threshold_by_max_metric(metric)]
thresh2d = self._metric_json[]
metrics = []
for t in thresholds:
idx = self.find_idx_by_threshol... | :param str metric: The desired metric.
:param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then
the thresholds in this set of metrics will be used.
:returns: The set of metrics for the list of thresholds. |
346,339 | def main(argv=None):
parser = ArgumentParser(prog="pygenstub")
parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
parser.add_argument("files", nargs="*", help="generate stubs for given files")
parser.add_argument(
"-m",
"--module",
action="... | Start the command line interface. |
346,340 | def execute(self, fn, *args, **kwargs):
if self.in_executor_context():
return fn(*args, **kwargs)
task = self.submit(fn, *args, **kwargs)
return task.result() | Execute an operation and return the result. |
346,341 | def handle(self, *args, **options):
now = arrow.utcnow().to(settings.TIME_ZONE)
now = now.date()
digest = Digest.objects.filter(date_end=str(now)).order_by(, )
users = digest.distinct()
subject =
msg_plain = render_to_string(, {: digest, : subject})
m... | get all the digest data to send to each user |
346,342 | def request(self, method, url, data=None, files=None, query=None, headers=None, timeout=60):
headers = headers or {}
if self.token:
my_token = self.token
else:
from figure import token
my_token = token
if my_token:
self.__set_aut... | Mechanism for issuing an API call |
346,343 | def init_atropos_wf(name=,
use_random_seed=True,
omp_nthreads=None,
mem_gb=3.0,
padding=10,
in_segmentation_model=list(ATROPOS_MODELS[].values())):
wf = pe.Workflow(name)
inputnode = pe.Node(niu.IdentityInt... | Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``,
which refine the mask previously computed with the spatial
normalization to the template.
**Parameters**
use_random_seed : bool
Whether ATROPOS should generate a random seed based on the
system's clock
omp... |
346,344 | def set_defaults(key):
def decorator(func):
@functools.wraps(func)
def wrapper(phase, new_value):
new_value = new_value or []
for item in new_value:
galaxy = new_value[item] if isinstance(item, str) else item
galaxy.redsh... | Load a default value for redshift from config and set it as the redshift for source or lens galaxies that have
falsey redshifts
Parameters
----------
key: str
Returns
-------
decorator
A decorator that wraps the setter function to set defaults |
346,345 | def angle_3points(p0, p1, p2):
vec1 = vector(p1, p0)
vec2 = vector(p2, p0)
return math.atan2(np.linalg.norm(np.cross(vec1, vec2)),
np.dot(vec1, vec2)) | compute the angle in radians between three 3D points
Calculated as the angle between p1-p0 and p2-p0.
Args:
p0, p1, p2: indexable objects with
indices 0, 1, 2 corresponding to 3D cartesian coordinates.
Returns:
Angle in radians between (p1-p0) and (p2-p0).
0.0 if p0==p1 o... |
346,346 | def to_key_val_list(value):
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError()
if isinstance(value, collections.Mapping):
value = value.items()
return list(value) | Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
Val... |
346,347 | def isHcl(s):
for c in s:
if c.isspace():
continue
if c == :
return False
else:
return True
raise ValueError("No HCL object could be decoded") | Detects whether a string is JSON or HCL
:param s: String that may contain HCL or JSON
:returns: True if HCL, False if JSON, raises ValueError
if neither |
346,348 | def update(self):
def process_result(result):
self.raw = result
return Command(, self.path, process_result=process_result) | Update the group.
Returns a Command. |
346,349 | def get_fraglength_dict(fastafiles):
fraglength_dict = {}
for filename in fastafiles:
qname = os.path.split(filename)[-1].split("-fragments")[0]
fraglength_dict[qname] = get_fragment_lengths(filename)
return fraglength_dict | Returns dictionary of sequence fragment lengths, keyed by query name.
- fastafiles - list of FASTA input whole sequence files
Loops over input files and, for each, produces a dictionary with fragment
lengths, keyed by sequence ID. These are returned as a dictionary with
the keys being query IDs derive... |
346,350 | def stringer(x):
if isinstance(x, string_types):
return x
if isinstance(x, (list, tuple)):
return [stringer(y) for y in x]
if isinstance(x, dict):
return dict((stringer(a), stringer(b)) for a, b in x.items())
return text_type(x) | Takes an object and makes it stringy
>>> print(stringer({'a': 1, 2: 3, 'b': [1, 'c', 2.5]}))
{'b': ['1', 'c', '2.5'], 'a': '1', '2': '3'} |
346,351 | def set_ground_width(self, ground_width):
state = self.state
state.ground_width = ground_width
state.panel.re_center(state.width/2, state.height/2, state.lat, state.lon) | set ground width of view |
346,352 | def get_current_container_id(read_from=):
if not os.path.exists(read_from):
return
with open(read_from, ) as cgroup:
for line in cgroup:
if re.match(, line.strip()):
return re.sub(, , line.strip()) | Get the ID of the container the application is currently running in,
otherwise return `None` if not running in a container.
This is a best-effort guess, based on cgroups.
:param read_from: the cgroups file to read from (default: `/proc/self/cgroup`) |
346,353 | def publishing_set_update_time(sender, instance, **kwargs):
if hasattr(instance, ):
if getattr(instance, , False):
instance._skip_update_publishing_modified_at = False
return
instance.publishing_modified_at = time... | Update the time modified before saving a publishable object. |
346,354 | def GetPoints(edna_service):
szServiceName = c_char_p(edna_service.encode())
nStarting, pulKey, pdValue = c_ushort(0), c_ulong(0), c_double(-9999)
szPoint, szTime = create_string_buffer(30), create_string_buffer(30)
szStatus, szDesc = create_string_buffer(20), create_string_buffer(90)
... | Obtains all the points in the edna_service, including real-time values.
:param edna_service: The full Site.Service name of the eDNA service.
:return: A pandas DataFrame of points in the form [Tag, Value, Time,
Description, Units] |
346,355 | def hurst_exponent(px, lags=range(2, 100)):
ts = px.reset_index(drop=True).dropna()
tau = [np.sqrt(ts.diff(lag).std()) for lag in lags]
poly = np.polyfit(np.log(lags), np.log(tau), 1)
return poly[0] * 2.0 | describe the prices
http://www.quantstart.com/articles/Basics-of-Statistical-Mean-Reversion-Testing
H = the hurts exponent
H < 0.5 - mean reverting
H = 0.5 - geometric brownian motion (aka random)
H > 0.5 - trending series |
346,356 | async def get_docker_version(self):
if self.image not in IMAGES:
_LOGGER.warning("%s is not a valid image using default", self.image)
self.image = "default"
self._version_data["beta"] = self.beta
self._version_data["source"] = "Docker"
self._version_data... | Get version published for docker. |
346,357 | def scrubFilename(filename):
global _PACKAGE_SCRUB_LIST
for package in _PACKAGE_SCRUB_LIST:
i = filename.rfind(package)
if i > -1:
return filename[i:]
return filename | Scrub the filename to a relative path for all packages in our scrub list. |
346,358 | def unindent_selection(self, cursor):
doc = self.editor.document()
tab_len = self.editor.tab_length
nb_lines = len(cursor.selection().toPlainText().splitlines())
if nb_lines == 0:
nb_lines = 1
block = doc.findBlock(cursor.selectionStart())
assert isin... | Un-indents selected text
:param cursor: QTextCursor |
346,359 | def tty_create_child(args):
master_fd, slave_fd = openpty()
try:
mitogen.core.set_block(slave_fd)
disable_echo(master_fd)
disable_echo(slave_fd)
pid = detach_popen(
args=args,
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
... | Return a file descriptor connected to the master end of a pseudo-terminal,
whose slave end is connected to stdin/stdout/stderr of a new child process.
The child is created such that the pseudo-terminal becomes its controlling
TTY, ensuring access to /dev/tty returns a new file descriptor open on the
sla... |
346,360 | def from_bytes(self, raw):
t resurrect the packet.'
if len(raw) < TCP._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an TCP object".format(len(raw)))
fields = struct.unpack(TCP._PACKFMT, raw[:TCP._MINLEN])
self._src = fields[0]
self._dst = fie... | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. |
346,361 | def rewind_body(body, body_pos):
body_seek = getattr(body, , None)
if body_seek is not None and isinstance(body_pos, integer_types):
try:
body_seek(body_pos)
except (IOError, OSError):
raise UnrewindableBodyError("An error occurred when rewinding request "
... | Attempt to rewind body to a certain position.
Primarily used for request redirects and retries.
:param body:
File-like object that supports seek.
:param int pos:
Position to seek to in file. |
346,362 | def _encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):
if not isinstance(certificate_or_public_key, (Certificate, PublicKey)):
raise TypeError(pretty_message(
,
type_name(certificate_or_public_key)
))
if not isinstance(data, byte_cls):
raise... | Encrypts a value using an RSA public key
:param certificate_or_public_key:
A Certificate or PublicKey instance to encrypt with
:param data:
A byte string of the data to encrypt
:param rsa_oaep_padding:
If OAEP padding should be used instead of PKCS#1 v1.5
:raises:
Val... |
346,363 | def render_date(date, tz=pytz.utc, fmt=_FULL_OUTPUT_FORMAT):
local = date.astimezone(tz)
ts = __date_to_millisecond_ts(date)
return fmt.format(
ts=ts,
utc=date.strftime(_DATE_FORMAT),
millis=ts % 1000,
utc_tz=date.strftime(_TZ_FORMAT),
local=l... | Format the given date for output. The local time render of the given
date is done using the given timezone. |
346,364 | def use(self, client_key):
if not self.clients.has_client(client_key):
raise ClientNotExist()
self.current_client = self.clients.get_client(client_key)
return self | :param client_key: The client key.
:type client_key: str
:return: The Orchestrator instance (method chaining)
:rtype: :class:`revision.orchestrator.Orchestrator` |
346,365 | def register(self, correlation_id, connection):
result = self._register_in_discovery(correlation_id, connection)
if result:
self._connections.append(connection) | Registers the given connection in all referenced discovery services.
This method can be used for dynamic service discovery.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param connection: a connection to register. |
346,366 | def texture_from_image(renderer, image_name):
soft_surface = ext.load_image(image_name)
texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface)
SDL_FreeSurface(soft_surface)
return texture | Create an SDL2 Texture from an image file |
346,367 | def get_q2(self, thetas=None, phis=None):
if thetas is not None and phis is not None:
self.compute_trigonometric_terms(thetas, phis)
nnn = len(self._pow_sin_t[1])
nnn_range = range(nnn)
sqrt_15_2pi = sqrt(15.0 / (2.0 * pi))
sqrt_5_pi = sqrt(5.0 / pi)
... | Calculates the value of the bond orientational order parameter of
weight l=2. If the function is called with non-empty lists of
polar and azimuthal angles the corresponding trigonometric terms
are computed afresh. Otherwise, it is expected that the
compute_trigonometric_terms function ... |
346,368 | def set_filter(self, text, status):
self._filter_string = text.lower()
self._filter_status = status
self.invalidateFilter() | text : string
The string to be used for pattern matching.
status : int
TODO: add description |
346,369 | def get_assessments_offered_for_assessment(self, assessment_id):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find(
dict({: str(... | Gets an ``AssessmentOfferedList`` by the given assessment.
In plenary mode, the returned list contains all known
assessments offered or an error results. Otherwise, the returned
list may contain only those assessments offered that are
accessible through this session.
arg: as... |
346,370 | def calc_global_bbox(self, view_matrix, bbox_min, bbox_max):
if self.matrix is not None:
view_matrix = matrix44.multiply(self.matrix, view_matrix)
if self.mesh:
bbox_min, bbox_max = self.mesh.calc_global_bbox(view_matrix, bbox_min, bbox_max)
for child in self.c... | Recursive calculation of scene bbox |
346,371 | def config_conf_section():
config_dict = OrderedDict((
(,
ConfOpt(None, True, None, {: },
False, )),
(,
ConfOpt(None, True, None, {: },
False, )),
(,
ConfOpt(None, True, None, {: },
False, ))... | Define a configuration section handling config file.
Returns:
dict of ConfOpt: it defines the 'create', 'update', 'edit' and 'editor'
configuration options. |
346,372 | def search_registry(self, searchterm):
return self.__search(type_attribute=self.__mispregistrytypes(), value=searchterm) | Search for registry keys and values
:type searchterm: str
:rtype: list |
346,373 | def _parse_line(self, line_no, line):
try:
matched = statement.parseString(line)
except ParseException as exc:
raise DataError("Error parsing line in TileBus file", line_number=line_no, column=exc.col, contents=line)
if in matched:
self._parse_cmd(... | Parse a line in a TileBus file
Args:
line_no (int): The line number for printing useful error messages
line (string): The line that we are trying to parse |
346,374 | def add_links(converted_text, html):
soup = BeautifulSoup(html, )
link_exceptions = [
,
,
]
footnotes = {}
citations = {}
backrefs = {}
links = soup.find_all()
for link in links:
href = link.get()
text = process_tag(link)
classes =... | Add the links to the bottom of the text |
346,375 | def fourier_series(x, f, n=0):
a0, *cos_a = parameters(.join([.format(i) for i in range(0, n + 1)]))
sin_b = parameters(.join([.format(i) for i in range(1, n + 1)]))
series = a0 + sum(ai * cos(i * f * x) + bi * sin(i * f * x)
for i, (ai, bi) in enumerate(zip(cos_a, sin_b)... | Returns a symbolic fourier series of order `n`.
:param n: Order of the fourier series.
:param x: Independent variable
:param f: Frequency of the fourier series |
346,376 | async def _write_loop(self):
while self.state == :
timeout = max(self.ping_interval, self.ping_timeout) + 5
packets = None
try:
packets = [await asyncio.wait_for(self.queue.get(), timeout)]
except (se... | This background task sends packages to the server as they are
pushed to the send queue. |
346,377 | def diff_means_abs(array_one, array_two):
abs_diff_means = np.abs(diff_means(array_one, array_two))
return abs_diff_means | Computes the absolute (symmetric) difference in means between two arrays of values.
Given arrays will be flattened (to 1D array) regardless of dimension,
and any non-finite/NaN values will be ignored.
Parameters
----------
array_one, array_two : iterable
Two arrays of values, possibly ... |
346,378 | def get_meta_options(self, model):
meta_fields = {
"ordering": ("-history_date", "-history_id"),
"get_latest_by": "history_date",
}
if self.user_set_verbose_name:
name = self.user_set_verbose_name
else:
name = format_lazy("historic... | Returns a dictionary of fields that will be added to
the Meta inner class of the historical record model. |
346,379 | def set_description(self, description, lang=None):
description = Validation.description_check_convert(description)
lang = Validation.lang_check_convert(lang, default=self._default_lang)
self.delete_description(lang)
subj = self._get_uuid_uriref()
self._graph.add... | Sets the `description` metadata property on your Thing/Point. Only one description is allowed per language,
so any other descriptions in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters fail validation
`description` (mandatory)... |
346,380 | def addcomment(self, creditmemo_increment_id,
comment, email=True, include_in_email=False):
return bool(
self.call(
,
[creditmemo_increment_id, comment, email, include_in_email]
)
) | Add new comment to credit memo
:param creditmemo_increment_id: Credit memo increment ID
:return: bool |
346,381 | def _get_best_type_from_mapping(mapping):
best_type_name = None
best_mapping = None
for k, m in mapping.items():
if k == "_default_":
continue
if best_type_name is None or len(m.properties) > len(best_mapping.properties):
best_type_name = k
best_mappi... | THERE ARE MULTIPLE TYPES IN AN INDEX, PICK THE BEST
:param mapping: THE ES MAPPING DOCUMENT
:return: (type_name, mapping) PAIR (mapping.properties WILL HAVE PROPERTIES |
346,382 | def add_days(date_obj, days_int):
n = from_ymd_to_excel(*date_obj.date) + days_int
return BaseDateTuple(*from_excel_to_ymd(n)) | addition of a number of days
:param BaseDateTuple d:
:param int days_int:
:return BaseDatetimeDate: |
346,383 | def data_filename(fname, pkgdir=""):
for static_dir in STATIC_PATH:
static_filename = os.path.join(static_dir, fname)
if os.path.exists(static_filename):
return static_filename
if pkgdir:
static_filename = os.path.join(static_dir, pkgdir, fname)
if os... | Return the path to a data file of ours.
The file is searched for on `STATIC_PATH`, and the first place it's found,
is returned.
Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir`
is provided, at that subdirectory. |
346,384 | def _get_group_signature_error(group, sponge_type):
validate_group_signature = validate_signature_fragments(
fragments=[txn.signature_message_fragment for txn in group],
hash_=group[0].bundle_hash,
public_key=group[0].address,
sponge_type=sponge_... | Validates the signature fragments for a group of transactions
using the specified sponge type.
Note: this method assumes that the transactions in the group
have already passed basic validation (see
:py:meth:`_create_validator`).
:return:
- ``None``: Indicates that th... |
346,385 | def _build_str_from_expression(exp_items):
time_delta_base, unit, method = exp_items
if unit not in _KEY_TIME_MAPPING:
return None
delta = datetime.timedelta(seconds=int(time_delta_base) * _KEY_TIME_MAPPING[unit])
now = datetime.datetime.now()
return datetime.datetime.strftime(now + (de... | 根据解析出的时间表达式的关键字计算对应的表达式值
:return: 表达式对应时间的标准时间格式字符串表示形式 |
346,386 | def profile_settings_args(self, ij, required):
if self.args.permutation_id is not None:
if not in sys.modules:
print()
sys.exit(1)
profile_args = self.profile_settings_args_layout_json(required)
else:
profile_args = self.profi... | Return args based on install.json or layout.json params.
Args:
ij (dict): The install.json contents.
required (bool): If True only required args will be returned.
Returns:
dict: Dictionary of required or optional App args. |
346,387 | def write_temp_file_or_dryrun(content, *args, **kwargs):
dryrun = get_dryrun(kwargs.get())
if dryrun:
fd, tmp_fn = tempfile.mkstemp()
os.remove(tmp_fn)
cmd_run =
cmd = % (tmp_fn, content)
if BURLAP_COMMAND_PREFIX:
print( % (render_command_prefix(), cmd_... | Writes the given content to a local temporary file. |
346,388 | def validate(self):
try:
resp = self.request().get(self.validate_url, verify=self.verifySSL).json()
except TokenExpiredError:
return False
except AttributeError:
return False
if in resp:
return False
return True | Confirms the current token is still valid.
Returns True if it is valid, False otherwise. |
346,389 | def _grep_qstat(self, status_type=):
args = "qstat -e {}".format(self.id).split()
res, _ = call(args)
if res == : return False
res = res.split()[2].split()[4]
if status_type == and res == :
return True
elif status_type == and (res == or res == ):
... | Greps qstat -e <job_id> for information from the queue.
:paramsstatus_type: complete, queued, running, error, gone |
346,390 | def get_font_matrix(self):
matrix = Matrix()
cairo.cairo_get_font_matrix(self._pointer, matrix._pointer)
self._check_status()
return matrix | Copies the current font matrix. See :meth:`set_font_matrix`.
:returns: A new :class:`Matrix`. |
346,391 | def off(self, motors=None, brake=True):
motors = motors if motors is not None else self.motors.values()
for motor in motors:
motor._set_brake(brake)
for motor in motors:
motor.stop() | Stop motors immediately. Configure motors to brake if ``brake`` is set. |
346,392 | def has_description(self, param):
return param in self.param_description.keys() and \
not self.param_description[param].isspace() | if a parameter has a description |
346,393 | def _set_linecard(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=linecard.linecard, is_container=, presence=False, yang_name="linecard", rest_name="linecard", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=Tru... | Setter method for linecard, mapped from YANG variable /global_lc_holder/linecard (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_linecard is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_linec... |
346,394 | def show_code_completion(self):
text = to_text_string(self.get_current_line_to_cursor())
last_obj = self.get_last_obj()
if not text:
return
obj_dir = self.get_dir(last_obj)
if last_obj and obj_dir and text.endswith():
self.show_... | Display a completion list based on the current line |
346,395 | def sign_array(p_values, alpha=0.05):
p_values = np.array(p_values)
p_values[p_values > alpha] = 0
p_values[(p_values < alpha) & (p_values > 0)] = 1
np.fill_diagonal(p_values, -1)
return p_values | Significance array
Converts an array with p values to a significance array where
0 is False (not significant), 1 is True (significant),
and -1 is for diagonal elements.
Parameters
----------
p_values : array_like or ndarray
An array, any object exposing the array interface, containing
... |
346,396 | def _prioritize_vcf(caller, vcf_file, prioritize_by, post_prior_fn, work_dir, data):
sample = dd.get_sample_name(data)
out_file = os.path.join(work_dir, "%s-%s-prioritize.tsv" % (sample, caller))
simple_vcf = os.path.join(work_dir, "%s-%s-simple.vcf.gz" % (sample, caller))
if not utils.file_exists(... | Provide prioritized tab delimited output for a single caller. |
346,397 | def unbare_repo(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if self.repo.bare:
raise InvalidGitRepositoryError("Method cannot operate on bare repositories" % func.__name__)
return func(self, *args, **kwargs)
return wrapper | Methods with this decorator raise InvalidGitRepositoryError if they
encounter a bare repository |
346,398 | def generate(self, output_dir, work, matches_filename):
template = self._get_template()
matches = pd.read_csv(matches_filename)
for siglum in self._corpus.get_sigla(work):
subm = matches[(matches[constants.WORK_FIELDNAME] != work) |
(matches[consta... | Generates HTML reports showing the text of each witness to `work`
with its matches in `matches` highlighted.
:param output_dir: directory to write report to
:type output_dir: `str`
:param work: name of work to highlight
:type text_name: `str`
:param matches_filename: fil... |
346,399 | def multipart_encode(params, boundary=None, cb=None):
if boundary is None:
boundary = gen_boundary()
else:
boundary = urllib.quote_plus(boundary)
headers = get_headers(params, boundary)
params = MultipartParam.from_params(params)
return MultipartYielder(params, boundary, cb), ... | Encode ``params`` as multipart/form-data.
``params`` should be a sequence of (name, value) pairs or MultipartParam
objects, or a mapping of names to values.
Values are either strings parameter values, or file-like objects to use as
the parameter value. The file-like objects must support .read() and ei... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.