Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
371,300 | def PriceHourly(self):
units = self.PriceUnits()
return(units[]*self.cpu+units[]*self.memory+units[]*self.storage+units[]) | Returns the total hourly price for the server.
Sums unit prices with unit volumes.
>>> clc.v2.Server("NY1BTDIPHYP0101").PriceHourly()
0.02857 |
371,301 | def sequencetyper(self):
for sample in self.metadata.samples:
if sample.general.bestassemblyfile != :
if type(sample[self.analysistype].allelenames) == list:
if sample[self.analysistype].profile != :
... | Determines the sequence type of each strain based on comparisons to sequence type profiles |
371,302 | def fields(self):
return {k:getattr(self, k, None) for k in self.schema.fields} | return all the fields and their raw values for this Orm instance. This
property returns a dict with the field names and their current values
if you want to control the values for outputting to an api, use .jsonable() |
371,303 | def meta_wrapped(f):
@wraps(f)
def wrapped(self, field, *args, **kwargs):
html = "{label}{errors}{original}<small>{description}</small>".format(
label=field.label(class_=),
original=f(self, field, *args, **kwargs),
errors=render_field_errors(field) or ,
... | Add a field label, errors, and a description (if it exists) to
a field. |
371,304 | def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,
request, request_token=None,
access_token=None):
log.debug(, client_key)
nonce_exists = self._noncegetter(
client_key=client_key, timestamp=... | Validate the timestamp and nonce is used or not. |
371,305 | def proximal_l2(space, lam=1, g=None):
r
lam = float(lam)
if g is not None and g not in space:
raise TypeError(.format(g, space))
class ProximalL2(Operator):
def __init__(self, sigma):
super(ProximalL2, self).__init__(
domain=space, r... | r"""Proximal operator factory of the l2-norm/distance.
Function for the proximal operator of the functional ``F`` where ``F``
is the l2-norm (or distance to g, if given)::
``F(x) = lam ||x - g||_2``
Parameters
----------
space : `LinearSpace`
Domain of F(x). Needs to be a Hilbert... |
371,306 | def nla_get_u64(nla):
tmp = c_uint64(0)
if nla and nla_len(nla) >= sizeof(tmp):
tmp = c_uint64.from_buffer(nla_data(nla)[:SIZEOF_U64])
return int(tmp.value) | Return value of 64 bit integer attribute as an int().
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L649
Positional arguments:
nla -- 64 bit integer attribute (nlattr class instance).
Returns:
Payload as an int(). |
371,307 | def parents(self):
if self._parents is None:
bottomups = tuple(Relationship.bottomup())
self._parents = TermList()
self._parents.extend(
[ other
for rship,others in six.iteritems(self.relations)
for other i... | ~TermList: The direct parents of the `Term`. |
371,308 | def get_dos_from_id(self, task_id):
args = {: task_id}
fields = []
structure = self.get_structure_from_id(task_id)
dosid = None
for r in self.query(fields, args):
dosid = r[][-1][]
if dosid is not None:
self._fs = gridfs.GridFS(self.db, )
... | Overrides the get_dos_from_id for the MIT gridfs format. |
371,309 | def grab_gpus(num_gpus=1, gpu_select=None, gpu_fraction=0.95, max_procs=-1):
os.environ[] = ""
if num_gpus == 0:
return 0
logger = logging.getLogger(__name__)
try:
py3nvml.nvmlInit()
except:
str_ =
warnings.warn(str_, RuntimeWarning)
logger.w... | Checks for gpu availability and sets CUDA_VISIBLE_DEVICES as such.
Note that this function does not do anything to 'reserve' gpus, it only
limits what GPUS your program can see by altering the CUDA_VISIBLE_DEVICES
variable. Other programs can still come along and snatch your gpu. This
function is more ... |
371,310 | def outputPoint(self):
node = self.outputNode()
if not node:
return self._outputPoint
hotspot = self.outputHotspot()
olocation = self.outputLocation()
ofixedx = self.outputFixedX()
ofixedy = self.outputFixedY()
l... | Returns a scene space point that the connection \
will draw to as its output source. If the connection \
has a node defined, then it will calculate the output \
point based on the position of the node, factoring in \
preference for output location and fixed positions. If \
the... |
371,311 | def _compute_raw_moments(self, n_counter, k_counter):
r
alpha_multipliers, beta_multipliers = self._get_parameter_symbols(n_counter, k_counter)
out_mat = sp.Matrix([a * b for a,b in zip(alpha_multipliers, beta_multipliers)])
out_mat = out_mat.applyfunc(sp.expand)
return out_mat | r"""
Compute :math:`X_i`
Gamma type 1: :math:`X_i = \frac {\beta_i}{\beta_0}Y_0 + Y_i`
Gamma type 2: :math:`X_i = \sum_{k=0}^{i} \frac {\beta_i}{\beta_k}Y_k`
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
:type n_counter: list... |
371,312 | def isMasterReqLatencyTooHigh(self):
format(MONITORING_PREFIX, self, r[1], r[0]))
else:
logger.trace("{} found master's latency to be lower than the "
"threshold for all requests.".format(self))
return r | Return whether the request latency of the master instance is greater
than the acceptable threshold |
371,313 | def _ancestors_or_self(
self, qname: Union[QualName, bool] = None) -> List[InstanceNode]:
res = [] if qname and self.qual_name != qname else [self]
return res + self.up()._ancestors(qname) | XPath - return the list of receiver's ancestors including itself. |
371,314 | def _check_portname(name):
if not isinstance(name, string_types) or not in name:
raise SaltInvocationError(
{0}\.format(name)
)
path = os.path.join(, name)
if not os.path.isdir(path):
raise SaltInvocationError({0}\.format(path))
return path | Check if portname is valid and whether or not the directory exists in the
ports tree. |
371,315 | def register_calculator_view(request):
if request.method == "POST":
form = CalculatorRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Succ... | Register a calculator. |
371,316 | def ip_hide_as_path_holder_as_path_access_list_instance(self, **kwargs):
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
hide_as_path_holder = ET.SubElement(ip, "hide-as-path-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-... | Auto Generated Code |
371,317 | def run(self, *args):
params = self.parser.parse_args(args)
organization = params.organization
domain = params.domain
is_top_domain = params.top_domain
overwrite = params.overwrite
if params.add:
code = self.add(organization, domain, is_top_domain, ... | List, add or delete organizations and domains from the registry.
By default, it prints the list of organizations available on
the registry. |
371,318 | def remove_old(self, max_log_time):
files = glob.glob(.format(self.log_dir))
files = list(map(lambda x: os.path.basename(x), files))
for log_file in files:
name = os.path.splitext(log_file)[0]
timestamp = name.split(, maxsplit=1)[1]
... | Remove all logs which are older than the specified time. |
371,319 | def ingest_data(self, data, cat_name, id_col, ra_col=, dec_col=, cat_loc=, append=False, count=-1):
if not append and cat_name in self.catalogs:
print(.format(cat_name))
else:
if isinstance(data, str):
cat_l... | Ingest a data file and regroup sources
Parameters
----------
data: str, pandas.DataFrame, astropy.table.Table
The path to the exported VizieR data or the data table
cat_name: str
The name of the added catalog
id_col: str
The name of th... |
371,320 | def save(self, filename="temp.pkl"):
output = open(filename, )
cPickle.dump(self.tm, output, protocol=cPickle.HIGHEST_PROTOCOL) | Save TM in the filename specified above |
371,321 | def send_ether_over_wpa(self, pkt, **kwargs):
payload = LLC() / SNAP() / pkt[Ether].payload
dest = pkt.dst
if dest == "ff:ff:ff:ff:ff:ff":
self.send_wpa_to_group(payload, dest)
else:
assert dest == self.client
self.send_wpa_to_client(payload) | Send an Ethernet packet using the WPA channel
Extra arguments will be ignored, and are just left for compatibility |
371,322 | def colorbar(self, cmap, position="right",
label="", clim=("", ""),
border_width=0.0, border_color="black",
**kwargs):
self._configure_2d()
cbar = scene.ColorBarWidget(orientation=position,
label_str=label,... | Show a ColorBar
Parameters
----------
cmap : str | vispy.color.ColorMap
Either the name of the ColorMap to be used from the standard
set of names (refer to `vispy.color.get_colormap`),
or a custom ColorMap object.
The ColorMap is used to apply a g... |
371,323 | def exit_with_exc_info(code=1, message=, print_tb=False, exception=None):
exc_type, exc_value = (exception.__class__, exception) \
if exception is not None else sys.exc_info()[:2]
if exc_type is not None:
if print_tb:
traceback.print_exc()
elif isinsta... | Exits the program, printing information about the last exception (if
any) and an optional error message. Uses *exception* instead if provided.
:param code: Exit code.
:type code: integer (valid exit code, 0-255)
:param message: Message to be printed after the exception information.
:type message: ... |
371,324 | def timestamp(num_params, p_levels, k_choices, N):
string = "_v%s_l%s_gs%s_k%s_N%s_%s.txt" % (num_params,
p_levels,
k_choices,
N,
... | Returns a uniform timestamp with parameter values for file identification |
371,325 | def command_line_arguments(command_line_parameters):
parser = argparse.ArgumentParser(description=, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(, , choices = all_algorithms, default = (,), nargs = , help = )
parser.add_argument(, action = , help = )
parser.add_ar... | Defines the command line parameters that are accepted. |
371,326 | def send_login_signal(self, request, user, profile, client):
signals.login.send(sender=profile.__class__, user=user,
profile=profile, client=client, request=request) | Send a signal that a user logged in. This signal should be sent only if
the user was *not* logged into Django. |
371,327 | def update_utxoset(self, transaction):
spent_outputs = [
spent_output for spent_output in transaction.spent_outputs
]
if spent_outputs:
self.delete_unspent_outputs(*spent_outputs)
self.store_unspent_outputs(
*[utxo._asdict() for utxo in transa... | Update the UTXO set given ``transaction``. That is, remove
the outputs that the given ``transaction`` spends, and add the
outputs that the given ``transaction`` creates.
Args:
transaction (:obj:`~bigchaindb.models.Transaction`): A new
transaction incoming into the sy... |
371,328 | def list_from_env(key, default=""):
try:
val = os.environ.get(key, default)
return val.split()
except (KeyError, ValueError):
return [] | Splits a string in the format "a,b,c,d,e,f" into
['a', 'b', 'c', 'd', 'e', 'f', ] |
371,329 | def run(self, steps=None, resume=False, redo=None):
recipe = {
"name" : self.name,
"steps" : []
}
start_at = 0
if redo:
recipe = utils.readJson(redo)
self.log.info(.format(recipe[], redo))
self.log.info()... | Run a Stimela recipe.
steps : recipe steps to run
resume : resume recipe from last run
redo : Re-run an old recipe from a .last file |
371,330 | def get_force_single(self, component_info=None, data=None, component_position=None):
components = []
append_components = components.append
for _ in range(component_info.plate_count):
component_position, plate = QRTPacket._get_exact(
RTForcePlateSingle, data, ... | Get a single force data channel. |
371,331 | def download(self, path, args=[], filepath=None, opts={},
compress=True, **kwargs):
url = self.base + path
wd = filepath or
params = []
params.append((, ))
params.append((, ))
if compress:
params.append((, ))
for opt in opt... | Makes a request to the IPFS daemon to download a file.
Downloads a file or files from IPFS into the current working
directory, or the directory given by ``filepath``.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.ex... |
371,332 | def plugin_method(*plugin_names):
def wrapper(callable_obj):
for plugin_name in plugin_names:
if not hasattr(callable_obj, plugin_name):
setattr(callable_obj, plugin_name, True)
return callable_obj
return wrapper | Plugin Method decorator.
Signs a web handler function with the plugins to be applied as attributes.
Args:
plugin_names (list): A list of plugin callable names
Returns:
A wrapped handler callable.
Examples:
>>> @plugin_method('json', 'bill')
... def method():
..... |
371,333 | def _get_attrs(self):
attrs = []
attrs.append(("N Blocks", self.n_blocks, "{}"))
bds = self.bounds
attrs.append(("X Bounds", (bds[0], bds[1]), "{:.3f}, {:.3f}"))
attrs.append(("Y Bounds", (bds[2], bds[3]), "{:.3f}, {:.3f}"))
attrs.append(("Z Bounds", (bds[4], bds... | An internal helper for the representation methods |
371,334 | def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0):
log = logging.getLogger(mod_logger + )
if not isinstance(source_ip_address, basestring):
msg =
log.error(msg)
raise TypeError(msg)
if not isinstance(desired_source_ip_address, basestrin... | Configures the source IP address for a Linux interface
:param source_ip_address: (str) Source IP address to change
:param desired_source_ip_address: (str) IP address to configure as the source in outgoing packets
:param device_num: (int) Integer interface device number to configure
:return: None
:r... |
371,335 | def temporal_participation_coeff(tnet, communities=None, decay=None, removeneg=False):
r
if communities is None:
if isinstance(tnet, dict):
if in tnet.keys():
communities = tnet[]
else:
raise ValueError()
else:
raise ValueErro... | r'''
Temporal participation coefficient is a measure of diversity of connections across communities for individual nodes.
Parameters
----------
tnet : array, dict
graphlet or contact sequence input. Only positive matrices considered.
communities : array
community vector. Either 1D (... |
371,336 | def compile_tag_re(self, tags):
return re.compile(self.raw_tag_re % tags, self.re_flags) | Return the regex used to look for Mustache tags compiled to work with
specific opening tags, close tags, and tag types. |
371,337 | def handle_404(request, exception):
error = format_error(title=, detail=str(exception))
return json(return_an_error(error), status=HTTPStatus.NOT_FOUND) | Handle 404 Not Found
This handler should be used to handle error http 404 not found for all
endpoints or if resource not available. |
371,338 | def median_high(data):
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
return data[n // 2] | Return the high median of data.
When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned. |
371,339 | def is_text_file(file_path: str) -> bool:
import codecs
expanded_path = os.path.abspath(os.path.expanduser(file_path.strip()))
valid_text_file = False
try:
with codecs.open(expanded_path, encoding=, errors=) as f:
if sum(1 for line in f) > 0:
... | Returns if a file contains only ASCII or UTF-8 encoded text.
:param file_path: path to the file being checked
:return: True if the file is a text file, False if it is binary. |
371,340 | def addFeatureSet(self, featureSet):
id_ = featureSet.getId()
self._featureSetIdMap[id_] = featureSet
self._featureSetIds.append(id_)
name = featureSet.getLocalId()
self._featureSetNameMap[name] = featureSet | Adds the specified featureSet to this dataset. |
371,341 | def add_mountains(self):
from noise import pnoise2
import random
random.seed()
octaves = (random.random() * 0.5) + 0.5
freq = 17.0 * octaves
for y in range(self.grd.grid_height - 1):
for x in range(self.grd.grid_width - 1):
pixel = s... | instead of the add_blocks function which was to produce
line shaped walls for blocking path finding agents, this
function creates more natural looking blocking areas like
mountains |
371,342 | def _make_eval_func(self, tensors, session, feed_dict, fetches,
callback=None):
if not isinstance(tensors, list):
tensors = [tensors]
num_tensors = len(tensors)
def eval_func(x):
shapes = dict(zip(self._vars, self._var_shapes))
augmented_feed_dict = {
... | Construct a function that evaluates a `Tensor` or list of `Tensor`s. |
371,343 | def _load_options(self, container, **options):
for opt in self.dict_options():
options.setdefault(opt, container)
return anyconfig.utils.filter_options(self._load_opts, options) | Select backend specific loading options. |
371,344 | def numberOfConnectedDistalSynapses(self, cells=None):
if cells is None:
cells = xrange(self.numberOfCells())
n = _countWhereGreaterEqualInRows(self.internalDistalPermanences, cells,
self.connectedPermanenceDistal)
for permanences in self.distalPermanences:... | Returns the number of connected distal synapses on these cells.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells. If None return count for all cells. |
371,345 | def parse_results_mol2(mol2_outpath):
docked_ligands = pd.DataFrame()
lines = [line.strip() for line in open(mol2_outpath, )]
props = {}
for i, line in enumerate(lines):
if line.startswith():
ligand = line.strip().strip().replace(, ).replace(, ).split()[1]
line = l... | Parse a DOCK6 mol2 output file, return a Pandas DataFrame of the results.
Args:
mol2_outpath (str): Path to mol2 output file
Returns:
DataFrame: Pandas DataFrame of the results |
371,346 | def set_server_admin_password(self, server_name, admin_password):
_validate_not_none(, server_name)
_validate_not_none(, admin_password)
return self._perform_post(
self._get_servers_path(server_name) + ,
_SqlManagementXmlSerializer.set_server_admin_password_to_xm... | Reset the administrator password for a server.
server_name:
Name of the server to change the password.
admin_password:
The new administrator password for the server. |
371,347 | def decrypt(self, data, nounce=None):
if nounce is None:
nounce = self._in_counter.to_bytes(length=8, byteorder=)
self._in_counter += 1
decrypted = self._enc_in.open(
b + nounce, data, bytes())
if not decrypted:
raise Exception()
... | Decrypt data with counter or specified nounce. |
371,348 | def set_connection_logging(self, loadbalancer, val):
uri = "/loadbalancers/%s/connectionlogging" % utils.get_id(loadbalancer)
val = str(val).lower()
req_body = {"connectionLogging": {
"enabled": val,
}}
resp, body = self.api.method_put(uri, body=r... | Sets the connection logging for the given load balancer. |
371,349 | def mlem(op, x, data, niter, callback=None, **kwargs):
osmlem([op], x, [data], niter=niter, callback=callback,
**kwargs) | Maximum Likelihood Expectation Maximation algorithm.
Attempts to solve::
max_x L(x | data)
where ``L(x | data)`` is the Poisson likelihood of ``x`` given ``data``.
The likelihood depends on the forward operator ``op`` such that
(approximately)::
op(x) = data
Parameters
----... |
371,350 | def reset(self):
self.getsCounter = 0
self.processedRequests = {}
self.responses = {}
self.transactions = {} | Clear the values of all attributes of the transaction store. |
371,351 | def chooseStep(self, divisors=None, binary=False):
self.binary = binary
if divisors is None:
divisors = [4, 5, 6]
else:
for divisor in divisors:
self.checkFinite(divisor, )
if divisor < 1:
raise GraphError(
... | Choose a nice, pretty size for the steps between axis labels.
Our main constraint is that the number of divisions must be taken
from the divisors list. We pick a number of divisions and a step
size that minimizes the amount of whitespace ("slop") that would
need to be included outside o... |
371,352 | def available_modes_with_ids(self):
if not self._available_mode_ids:
all_modes = FIXED_MODES.copy()
self._available_mode_ids = all_modes
modes = self.get_available_modes()
try:
if modes:
simple_mode... | Return list of objects containing available mode name and id. |
371,353 | def guess_media_type(filepath):
o = subprocess.check_output([, , , filepath])
o = o.strip()
return o | Returns the media-type of the file at the given ``filepath`` |
371,354 | def volume_adjusted_moving_average(close_data, volume, period):
catch_errors.check_for_input_len_diff(close_data, volume)
catch_errors.check_for_period_error(close_data, period)
avg_vol = np.mean(volume)
vol_incr = avg_vol * 0.67
vol_ratio = [val / vol_incr for val in volume]
close_vol = n... | Volume Adjusted Moving Average.
Formula:
VAMA = SUM(CLOSE * VolumeRatio) / period |
371,355 | def exists(name, path=None):
*
_exists = name in ls_(path=path)
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists | Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name |
371,356 | def get_pandasframe(self):
if self.dataset:
self._load_dimensions()
return self._get_pandasframe_one_dataset()
return self._get_pandasframe_across_datasets() | The method loads data from dataset |
371,357 | def get_site(self, site_id):
url = "/2/sites/%s" % site_id
return self.site_from_json(self._get_resource(url)["site"]) | Returns site data.
http://dev.wheniwork.com/#get-existing-site |
371,358 | def add_trendline(self,date0,date1,on=,text=None,**kwargs):
d={:,:date0,:date1,:on,:text}
d.update(**kwargs)
self.trendlines.append(d) | Adds a trendline to the QuantFigure.
Given 2 dates, the trendline is connected on the data points
that correspond to those dates.
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data series in which the
trendline should be... |
371,359 | def endings(self):
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
return self.get_analysis_element(ENDING) | The list of word endings.
Ambiguous cases are separated with pipe character by default.
Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries. |
371,360 | def dumpdb(args):
if len(args.args) < 2:
raise ParserError()
ds = _get_dataset(args)
db = Database(ds, fname=args.args[1])
mdpath = Path(args.args[2]) if len(args.args) > 2 else ds.tablegroup._fname
args.log.info(.format(db.to_cldf(mdpath.parent, mdname=mdpath.name))) | cldf dumpdb <DATASET> <SQLITE_DB_PATH> [<METADATA_PATH>] |
371,361 | def write_conll(self, fname):
if not in self.fields:
raise InvalidFieldsException("dataset is not in CONLL format: missing label field")
def instance_to_conll(inst):
tab = [v for k, v in inst.items() if k != ]
return .format(inst[], .join([.join([ if e is N... | Serializes the dataset in CONLL format to fname |
371,362 | def fail(self, cmd, title=None, message=None):
if message is None:
message = self.handle_exc()
else:
message = escape(message)
self.db.send(
% dump({
: escape(title or % cmd),
: message
})
) | Send back captured exceptions |
371,363 | def _knit(fin, fout,
opts_knit=,
opts_chunk=):
script = (
)
rcmd = (, ,
script.format(input=fin, output=fout,
opts_knit=opts_knit, opts_chunk=opt... | Use knitr to convert r markdown (or anything knitr supports)
to markdown.
fin / fout - strings, input / output filenames.
opts_knit - string, options to pass to knit
opts_shunk - string, chunk options
options are passed verbatim to knitr:knit running in Rscript. |
371,364 | def map_pixel_inv(row, col, cellx, celly, xmin, ymax):
col = np.asarray(col)
row = np.asarray(row)
point_x = xmin+col*cellx
point_y = ymax+row*celly
return point_x, point_y | Usage:
map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax)
where:
xmin is leftmost X coordinate in system
ymax is topmost Y coordinate in system
Example:
raster = HMISea.tif
ndv, xsize, ysize, geot, projection, datatype = get_geo_info(rast... |
371,365 | def close(self):
self.flush()
self.stream.close()
logging.StreamHandler.close(self) | Close the stream. |
371,366 | def _proxy(self):
if self._context is None:
self._context = CountryContext(self._version, iso_code=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: CountryContext for this CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryContext |
371,367 | def datashape_type_to_numpy(type_):
if isinstance(type_, Option):
type_ = type_.ty
if isinstance(type_, DateTime):
return np.dtype()
if isinstance(type_, String):
return np.dtype(object)
if type_ in integral:
return np.dtype()
else:
return type_.to_numpy_... | Given a datashape type, return the associated numpy type. Maps
datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the
numpy datetime returned by datashape isn't supported by pipeline.
Parameters
----------
type_: datashape.coretypes.Type
The datashape type.
Returns
... |
371,368 | def process_response(self, request, response):
if not hasattr(request, ) or not request._cache_update_cache:
return response
patch_response_headers(response, timeout)
if timeout:
cache_key = learn_cache_key(request, response, timeout, self.key_prefix... | Sets the cache, if needed. |
371,369 | def plot_final(self, ax):
bnmask = np.array(
list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int)
def M(x): return np.delete(x, bnmask)
if (self.cadence == ) or (len(self.time) < 4000):
ax.plot(M(self.time), M(self.flux), ls=,
... | Plots the final de-trended light curve. |
371,370 | async def handle_json_response(responses):
json_data = {}
if responses.status != 200:
err_msg = HttpProcessingError(code=responses.status,
message=await responses.json())
logging.error("Wallabag: aiohttp error {err_msg}".format(
... | get the json data response
:param responses: the json response
:return the json data without 'root' node |
371,371 | def hide_routemap_holder_route_map_content_set_origin_origin_igp(self, **kwargs):
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElement(hide_routemap_holder, "route-map... | Auto Generated Code |
371,372 | def set_kill_on_exit_mode(bKillOnExit = False):
try:
win32.DebugSetProcessKillOnExit(bKillOnExit)
except (AttributeError, WindowsError):
return False
return True | Defines the behavior of the debugged processes when the debugging
thread dies. This method only affects the calling thread.
Works on the following platforms:
- Microsoft Windows XP and above.
- Wine (Windows Emulator).
Fails on the following platforms:
- Microsoft ... |
371,373 | def prepare(self, config_file=None, user=None, password=None, **kwargs):
if config_file is not None:
self.read_config(config_file)
else:
self._prepare_account(user, password, **kwargs)
self.autologin() | 登录的统一接口
:param config_file 登录数据文件,若无则选择参数登录模式
:param user: 各家券商的账号或者雪球的用户名
:param password: 密码, 券商为加密后的密码,雪球为明文密码
:param account: [雪球登录需要]雪球手机号(邮箱手机二选一)
:param portfolio_code: [雪球登录需要]组合代码
:param portfolio_market: [雪球登录需要]交易市场,
可选['cn', 'us', 'hk'] 默认 'cn' |
371,374 | def query_parent_objects(self, context, query=None):
if query is None:
return self.get_parent_objects(context)
catalog = None
try:
catalogs = api.get_catalogs_for(context)
catalog = catalogs[0]
return map(api.... | Return the objects of the same type from the parent object
:param query: Catalog query to narrow down the objects
:type query: dict
:returns: Content objects of the same portal type in the parent |
371,375 | def clear_sonos_playlist(self, sonos_playlist, update_id=0):
if not isinstance(sonos_playlist, DidlPlaylistContainer):
sonos_playlist = self.get_sonos_playlist_by_attr(,
sonos_playlist)
count = self.music_library.browse(ml... | Clear all tracks from a Sonos playlist.
This is a convenience method for :py:meth:`reorder_sonos_playlist`.
Example::
device.clear_sonos_playlist(sonos_playlist)
Args:
sonos_playlist
(:py:class:`~.soco.data_structures.DidlPlaylistContainer`):
... |
371,376 | def insertOntology(self, ontology):
try:
models.Ontology.create(
id=ontology.getName(),
name=ontology.getName(),
dataurl=ontology.getDataUrl(),
ontologyprefix=ontology.getOntologyPrefix())
except Excepti... | Inserts the specified ontology into this repository. |
371,377 | def rotate_in_plane(chi, phase):
v = chi.T
sp = np.sin(phase)
cp = np.cos(phase)
res = 1.*v
res[0] = v[0]*cp + v[1]*sp
res[1] = v[1]*cp - v[0]*sp
return res.T | For transforming spins between the coprecessing and coorbital frames |
371,378 | def padRectEqually(rect, padding, bounds, clipExcess = True):
return padRect(rect, padding, padding, padding, padding, bounds, clipExcess) | Applies equal padding to all sides of a rectangle,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). |
371,379 | def _get_rh_methods(rh):
for k, v in vars(rh).items():
if all([
k in HTTP_METHODS,
is_method(v),
hasattr(v, "input_schema")
]):
yield (k, v) | Yield all HTTP methods in ``rh`` that are decorated
with schema.validate |
371,380 | def do__relative_load(self, args: argparse.Namespace) -> None:
file_path = args.file_path
relative_path = os.path.join(self._current_script_dir or , file_path)
self.do_load(relative_path) | Run commands in script file that is encoded as either ASCII or UTF-8 text |
371,381 | def data_check(data,target):
if isinstance(data, pd.DataFrame) or isinstance(data, pd.core.frame.DataFrame):
data_index = data.index
if target is None:
transformed_data = data.ix[:,0].values
data_name = str(data.columns.values[0])
else:
... | Checks data type
Parameters
----------
data : pd.DataFrame or np.array
Field to specify the time series data that will be used.
target : int or str
Target column
Returns
----------
transformed_data : np.array
Raw data array for use in the model
... |
371,382 | def emit(self, record):
self.records.append(Record(levelno=record.levelno, levelname=record.levelname,
message=self.format(record)))
return super(SetupLogChecker, self).emit(record) | Store the message, not only the record. |
371,383 | def extract_common(self, keys):
keys = set(keys)
new = self.__class__()
intersection = self.intersection(keys)
for key in keys:
dict.__setitem__(new, key, _shallowcopy(intersection))
dict.__setitem__(new.offsets, key, self.offsets[key])
return new | Return a new segmentlistdict containing only those
segmentlists associated with the keys in keys, with each
set to their mutual intersection. The offsets are
preserved. |
371,384 | def get_num_nodes(properties=None, hadoop_conf_dir=None, offline=False):
return len(get_task_trackers(properties, hadoop_conf_dir, offline)) | Get the number of task trackers in the Hadoop cluster.
All arguments are passed to :func:`get_task_trackers`. |
371,385 | def make_parser(defaults=None):
if defaults is None:
defaults = DEFAULTS
ctypes = API.list_types()
ctypes_s = ", ".join(ctypes)
type_help = "Select type of %s config files from " + \
ctypes_s + " [Automatically detected by file ext]"
mts = API.MERGE_STRATEGIES
mts_s = ", "... | :param defaults: Default option values |
371,386 | def load_notebook_node(notebook_path):
nb = nbformat.reads(papermill_io.read(notebook_path), as_version=4)
if not hasattr(nb.metadata, ):
nb.metadata[] = {
: dict(),
: dict(),
: __version__,
}
for cell in nb.cells:
if not hasattr(cell.metada... | Returns a notebook object with papermill metadata loaded from the specified path.
Args:
notebook_path (str): Path to the notebook file.
Returns:
nbformat.NotebookNode |
371,387 | def _splitit(self, line, isheader):
line_wrapped = []
for cell, width in zip(line, self._width):
array = []
for c in cell.split():
array.extend(textwrap.wrap(unicode(c, ), width))
line_wrapped.append(array)
max_cell_lines = reduce(max... | Split each element of line to fit the column width
Each element is turned into a list, result of the wrapping of the
string to the desired width |
371,388 | def elbow_method(data, k_min, k_max, distance=):
k_range = range(k_min, k_max)
k_means_var = [Clustering.kmeans(k).fit(data) for k in k_range]
centroids = [X.model.cluster_centers_ for X in k_means_var]
k_euclid = [cdist(data, cent... | Calculates and plots the plot of variance explained - number of clusters
Implementation reference: https://github.com/sarguido/k-means-clustering.rst
:param data: The dataset
:param k_min: lowerbound of the cluster range
:param k_max: upperbound of the cluster range
:param dista... |
371,389 | def index_resolver(index, strict=False):
if strict:
return lambda id_: index[id_]
else:
return index.get | Returns a function that accepts a value and returns index[value]. |
371,390 | def get_departures(self, station):
url = + station
raw_departures = self._request(, url)
return self.parse_departures(raw_departures) | Fetch the current departure times from this station
http://webservices.ns.nl/ns-api-avt?station=${Naam of afkorting Station}
@param station: station to lookup |
371,391 | def create(obj: PersistedObject, obj_type: Type[T], extensions_supported: Iterable[str]):
msg = "{obj} cannot be parsed as a {typ} because no parser supporting that extension ({ext}) is able to " \
"create this type of object." \
"".format(obj=obj, typ=get_pretty_t... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param obj:
:param obj_type:
:param extensions_supported:
:return: |
371,392 | def get_subtask_fields(config_class):
from lsst.pex.config import ConfigurableField, RegistryField
def is_subtask_field(obj):
return isinstance(obj, (ConfigurableField, RegistryField))
return _get_alphabetical_members(config_class, is_subtask_field) | Get all configurable subtask fields from a Config class.
Parameters
----------
config_class : ``lsst.pipe.base.Config``-type
The configuration class (not an instance) corresponding to a Task.
Returns
-------
subtask_fields : `dict`
Mapping where keys are the config attribute na... |
371,393 | def get_configuration_dict(self, secret_attrs=False):
cd = {: self.repo_nexml2json,
: len(self._shards),
: self._filepath_args,
: [],
}
for i in self._shards:
cd[].append(i.get_configuration_dict(secret_attrs=secret_attrs))
... | Type-specific configuration for backward compatibility |
371,394 | def rows(self, offs):
lkey = s_common.int64en(offs)
for lkey, byts in self.slab.scanByRange(lkey, db=self.db):
indx = s_common.int64un(lkey)
yield indx, byts | Iterate over raw indx, bytes tuples from a given offset. |
371,395 | def rank_dated_files(pattern, dir, descending=True):
files = glob.glob(op.join(dir, pattern))
return sorted(files, reverse=descending) | Search a directory for files that match a pattern. Return an ordered list of these files by filename.
Args:
pattern: The glob pattern to search for.
dir: Path to directory where the files will be searched for.
descending: Default True, will sort alphabetically by descending order.
Retu... |
371,396 | def amplify_ground_shaking(T, vs30, gmvs):
gmvs[gmvs > MAX_GMV] = MAX_GMV
interpolator = interpolate.interp1d(
[0, 0.1, 0.2, 0.3, 0.4, 5],
[(760 / vs30)**0.35,
(760 / vs30)**0.35,
(760 / vs30)**0.25,
(760 / vs30)**0.10,
(760 / vs30)**-0.05,
(76... | :param T: period
:param vs30: velocity
:param gmvs: ground motion values for the current site in units of g |
371,397 | def find_equips(
self,
name,
iexact,
environment,
equip_type,
group,
ip,
pagination):
if not isinstance(pagination, Pagination):
raise InvalidParameterError(
u"Invalid parameter:... | Find vlans by all search parameters
:param name: Filter by vlan name column
:param iexact: Filter by name will be exact?
:param environment: Filter by environment ID related
:param equip_type: Filter by equipment_type ID related
:param group: Filter by equipment group ID related... |
371,398 | def main():
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]",
version=xtuml.version.complete_string,
formatter=optparse.TitledHelpFormatter())
parser.add_option("-v", "--verbosity", dest=, actio... | Parse command line options and launch the interpreter |
371,399 | def focal(self):
if self._focal is None:
focal = [(px / 2.0) / np.tan(np.radians(fov / 2.0))
for px, fov in zip(self._resolution, self.fov)]
self._focal = np.asanyarray(focal, dtype=np.float64)
return self._focal | Get the focal length in pixels for the camera.
Returns
------------
focal : (2,) float
Focal length in pixels |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.