Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
352,400 | def peek(contents):
if not isinstance(contents, byte_cls):
raise TypeError( % type_name(contents))
info, consumed = _parse(contents, len(contents))
return consumed | Parses a byte string of ASN.1 BER/DER-encoded data to find the length
This is typically used to look into an encoded value to see how long the
next chunk of ASN.1-encoded data is. Primarily it is useful when a
value is a concatenation of multiple values.
:param contents:
A byte string of BER/D... |
352,401 | def add_log_error(self, x, flag_also_show=False, E=None):
self.parent_form.add_log_error(x, flag_also_show, E) | Delegates to parent form |
352,402 | def get_risk_files(inputs):
rfs = {}
job_ini = inputs[]
for key in inputs:
if key == :
rfs[] = inputs[
] = inputs[key]
del inputs[]
elif key.endswith((, , )):
match = RISK_TYPE_REGEX.match(key)
if ... | :param inputs: a dictionary key -> path name
:returns: a pair (file_type, {risk_type: path}) |
352,403 | def _api_request(self, uri, method, **kwargs):
id_svc = self.identity
if not all((self.management_url, id_svc.token, id_svc.tenant_id)):
id_svc.authenticate()
if not self.management_url:
continue
parsed[pos] = _safe_quote(par... | Manages the request by adding any auth information, and retries
the request after authenticating if the initial request returned
and Unauthorized exception. |
352,404 | def mime(self):
mimes = []
for Kind in type(self).__mro__:
for mime in getattr(Kind, , []):
if mime not in mimes:
mimes.append(mime)
return mimes | A list of mime types (:class:`mutagen.text`) |
352,405 | def get_subscribers(self):
data = self.signal.instance_subscribers
if self.instance not in data:
data[self.instance] = MethodAwareWeakList()
return data[self.instance] | Get per-instance subscribers from the signal. |
352,406 | def p_case_list(p):
if len(p) == 1:
p[0] = node.stmt_list()
elif len(p) == 3:
assert isinstance(p[2], node.stmt_list)
p[0] = p[2]
elif len(p) == 6:
p[0] = node.if_stmt(
cond_expr=node.expr(
op="==", args=node.expr_list([p[2]])),
th... | case_list :
| CASE expr sep stmt_list_opt case_list
| CASE expr error stmt_list_opt case_list
| OTHERWISE stmt_list |
352,407 | def _proxy(self):
if self._context is None:
self._context = WorkerContext(
self._version,
workspace_sid=self._solution[],
sid=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkerContext for this WorkerInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerContext |
352,408 | def remove(self):
body = request.body.read()
indata = cjson.decode(body)
try:
indata = validateJSONInputNoCopy("migration_rqst", indata)
return self.dbsMigrate.removeMigrationRequest(indata)
except dbsException as he:
dbsExceptionHandler(he.eC... | Interface to remove a migration request from the queue.
Only Permanent FAILED/9 and PENDING/0 requests can be removed
(running and sucessed requests cannot be removed) |
352,409 | def get_shell(pid=None, max_depth=6):
pid = str(pid or os.getpid())
mapping = _get_process_mapping()
for proc_cmd in _iter_process_command(mapping, pid, max_depth):
if proc_cmd.startswith():
return _get_login_shell(proc_cmd)
name = os.path.basename(proc_cmd).lower()
... | Get the shell that the supplied pid or os.getpid() is running in. |
352,410 | def download(cls, filename, input_dir, dl_dir=None):
file_info = cls.parse_remote(filename)
if not dl_dir:
dl_dir = os.path.join(input_dir, file_info.container,
os.path.dirname(file_info.blob))
utils.safe_makedir(dl_dir)
out_fil... | Download the resource from the storage. |
352,411 | def rotate_board(self, angle, unit=):
if unit == :
angle = angle*math.pi/180
angle %= 2*math.pi
if angle not in [0, math.pi/2, math.pi, math.pi*3/2]:
raise ValueError()
new_pos = [[0 for _ in self.pos_range] for _ in self.pos_range]
cos_ang = ma... | Rotate the chessboard for a specific angle,
angle must be integral multiple of pi/2(90 degree) |
352,412 | def cycle(self):
try:
events = self.getEvents()
except requests.ConnectionError:
return
for event in events:
self.onEvent(event)
if self.autoAck:
event.ack() | Request one batch of events from Skype, calling :meth:`onEvent` with each event in turn.
Subclasses may override this method to alter loop functionality. |
352,413 | def xdifference(self, to):
x,y = 0,1
assert self.level == to.level
self_tile = list(self.to_tile()[0])
to_tile = list(to.to_tile()[0])
if self_tile[x] >= to_tile[x] and self_tile[y] <= self_tile[y]:
ne_tile, sw_tile = self_tile, to_tile
else:
... | Generator
Gives the difference of quadkeys between self and to
Generator in case done on a low level
Only works with quadkeys of same level |
352,414 | def QA_data_calc_marketvalue(data, xdxr):
mv = xdxr.query().loc[:,
[,
]].dropna()
res = pd.concat([data, mv], axis=1)
res = res.assign(
shares=res.shares_after.fillna(method=),
lshares=res.liquidity_after.fi... | 使用数据库数据计算复权 |
352,415 | def backup_complete(self):
if self.deploymentType != :
logging.warning(
)
return None
status = self.backup_progress()
perc_complete = int(re.search(r"\s([0-9]*)\s",
status[]).group(1))
file_size = int(... | Return boolean based on 'alternativePercentage' and 'size' returned from backup_progress (cloud only). |
352,416 | def paste(self, mimeData):
if self.isActive():
self.delete()
elif self._qpart.textCursor().hasSelection():
self._qpart.textCursor().deleteChar()
text = bytes(mimeData.data(self.MIME_TYPE)).decode()
lines = text.splitlines()
cursorLine, cursorCol ... | Paste recrangular selection.
Add space at the beginning of line, if necessary |
352,417 | def _should_split_column_cells(cls, column_cells: List[str]) -> bool:
return any(cls._should_split_cell(cell_text) for cell_text in column_cells) | Returns true if there is any cell in this column that can be split. |
352,418 | def with_color_stripped(f):
@wraps(f)
def colored_len(s):
s2 = re.sub(
COLOR_BEGIN_RGX + + COLOR_END_RGX,
lambda m: re.sub(COLOR_BEGIN_RGX, , m.group(1)),
s,
)
if re.search(COLOR_BEGIN_RGX, s2):
raise UnterminatedColorError(s)
... | A function decorator for applying to `len` or imitators thereof that strips
ANSI color sequences from a string before passing it on. If any color
sequences are not followed by a reset sequence, an `UnterminatedColorError`
is raised. |
352,419 | def simple_repr(obj: Any, attrnames: List[str],
with_addr: bool = False, joiner: str = COMMA_SPACE) -> str:
elements = ["{}={}".format(name, repr(getattr(obj, name)))
for name in attrnames]
return repr_result(obj, elements, with_addr=with_addr, joiner=joiner) | Convenience function for :func:`__repr__`.
Works its way through a list of attribute names, and creates a ``repr()``
representation assuming that parameters to the constructor have the same
names.
Args:
obj: object to display
attrnames: names of attributes to include
with_addr: ... |
352,420 | def create_draft_for_edit_extension(self, publisher_name, extension_name):
route_values = {}
if publisher_name is not None:
route_values[] = self._serialize.url(, publisher_name, )
if extension_name is not None:
route_values[] = self._serialize.url(, extension_na... | CreateDraftForEditExtension.
[Preview API]
:param str publisher_name:
:param str extension_name:
:rtype: :class:`<ExtensionDraft> <azure.devops.v5_0.gallery.models.ExtensionDraft>` |
352,421 | def get_posix_property(value, mode=POSIX):
if mode == POSIX_BYTES:
return unidata.ascii_posix_properties[value]
elif mode == POSIX_UNICODE:
return unidata.unicode_binary[
( + value[1:]) if value.startswith() else ( + value)
]
else:
return unidata.unicode_pos... | Retrieve the posix category. |
352,422 | def strip_wrapping(html):
if html.startswith() and html.endswith():
html = html[5:-6]
return html.strip() | Removes the wrapping that might have resulted when using get_html_tree(). |
352,423 | def buy(self, player, cost):
if cost > self.max_bid():
raise InsufficientFundsError()
elif not any(roster_slot.accepts(player) and roster_slot.occupant is None for roster_slot in self.roster):
raise NoValidRosterSlotError()
elif self.owns(player):
rai... | indicate that the player was bought at the specified cost
:param Player player: player to buy
:param int cost: cost to pay
:raises InsufficientFundsError: if owner doesn't have the money
:raises NoValidRosterSlotError: if owner doesn't have a slot this player could fill
:raises... |
352,424 | def serialize_value_list(self, list_elem, thelist):
for value in thelist:
value_elem = SubElement(list_elem, )
self.serialize_value(value_elem, value)
return list_elem | Serializes a list, where the values are objects of type
str, Attrib, or PathAttrib.
Example::
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value> |
352,425 | def traceroute(
self,
destination,
source=c.TRACEROUTE_SOURCE,
ttl=c.TRACEROUTE_TTL,
timeout=c.TRACEROUTE_TIMEOUT,
vrf=c.TRACEROUTE_VRF,
):
raise NotImplementedError | Executes traceroute on the device and returns a dictionary with the result.
:param destination: Host or IP Address of the destination
:param source (optional): Use a specific IP Address to execute the traceroute
:param ttl (optional): Maimum number of hops
:param timeout (optional): Num... |
352,426 | def _handle_exception(ignore_callback_errors, print_callback_errors, obj,
cb_event=None, node=None):
if not hasattr(obj, ):
obj._vispy_err_registry = {}
registry = obj._vispy_err_registry
if cb_event is not None:
cb, event = cb_event
exp_type =
else:
... | Helper for prining errors in callbacks
See EventEmitter._invoke_callback for a use example. |
352,427 | def createModels(self, numModels=1):
self._checkForOrphanedModels()
modelResults = []
for _ in xrange(numModels):
candidateParticle = None
if (self._maxModels is not None and
(self._resultsDB.numModels() - self._resultsDB.getNumErrModels()) >=
self._maxMod... | Create one or more new models for evaluation. These should NOT be models
that we already know are in progress (i.e. those that have been sent to us
via recordModelProgress). We return a list of models to the caller
(HypersearchWorker) and if one can be successfully inserted into
the models table (i.e. i... |
352,428 | def PushItem(self, item, block=True):
if not self._zmq_socket:
self._CreateZMQSocket()
if not self._terminate_event:
raise RuntimeError()
logger.debug(
.format(self.name, self.port))
last_retry_timestamp = time.time() + self.timeout_seconds
while not self._terminate_event... | Push an item on to the queue.
If no ZeroMQ socket has been created, one will be created the first time
this method is called.
Args:
item (object): item to push on the queue.
block (Optional[bool]): whether the push should be performed in blocking
or non-blocking mode.
Raises:
... |
352,429 | def computeNodeDepths(self, graph):
nodes = graph[]
depth = 0
while nodes:
next_nodes = []
for node in nodes:
node[] = depth
for link in node[]:
if not any(link[] is node for node in next_nodes):
... | Iteratively assign the depth (x-position) for each node.
Nodes are assigned the maximum depth of incoming neighbors plus one;
nodes with no incoming links are assigned depth zero, while
nodes with no outgoing links are assigned the maximum depth. |
352,430 | def appndi(item, cell):
assert isinstance(cell, stypes.SpiceCell)
if hasattr(item, "__iter__"):
for i in item:
libspice.appndi_c(ctypes.c_int(i), cell)
else:
item = ctypes.c_int(item)
libspice.appndi_c(item, cell) | Append an item to an integer cell.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndi_c.html
:param item: The item to append.
:type item: Union[float,Iterable[int]]
:param cell: The cell to append to.
:type cell: spiceypy.utils.support_types.SpiceCell |
352,431 | def _runshell(cmd, exception):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.wait() != 0:
raise BridgeException(exception)
return p | Run a shell command. if fails, raise a proper exception. |
352,432 | def sep_dist_floc(ConcAluminum, ConcClay, coag, material,
DIM_FRACTAL, DiamTarget):
return (material.Diameter
* (np.pi/(6
* frac_vol_floc_initial(ConcAluminum, ConcClay,
coag, material)
))**(... | Return separation distance as a function of floc size. |
352,433 | def tempput(local_path=None, remote_path=None, use_sudo=False,
mirror_local_mode=False, mode=None):
import warnings
warnings.simplefilter(, RuntimeWarning)
if remote_path is None:
remote_path = os.tempnam()
put(local_path, remote_path, use_sudo, mirror_local_mode, mode)
yiel... | Put a file to remote and remove it afterwards |
352,434 | def optimally_align_text(x, y, texts, expand=(1., 1.), add_bboxes=[],
renderer=None, ax=None,
direction=):
if ax is None:
ax = plt.gca()
if renderer is None:
r = get_renderer(ax.get_figure())
else:
r = renderer
xmin, xmax = s... | For all text objects find alignment that causes the least overlap with
points and other texts and apply it |
352,435 | def element_focus_should_not_be_set(self, locator):
self._info("Verifying element focus is not set" % locator)
self._check_element_focus(False, locator) | Verifies the element identified by `locator` does not have focus.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id | |
352,436 | def urltool(classqname, filt, reverse):
filt = re.compile(filt or )
rootCls = namedAny(classqname)
rules = list(_iterClass(rootCls))
arr = []
for item in sorted(rules):
if item.subKlein:
continue
matched = filt.search(item.rulePath)
matched = not matched if... | Dump all urls branching from a class as OpenAPI 3 documentation
The class must be given as a FQPN which points to a Klein() instance.
Apply optional [FILT] as a regular expression searching within urls. For
example, to match all urls beginning with api, you might use '^/api' |
352,437 | def search_ap(self, mode, query):
url = .format(self.host, mode, query)
return self.__get(url) | 搜索接入点
查看指定接入点的所有配置信息,包括所有监听端口的配置。
Args:
- mode: 搜索模式,可以是domain、ip、host
- query: 搜索文本
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回搜索结果,失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response... |
352,438 | def generate_id(self, agreement_id, types, values):
values_hash = utils.generate_multi_value_hash(types, values)
return utils.generate_multi_value_hash(
[, , ],
[agreement_id, self.address, values_hash]
) | Generate id for the condition.
:param agreement_id: id of the agreement, hex str
:param types: list of types
:param values: list of values
:return: id, str |
352,439 | def getNextNode(nodes,usednodes,parent):
for e in edges:
if e.source==parent:
if e.target in usednodes:
x = e.target
break
elif e.target==parent:
if e.source in usednoes:
x = e.source
break
return x | Get next node in a breadth-first traversal of nodes that have not been used yet |
352,440 | def open(self, external_dir=None):
if self.kind == :
with io.BytesIO(self._data.data) as f:
yield f
elif self.kind == :
filepath = self._data.linked_file[b].value
filepath = filepath.replace(, ).replace(, )
if not os.path.exists(fi... | Open the smart object as binary IO.
:param external_dir: Path to the directory of the external file.
Example::
with layer.smart_object.open() as f:
data = f.read() |
352,441 | def msregularize(msname, newname):
t = table(msname)
t1 = t.sort()
nadded = 0
for tsub in t.iter([, ]):
nmissing = t1.nrows() - tsub.nrows()
if nmissing < 0:
raise ValueError("A time/band chunk has too many rows")
if nmissing > 0:
... | Regularize an MS
The output MS will be such that it has the same number of baselines
for each time stamp. Where needed fully flagged rows are added.
Possibly missing rows are written into a separate MS <newname>-add.
It is concatenated with the original MS and sorted in order of TIME,
DATADESC_ID,... |
352,442 | def serialize_class(Cls):
metaclass = xtuml.get_metaclass(Cls)
attributes = [ % (name, ty.upper()) for name, ty in metaclass.attributes]
s = % metaclass.kind
s += .join(attributes)
s +=
return s | Serialize an xtUML metamodel class. |
352,443 | def info(self):
proc = Popen([, , ],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode().strip()
return u.format(version) | Returns the name and version of the current shell |
352,444 | def package_install(name, **kwargs):
cmd = + name
if kwargs.get(, False):
cmd += + kwargs[]
out, err = DETAILS[].sendline(cmd)
return parse(out) | Install a "package" on the ssh server |
352,445 | def _remove_bcbiovm_path():
cur_path = os.path.dirname(os.path.realpath(sys.executable))
paths = os.environ["PATH"].split(":")
if cur_path in paths:
paths.remove(cur_path)
os.environ["PATH"] = ":".join(paths) | Avoid referencing minimal bcbio_nextgen in bcbio_vm installation. |
352,446 | def connection(self):
heartbeat = self.container.config.get(
HEARTBEAT_CONFIG_KEY, DEFAULT_HEARTBEAT
)
transport_options = self.container.config.get(
TRANSPORT_OPTIONS_CONFIG_KEY, DEFAULT_TRANSPORT_OPTIONS
)
ssl = self.container.config.get(AMQP_SS... | Provide the connection parameters for kombu's ConsumerMixin.
The `Connection` object is a declaration of connection parameters
that is lazily evaluated. It doesn't represent an established
connection to the broker at this point. |
352,447 | def update_costs(self):
for var in self.indicators:
if var not in self.costs:
self.costs[var] = var.cost
else:
if var._get_primal() > self.integer_threshold:
self.costs[var] += var.cost
self.model.objective.set_linear_c... | Update the coefficients for the indicator variables in the objective.
Done incrementally so that second time the function is called,
active indicators in the current solutions gets higher cost than the
unused indicators. |
352,448 | def is_legal_object(self, c: OntologyClass) -> bool:
ranges = self.included_ranges()
return not ranges or c in ranges or c.super_classes_closure() & ranges | is_legal_object(c) = true if
- c in included_ranges(self) or
- super_classes_closure(c) intersection included_ranges(self) is not empty
Args:
c:
Returns: |
352,449 | def add_domain_name_list(list_name):
*
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_domain_names_list",
"params": [{"list_name": list_name}]}
response = __proxy__[](payload, True)
return _validate_change_result(response) | Add a list of policy domain names.
list_name(str): The name of the specific policy domain name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList |
352,450 | def adjust_from_utc_fields(*args, **kwargs):
raw_ts = Timestamp(*args, **kwargs)
offset = raw_ts.utcoffset()
if offset is None or offset == timedelta():
return raw_ts
adjusted = raw_ts + offset
if raw_ts.precision is None:
r... | Constructs a timestamp from UTC fields adjusted to the local offset if given. |
352,451 | def __get_boxes(self):
boxfile = self.__box_path
try:
box_builder = pyocr.builders.LineBoxBuilder()
with self.fs.open(boxfile, ) as file_desc:
boxes = box_builder.read_file(file_desc)
if boxes != []:
return boxes
... | Get all the word boxes of this page. |
352,452 | def id(self):
if self._id is None:
self._id = int(self._element.get())
return self._id | :return: the ID attribute of the sentence
:rtype: int |
352,453 | def process_request_thread(self, request, client_address):
handler = self.RequestHandlerClass(request, client_address, self)
try:
handler.handle_request()
self.request_complete_callback()
except Exception as e:
try:
handler.handle_error(e)
finally:
... | Override of ThreadingMixIn.process_request_thread() that delegates to the request handler. |
352,454 | def _assignrepr_bracketed2(assignrepr_bracketed1, values, prefix, width=None):
brackets = getattr(assignrepr_bracketed1, )
prefix += brackets[0]
lines = []
blanks = *len(prefix)
for (idx, subvalues) in enumerate(values):
if idx == 0:
lines.append(assignrepr_bracketed1(subval... | Return a prefixed, wrapped and properly aligned bracketed string
representation of the given 2-dimensional value matrix using function
|repr|. |
352,455 | def get_ecs_cluster_for_queue(queue_name, batch_client=None):
if batch_client is None:
batch_client = boto3.client()
queue_resp = batch_client.describe_job_queues(jobQueues=[queue_name])
if len(queue_resp[]) == 1:
queue = queue_resp[][0]
else:
raise BatchReadingError(
... | Get the name of the ecs cluster using the batch client. |
352,456 | def page_rank(self, damping_factor=0.85, max_iterations=100,
min_delta=0.00001):
nodes = self.get_node_list()
graph_size = len(nodes)
if graph_size == 0:
return {}
min_value = old_div((1.0-damping_factor),graph_size)
pagera... | API:
page_rank(self, damping_factor=0.85, max_iterations=100,
min_delta=0.00001)
Description:
Compute and return the page-rank of a directed graph.
This function was originally taken from here and modified for this
graph class: http://code.google... |
352,457 | def _check_file(self, f):
L.info(, f)
full_result = True
full_summary = OrderedDict()
try:
data = load_data(f)
except Exception as e:
L.error()
L.error(e.args)
return False, {f: OrderedDict([(, False)])}
try:
... | Run tests on a morphology file |
352,458 | def distance(self, other):
return np.linalg.norm(other.coords - self.coords) | Get distance between two sites.
Args:
other: Other site.
Returns:
Distance (float) |
352,459 | def flush(self):
if self.debug:
sys.stderr.write("%s: FLUSH INPUT (%i bytes waiting)\n" %(
self.__class__.__name__,
self.ser.inWaiting()
))
self.ser.flushInput() | Flush input buffers. |
352,460 | def _unfold_map(self, display_text_map):
from ..type.primitives import Type
lt_identifier = Id(display_text_map[]).get_identifier()
st_identifier = Id(display_text_map[]).get_identifier()
ft_identifier = Id(display_text_map[]).get_identifier()
try:
self._lang... | Parses a display text dictionary map. |
352,461 | def get_cache_key(self, offset=0, limit=0, order=None, post_slug=):
return hashlib.sha1(
.join([
str(self._get_data_source_url()),
str(offset),
str(limit),
str(order),
str(post_slug),
])
... | The return of Get |
352,462 | def load_params(self, fname):
save_dict = ndarray.load(fname)
arg_params = {}
aux_params = {}
for k, value in save_dict.items():
arg_type, name = k.split(, 1)
if arg_type == :
arg_params[name] = value
elif arg_type == :
... | Loads model parameters from file.
Parameters
----------
fname : str
Path to input param file.
Examples
--------
>>> # An example of loading module parameters.
>>> mod.load_params('myfile') |
352,463 | def replace_heroku_db(self, file_url):
self.print_message("Replacing database for Heroku app " % self.args.destination_app)
self.reset_heroku_database()
if file_url:
self.print_message("Restoring from URL " % file_url)
args = [
"heroku",
... | Replace Heroku database with database from specified source. |
352,464 | def _write_pidfile(self):
LOGGER.debug(, self.pidfile_path)
with open(self.pidfile_path, "w") as handle:
handle.write(str(os.getpid())) | Write the pid file out with the process number in the pid file |
352,465 | def read_login(collector, image, **kwargs):
docker_api = collector.configuration["harpoon"].docker_api
collector.configuration["authentication"].login(docker_api, image, is_pushing=False, global_docker=True) | Login to a docker registry with read permissions |
352,466 | def add_listener(self, event_name: str, listener: Callable):
self.listeners[event_name].append(listener)
return self | Add a listener. |
352,467 | def download_historical(tickers_list, output_folder):
__validate_list(tickers_list)
for ticker in tickers_list:
file_name = os.path.join(output_folder, ticker + )
with open(file_name, ) as f:
base_url =
try:
urlopen(base_url + ticker)
... | Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume. Files
will be saved to output_folder as <ticker>.csv.
:param tickers_list: List of tickers that will be returned.
... |
352,468 | def register_column(self,
column,
expr,
deltas=None,
checkpoints=None,
odo_kwargs=None):
self._table_expressions[column] = ExprData(
expr,
deltas,
... | Explicitly map a single bound column to a collection of blaze
expressions. The expressions need to have ``timestamp`` and ``as_of``
columns.
Parameters
----------
column : BoundColumn
The pipeline dataset to map to the given expressions.
expr : Expr
... |
352,469 | def get_wind(wxdata: [str], units: Units) -> ([str], Number, Number, Number, [Number]):
direction, speed, gust = , ,
variable = []
if wxdata:
item = copy(wxdata[0])
for rep in []:
item = item.replace(rep, )
item = item.replace(, )
if item.endswi... | Returns the report list and removed:
Direction string, speed string, gust string, variable direction list |
352,470 | def set_color(self, r, g, b):
chr(g & 0xFF),
chr(b & 0xFF))
self._color.write_value(command) | Set the red, green, blue color of the bulb. |
352,471 | def set_taskfileinfo(self, tfi):
self._taskfileinfo = tfi
if tfi:
self.set_element(tfi.task.element) | Set the :class:`jukeboxcore.filesys.TaskFileInfo` that the refobject represents.
:param tfi: the taskfileinfo for the refobject or None if nothing is loaded.
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` | None
:returns: None
:rtype: None
:raises: None |
352,472 | def needs_i8_conversion(arr_or_dtype):
if arr_or_dtype is None:
return False
return (is_datetime_or_timedelta_dtype(arr_or_dtype) or
is_datetime64tz_dtype(arr_or_dtype) or
is_period_dtype(arr_or_dtype)) | Check whether the array or dtype should be converted to int64.
An array-like or dtype "needs" such a conversion if the array-like
or dtype is of a datetime-like dtype
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
W... |
352,473 | def iswhsp(string):
string = stypes.stringToCharP(string)
return bool(libspice.iswhsp_c(string)) | Return a boolean value indicating whether a string contains
only white space characters.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/iswhsp_c.html
:param string: String to be tested.
:type string: str
:return:
the boolean value True if the string is empty or contains
... |
352,474 | def static_fit_result(fit_result, v_residual=None,
v_label=,
figsize=(5, 5), height_ratios=(3, 1), ms_data=8,
p_err=None, v_err=None, pdf_filen=None,
title=):
f, ax = plt.subplots(2, 1, sharex=True, figsize=figsize,
... | plot static compressional curve fitting result
:param fit_result: lmfit result object, see example jnb file for detail
:param v_residual: manual input of fit residual
:param v_label: label for volume axis
:param figsize: figure size
:param fitline: manual input of fit line, array of (v_fitline, p_f... |
352,475 | def _forecast_transform(f_d):
begins = f_d.get(, None)
issued = f_d.get(, None)
solid_stars = f_d.get(, None)
faded_stars = f_d.get(, None)
air_pressure = f_d.get(, None)
unit_pressure = f_d.get(, None)
air_temp = f_d.get(, None)
unit_temp = f_d.get(, None)
max = f_d.get(, None)... | Get attribute dict from flattened forecast dict. |
352,476 | def addPixmap(self, pixmap):
item = QtGui.QGraphicsPixmapItem(pixmap)
self.addToGroup(item)
return item | Adds a pixmap to this graphics item.
:param pixmap | <QtGui.QPixmap> |
352,477 | def generate_secret_key():
import string
import random
rng = random.SystemRandom()
return .join(
rng.choice(string.ascii_letters + string.digits)
for dummy in range(0, 256)
) | Generate secret key. |
352,478 | def pass_verbosity(f):
def new_func(*args, **kwargs):
kwargs[] = click.get_current_context().verbosity
return f(*args, **kwargs)
return update_wrapper(new_func, f) | Marks a callback as wanting to receive the verbosity as a keyword argument. |
352,479 | def linkify(self):
self.services.optimize_service_search(self.hosts)
self.linkify_one_command_with_commands(self.commands, )
self.linkify_one_command_with_commands(self.commands, )
self.linkify_one_command_with_commands(self.commands, )
self.linkify_one_comman... | Make 'links' between elements, like a host got a services list
with all its services in it
:return: None |
352,480 | def as_svg_data_uri(matrix, version, scale=1, border=None, color=,
background=None, xmldecl=False, svgns=True, title=None,
desc=None, svgid=None, svgclass=,
lineclass=, omitsize=False, unit=,
encoding=, svgversion=None, nl=False,
... | \
Converts the matrix to a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by default (set ``nl`` to
``True`` to enable it).
Aside from the missing ``out`` parameter and the different ``xmldecl``
and ``nl`` defa... |
352,481 | def simplify_soc_marker(self, text, prev_text):
if self.cell_marker_start:
return text
if self.is_code() and text and text[0] == self.comment + :
if not prev_text or not prev_text[-1].strip():
text[0] = self.comment +
return text | Simplify start of cell marker when previous line is blank |
352,482 | def profileMain(self, M, z):
c = self.c_M_z(M, z)
r200 = self.r200_M(M)
rho0 = self.rho0_c(c)
Rs = r200/c
return r200, rho0, c, Rs | returns all needed parameter (in comoving units modulo h) to draw the profile of the main halo
r200 in co-moving Mpc/h
rho_s in h^2/Mpc^3 (co-moving)
Rs in Mpc/h co-moving
c unit less |
352,483 | def constant_cache(method):
@functools.wraps(method)
def wrapper(self, context):
if not self._is_cached:
return method(self, context)
name = context.name
cached = self._constant_cache.get(name, None)
if cached is None:
data = self.... | Caches constant arrays associated with an array name.
The intent of this decorator is to avoid the cost
of recreating and storing many arrays of constant data,
especially data created by np.zeros or np.ones.
Instead, a single array of the first given shape is created
and any further requests for co... |
352,484 | def get_causal_edge(stmt, activates):
any_contact = any(
evidence.epistemics.get(, False)
for evidence in stmt.evidence
)
if any_contact:
return pc.DIRECTLY_INCREASES if activates else pc.DIRECTLY_DECREASES
return pc.INCREASES if activates else pc.DECREASES | Returns the causal, polar edge with the correct "contact". |
352,485 | def load(self, filename):
dir_name = os.path.dirname(filename)
mod_name = os.path.basename(filename).split()[0]
self.filename = mod_name
sys.path.insert(0, dir_name)
mod = __import__(mod_name)
sys.path.remove(dir_name)
pipers, xtras, pipes = mod.pipeline... | Instanciates (loads) pipeline from a source code file.
Arguments:
- filename(``path``) location of the pipeline source code. |
352,486 | def copy(self):
new = self.__class__()
do_not_copy_by_ref = {"metabolites", "reactions", "genes", "notes",
"annotation", "groups"}
for attr in self.__dict__:
if attr not in do_not_copy_by_ref:
new.__dict__[attr] = self.__dict__[a... | Provides a partial 'deepcopy' of the Model. All of the Metabolite,
Gene, and Reaction objects are created anew but in a faster fashion
than deepcopy |
352,487 | def _flush_index(self):
data = {: self.version, : self._index}
with open(self._get_path(), ) as f:
json.dump(data, f)
self.__index = None | Writes the current list of file paths in the index to the json file
and then sets self.__index = None. |
352,488 | def acquisition_function(self, x):
return self._penalized_acquisition(x, self.model, self.X_batch, self.r_x0, self.s_x0) | Returns the value of the acquisition function at x. |
352,489 | def underline(text):
text += "\n"
for i in range(len(text)-1):
text += "="
text += "\n"
return text | Takes a string, and returns it underscored. |
352,490 | def print_data(zone_id, connection):
result = connection.execute(
select([cast(zone_id.encode(), BYTEA), test_table]))
result = result.fetchall()
ZONE_ID_INDEX = 0
print("use zone_id: ", zone_id)
print("{:<3} - {} - {} - {}".format("id", , "data", "raw_data"))
for row in re... | fetch data from database (use zone_id if not empty/None) and print to
console |
352,491 | def _ModifyInterface(
self, interface_config, config_key, config_value, replace=False):
config_entry = % (config_key, config_value)
if not open(interface_config).read().count(config_key):
with open(interface_config, ) as config:
config.write( % config_entry)
elif replace:
for... | Write a value to a config file if not already present.
Args:
interface_config: string, the path to a config file.
config_key: string, the configuration key to set.
config_value: string, the value to set for the configuration key.
replace: bool, replace the configuration option if already pr... |
352,492 | def _is_empty(self, response):
if not response.content:
return True
try:
body = response.json()
return not body
except ValueError:
raise DeserializationError(
"Error occurred in deserializing the response body.") | Check if response body contains meaningful content.
:rtype: bool
:raises: DeserializationError if response body contains invalid
json data. |
352,493 | def read_nb(filename, solution) -> nbformat.NotebookNode:
with open(filename, ) as f:
nb = nbformat.read(f, as_version=4)
email = find_student_email(nb)
preamble = nbformat.v4.new_markdown_cell(
source= + email, metadata={: []})
tags_to_check = TAGS if not solution else SOL_TAGS
... | Takes in a filename of a notebook and returns a notebook object containing
only the cell outputs to export. |
352,494 | def update_status(self):
if (self.status is not None) and self.status > 0:
return False
old_status = self.status
job_dir = self.run_dir + os.sep + self.id
if os.path.isfile(run_dir + os.sep + ):
self.status = self.FAILED
... | returns True if status has changed |
352,495 | def headers_to_include_from_request(curr_request):
return {
h: v for h, v in curr_request.META.items() if h in _settings.HEADERS_TO_INCLUDE} | Define headers that needs to be included from the current request. |
352,496 | def infer_typing_namedtuple(node, context=None):
try:
func = next(node.func.infer())
except InferenceError:
raise UseInferenceDefault
if func.qname() != "typing.NamedTuple":
raise UseInferenceDefault
if len(node.args) != 2:
raise UseInferenceDefault
... | Infer a typing.NamedTuple(...) call. |
352,497 | def event_handler_event_handler_list_description(self, **kwargs):
config = ET.Element("config")
event_handler = ET.SubElement(config, "event-handler", xmlns="urn:brocade.com:mgmt:brocade-event-handler")
event_handler_list = ET.SubElement(event_handler, "event-handler-list")
name... | Auto Generated Code |
352,498 | def get_success_url(self):
return .format(
reverse(
,
kwargs={
: self.forum_post.topic.forum.slug,
: self.forum_post.topic.forum.pk,
: self.forum_post.topic.slug,
: self.forum_pos... | Returns the URL to redirect the user to upon valid form processing. |
352,499 | def column_name(self, source, allele_group):
return self.column_format.format(
source=source,
allele_group=allele_group) | Parameters
----------
source : string
name of the ReadSource
allele_group : string
one of: num_ref, num_alt, total_depth
Returns
----------
column name : string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.