Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
353,800 | def swapaxes(self, axis1, axis2, copy=True):
i = self._get_axis_number(axis1)
j = self._get_axis_number(axis2)
if i == j:
if copy:
return self.copy()
return self
mapping = {i: j, j: i}
new_axes = (self._get_axis(mapping.get(k, k... | Interchange axes and swap values axes appropriately.
Returns
-------
y : same as input |
353,801 | def get_station(self, id):
status, data = self.http_client.get_json(
NAMED_STATION_URI % str(id),
params={: self.API_key},
headers={: })
return self.stations_parser.parse_dict(data) | Retrieves a named station registered on the Stations API.
:param id: the ID of the station
:type id: str
:returns: a *pyowm.stationsapi30.station.Station* object |
353,802 | def get_fields(Model,
parent_field="",
model_stack=None,
stack_limit=2,
excludes=[, , ]):
out_fields = []
if model_stack is None:
model_stack = []
if isinstance(Model, basestring):
app_label, model_name = Model.split()
... | Given a Model, return a list of lists of strings with important stuff:
...
['test_user__user__customuser', 'customuser', 'User', 'RelatedObject']
['test_user__unique_id', 'unique_id', 'TestUser', 'CharField']
['test_user__confirmed', 'confirmed', 'TestUser', 'BooleanField']
... |
353,803 | def Kweq_IAPWS_gas(T):
r
gamma0 = 6.141500E-1
gamma1 = 4.825133E4
gamma2 = -6.770793E4
gamma3 = 1.010210E7
K_w_G = 10**(-1*(gamma0 + gamma1/T + gamma2/T**2 + gamma3/T**3))
return K_w_G | r'''Calculates equilibrium constant for OH- and H+ in water vapor,
according to [1]_.
This is the most recent formulation available.
.. math::
-log_{10} K_w^G = \gamma_0 + \gamma_1 T^{-1} + \gamma_2 T^{-2} + \gamma_3 T^{-3}
Parameters
----------
T : float
Temperature of H2O [K... |
353,804 | def timeit(hosts=None,
stmt=None,
warmup=30,
repeat=None,
duration=None,
concurrency=1,
output_fmt=None,
fail_if=None,
sample_mode=):
num_lines = 0
log = Logger(output_fmt)
with Runner(hosts, concurrency, sample_mod... | Run the given statement a number of times and return the runtime stats
Args:
fail-if: An expression that causes cr8 to exit with a failure if it
evaluates to true.
The expression can contain formatting expressions for:
- runtime_stats
- statement
... |
353,805 | def itemgetter_handle(tokens):
internal_assert(len(tokens) == 2, "invalid implicit itemgetter args", tokens)
op, args = tokens
if op == "[":
return "_coconut.operator.itemgetter(" + args + ")"
elif op == "$[":
return "_coconut.functools.partial(_coconut_igetitem, index=" + args + ")... | Process implicit itemgetter partials. |
353,806 | def setup(build=True, installdir="MalmoPlatform"):
gradlew =
if os.name == :
gradlew =
cwd = os.getcwd()
os.chdir(installdir)
os.chdir("Minecraft")
try:
pathlib.Path("src/main/resources/version.properties").write_text("malmomod.version={}\n".format(malmo_version... | Set up Minecraft for use with the MalmoEnv gym environment |
353,807 | def _setup_hypercube(cube, slvr_cfg):
mbu.register_default_dimensions(cube, slvr_cfg)
cube.register_dimension(, 2,
description=)
cube.register_dimension(, 2,
description=)
cube.register_dimension(, 2,
descri... | Sets up the hypercube given a solver configuration |
353,808 | def local_position_ned_cov_encode(self, time_boot_ms, time_utc, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance):
return MAVLink_local_position_ned_cov_message(time_boot_ms, time_utc, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance) | The filtered local position (e.g. fused computer vision and
accelerometers). Coordinate frame is right-handed,
Z-axis down (aeronautical frame, NED / north-east-down
convention)
time_boot_ms : Timestamp (milliseconds since system boot). 0 for... |
353,809 | def grouplabelencode(data, mapping, nacode=None, nastate=False):
if nastate:
if nacode is None:
nacode = len(mapping)
if isinstance(mapping, list):
m = mapping
e = range(len(mapping))
elif isinstance(mapping, dict):
m = list(mapping.values())
... | Encode data array with grouped labels
Parameters:
-----------
data : list
array with labels
mapping : dict, list of list
the index of each element is used as encoding.
Each element is a single label (str) or list
of labels that are mapped to the encoding.
nacode : ... |
353,810 | def prompt_pass(name, default=None):
prompt = name + (default and % default or )
prompt += name.endswith() and or
while True:
rv = getpass.getpass(prompt)
if rv:
return rv
if default is not None:
return default | Grabs hidden (password) input from command line.
:param name: prompt text
:param default: default value if no input provided. |
353,811 | def _create_table(self, table_name):
s table for storing simple dictionaries
_iddblite dblite,CREATE TABLE IF NOT EXISTS %s (%s);Create table error, %s, SQL: %s' % (err, SQL)) | create sqlite's table for storing simple dictionaries |
353,812 | def loadCats(self, ids=[]):
if type(ids) == list:
return [self.cats[id] for id in ids]
elif type(ids) == int:
return [self.cats[ids]] | Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects |
353,813 | def access_entries(self):
entries = self._properties.get("access", [])
return [AccessEntry.from_api_repr(entry) for entry in entries] | List[google.cloud.bigquery.dataset.AccessEntry]: Dataset's access
entries.
``role`` augments the entity type and must be present **unless** the
entity type is ``view``.
Raises:
TypeError: If 'value' is not a sequence
ValueError:
If any item in th... |
353,814 | def fast_lindblad_terms(gamma, unfolding, matrix_form=False, file_name=None,
return_code=False):
r
Ne = unfolding.Ne
Nrho = unfolding.Nrho
Mu = unfolding.Mu
if True:
code = ""
code += "def lindblad_terms("
if not matrix_form: code += "rho, "
... | r"""Return a fast function that returns the Lindblad terms.
We test a basic two-level system.
>>> import numpy as np
>>> Ne = 2
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0.0, -gamma21],
... [gamma21, 0.0]])
>>> rhos = np.array([[0.6, 3+2j],
... ... |
353,815 | def audio_from_youtube(
self,
source_url,
download=True,
output_file_path=None,
download_format=None,
largest_audio=True,
):
def _list_audiostreams(self, source_url):
self.log(u"Getting audiostreams...... | Download an audio stream from a YouTube video,
and save it to file.
If ``download`` is ``False``, return the list
of available audiostreams but do not download.
Otherwise, download the audio stream best matching
the provided parameters, as follows.
If ``download_format`... |
353,816 | def fill_dcnm_subnet_info(self, tenant_id, subnet, start, end, gateway,
sec_gateway, direc):
serv_obj = self.get_service_obj(tenant_id)
fw_dict = serv_obj.get_fw_dict()
fw_id = fw_dict.get()
if direc == :
name = fw_id[0:4] + fw_const.IN_... | Fills the DCNM subnet parameters.
Function that fills the subnet parameters for a tenant required by
DCNM. |
353,817 | def reachable_frontier_from(
self,
start_frontier: Dict[ops.Qid, int],
*,
is_blocker: Callable[[ops.Operation], bool] = lambda op: False
) -> Dict[ops.Qid, int]:
active = set()
end_frontier = {}
queue = BucketPriorityQueue[ops.Operat... | Determines how far can be reached into a circuit under certain rules.
The location L = (qubit, moment_index) is *reachable* if and only if:
a) L is one of the items in `start_frontier`.
OR
b) There is no operation at L and prev(L) = (qubit, moment_index-1)
... |
353,818 | def mask(self):
if self.filter_func is None:
raise RuntimeError("Can't get a mask without a filter function!")
else:
if self._mask is None:
for column in self.columns:
if column in self.filter_func:
... | Create a mask implementing the requested filter on the datasets
Returns
-------
array of Boolean
True for dataset indices to be returned by the get_column method |
353,819 | def pane_position_check(self):
text_buffer = self.get_buffer()
from rafcon.gui.singleton import main_window_controller
if main_window_controller is None or main_window_controller.view is None:
return
from rafcon.gui.runtime_config import global_runtime_con... | Update right bar pane position if needed
Checks calculates if the cursor is still visible and updates the pane position if it is close to not be seen.
In case of an un-docked right-bar this method does nothing.
:return: |
353,820 | def _parse_run_control(block):
_, max_iterations, strain_ratio, _, _ = parse_fixed_width(
2 * [(5, int)] + [(10, float)] + 2 * [(5, int)], block)
return propagation.EquivalentLinearCalculation(
strain_ratio, max_iterations, tolerance=10.) | Parse run control block. |
353,821 | def presenter(self, presenter_name):
if presenter_name in self.__presenters.keys():
return self.__presenters[presenter_name] | :meth:`.WWebPresenterCollectionProto.presenter` method implementation |
353,822 | def qteMoveToEndOfBuffer(self):
tc = self.qteText.textCursor()
tc.movePosition(QtGui.QTextCursor.End)
self.qteText.setTextCursor(tc) | Move cursor to the end of the buffer to facilitate auto
scrolling.
Technically, this is exactly the 'endOfBuffer' macro but to
avoid swamping Qtmacs with 'qteRunMacroStarted' messages to no
avail it was implemented here natively. |
353,823 | def provStacks(self, offs, size):
for _, iden in self.provseq.slice(offs, size):
stack = self.getProvStack(iden)
if stack is None:
continue
yield (iden, stack) | Returns a stream of provenance stacks at the given offset |
353,824 | def iter_change_type(self, change_type):
if change_type not in self.change_type:
raise ValueError("Invalid change type: %s" % change_type)
for diff in self:
if diff.change_type == change_type:
yield diff
elif change_type == "A" and diff.new_f... | :return:
iterator yielding Diff instances that match the given change_type
:param change_type:
Member of DiffIndex.change_type, namely:
* 'A' for added paths
* 'D' for deleted paths
* 'R' for renamed paths
* 'M' for paths with modified da... |
353,825 | def main():
logging.basicConfig(format=LOGGING_FORMAT)
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
add_properties(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.... | CLI entrypoint for scaling policy creation |
353,826 | def router_fabric_virtual_gateway_address_family_ipv6_gateway_mac_address(self, **kwargs):
config = ET.Element("config")
router = ET.SubElement(config, "router", xmlns="urn:brocade.com:mgmt:brocade-common-def")
fabric_virtual_gateway = ET.SubElement(router, "fabric-virtual-gateway", xml... | Auto Generated Code |
353,827 | def detect_spans(self, tokens):
candidates = self._get_candidates(tokens)
results = self._filter_candidates(tokens, candidates)
return results | Return (abbr_span, long_span) pair for each abbreviation definition.
abbr_span and long_span are (int, int) spans defining token ranges. |
353,828 | def docker(gandi, vm, args):
if not [basedir for basedir in os.getenv(, ).split()
if os.path.exists( % basedir)]:
gandi.echo()
return
if vm:
gandi.configure(True, , vm)
else:
vm = gandi.get()
if not vm:
gandi.echo()
return
return ... | Manage docker instance |
353,829 | def check_board(self):
num_mines = np.sum(self.info_map == 12)
num_undiscovered = np.sum(self.info_map == 11)
num_questioned = np.sum(self.info_map == 10)
if num_mines > 0:
return 0
elif np.array_equal(self.info_map == 9, self.mine_map):
return 1... | Check the board status and give feedback. |
353,830 | def load_store(cls, store, decoder=None):
variables, attributes = store.load()
if decoder:
variables, attributes = decoder(variables, attributes)
obj = cls(variables, attrs=attributes)
obj._file_obj = store
return obj | Create a new dataset from the contents of a backends.*DataStore
object |
353,831 | def fork(self):
url = self._build_url(, base_url=self._api)
json = self._json(self._post(url), 201)
return Gist(json, self) if json else None | Fork this gist.
:returns: :class:`Gist <Gist>` if successful, ``None`` otherwise |
353,832 | def on_resolve(target, func, *args, **kwargs):
return _register_hook(ON_RESOLVE, target, func, *args, **kwargs) | Register a resolution hook. |
353,833 | def dict2resource(raw, top=None, options=None, session=None):
if top is None:
top = PropertyHolder(raw)
seqs = tuple, list, set, frozenset
for i, j in iteritems(raw):
if isinstance(j, dict):
if in j:
resource = cls_for_resource(j[])(options, session, j)
... | Convert a dictionary into a Jira Resource object.
Recursively walks a dict structure, transforming the properties into attributes
on a new ``Resource`` object of the appropriate type (if a ``self`` link is present)
or a ``PropertyHolder`` object (if no ``self`` link is present). |
353,834 | def handle_input(self, ncode, wparam, lparam):
x_pos = lparam.contents.x_pos
y_pos = lparam.contents.y_pos
data = lparam.contents.mousedata
self.emulate_mouse(wparam, x_pos, y_pos, data)
... | Process the key input. |
353,835 | def client(self):
if self._client is None:
self._client = self._client_builder()
return self._client | Return client for current application. |
353,836 | def wr_xlsx(self, fout_xlsx, nts):
wr_xlsx(fout_xlsx, nts, prt_flds=self.prt_flds, fld2col_widths=self.fld2col_widths) | Write specified namedtuples into an Excel spreadsheet. |
353,837 | def _add_io_handler(self, handler):
logger.debug(, handler)
self._unprepared_handlers[handler] = None
self._configure_io_handler(handler) | Add an I/O handler to the loop. |
353,838 | def _ParseRecords(self, parser_mediator, evt_file):
for record_index in range(evt_file.number_of_records):
if parser_mediator.abort:
break
try:
evt_record = evt_file.get_record(record_index)
self._ParseRecord(parser_mediator, record_index, evt_record)
... | Parses Windows EventLog (EVT) records.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
evt_file (pyevt.file): Windows EventLog (EVT) file. |
353,839 | def restorecon(path, recursive=False):
*
if recursive:
cmd = [, , path]
else:
cmd = [, , path]
return not __salt__[](cmd, python_shell=False) | Reset the SELinux context on a given path
CLI Example:
.. code-block:: bash
salt '*' file.restorecon /home/user/.ssh/authorized_keys |
353,840 | def p_ArrayLiteralContent(p):
if len(p) < 3:
p[0] = ArrayLiteralContent(None, p[1])
else:
p[0] = ArrayLiteralContent(p[1], p[3]) | ArrayLiteralContent : Expression
ArrayLiteralContent : Expression COLON Expression |
353,841 | def edit_imagefindpars():
teal.teal(imagefindpars.__taskname__, returnAs=None,
autoClose=True, loadOnly=False, canExecute=False) | Allows the user to edit the imagefindpars configObj in a TEAL GUI |
353,842 | def _render_our_module_key_flags(self, module, output_lines, prefix=):
key_flags = self.get_key_flags_for_module(module)
if key_flags:
self._render_module_flags(module, key_flags, output_lines, prefix) | Returns a help string for the key flags of a given module.
Args:
module: module|str, the module to render key flags for.
output_lines: [str], a list of strings. The generated help message
lines will be appended to this list.
prefix: str, a string that is prepended to each generated hel... |
353,843 | def get_modifier_mapping(self):
r = request.GetModifierMapping(display = self.display)
return r.keycodes | Return a list of eight lists, one for each modifier. The list
can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on.
The sublists list the keycodes bound to that modifier. |
353,844 | def spawn_worker(self, entrypoint, args, kwargs,
context_data=None, handle_result=None):
if self._being_killed:
_log.info("Worker spawn prevented due to being killed")
raise ContainerBeingKilled()
service = self.service_cls()
worker_ctx = W... | Spawn a worker thread for running the service method decorated
by `entrypoint`.
``args`` and ``kwargs`` are used as parameters for the service method.
``context_data`` is used to initialize a ``WorkerContext``.
``handle_result`` is an optional function which may be passed
in b... |
353,845 | def close(self):
if self._protocol is not None:
self._protocol.processor.close()
del self._protocol | Closes connection to the server. |
353,846 | def usersettings(request):
if hasattr(request, ):
usersettings = request.usersettings
else:
from .shortcuts import get_current_usersettings
usersettings = get_current_usersettings()
return {
: usersettings
} | Returns the current ``UserSettings`` based on
the SITE_ID in the project's settings as context variables
If there is no 'usersettings' attribute in the request, fetches the
current UserSettings (from usersettings.shortcuts.get_current_usersettings). |
353,847 | def list_pod_preset_for_all_namespaces(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.list_pod_preset_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_pod_preset_for_all_namespaces_with_http_info(**kwargs)
return dat... | list or watch objects of kind PodPreset
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_pod_preset_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool
... |
353,848 | def get_arguments():
import argparse
parser = argparse.ArgumentParser(
description=)
parser.add_argument("--platform_name", , nargs=,
help="The Platform name",
type=str, required=True)
parser.add_argument("--sensor", , nargs=,
... | Get the command line arguments |
353,849 | def add_qualified_edge(
self,
u,
v,
*,
relation: str,
evidence: str,
citation: Union[str, Mapping[str, str]],
annotations: Optional[AnnotationsHint] = None,
subject_modifier: Optional[Mapping] = None,
... | Add a qualified edge.
Qualified edges have a relation, evidence, citation, and optional annotations, subject modifications,
and object modifications.
:param u: The source node
:param v: The target node
:param relation: The type of relation this edge represents
:param ev... |
353,850 | def _set_system_id(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=system_id.system_id, is_container=, presence=False, yang_name="system-id", rest_name="system-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_path... | Setter method for system_id, mapped from YANG variable /protocol/spanning_tree/rpvst/system_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_id is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... |
353,851 | def train_history(self, tid=None):
def result2history(result):
if isinstance(result["history"], list):
return pd.concat([pd.DataFrame(hist["loss"]).assign(fold=i)
for i, hist in enumerate(result["history"])])
else:
... | Get train history as pd.DataFrame |
353,852 | def kick_user(self, user_id, reason=""):
try:
self.client.api.kick_user(self.room_id, user_id)
return True
except MatrixRequestError:
return False | Kick a user from this room.
Args:
user_id (str): The matrix user id of a user.
reason (str): A reason for kicking the user.
Returns:
boolean: Whether user was kicked. |
353,853 | def _convert_pyx_sources_to_lang(self):
if have_pyrex():
return
lang = self.language or
target_ext = if lang.lower() == else
sub = functools.partial(re.sub, , target_ext)
self.sources = list(map(sub, self.sources)) | Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources. |
353,854 | def set_quiet(mres, parent, global_options):
quiet = global_options.get()
if quiet is not None:
mres._quiet = quiet
else:
mres._quiet = parent.quiet | Sets the 'quiet' property on the MultiResult |
353,855 | def parse_JSON(self, JSON_string):
if JSON_string is None:
raise parse_response_error.ParseResponseError()
d = json.loads(JSON_string)
try:
reference_time = d[]
reception_time = timeutils.now()
lon ... | Parses an *UVIndex* instance out of raw JSON data. Only certain
properties of the data are used: if these properties are not found or
cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
:type JSON_string: str
:returns: an *UVIndex* instance or ``None`` if... |
353,856 | def bind(self, flask_app, service, group=None):
if group not in self.services[service]:
raise RuntimeError(
.format(
group, service)
)
for name, api in self.services[service][group].items():
if api.view_fn is N... | Bind the service API urls to a flask app. |
353,857 | def element_as_json(name):
if name:
element = fetch_json_by_name(name)
if element.json:
return element.json | Get specified element json data by name
:param name: name of element
:return: json data representing element, else None |
353,858 | def ntp_authentication_key_encryption_level(self, **kwargs):
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
authentication_key = ET.SubElement(ntp, "authentication-key")
keyid_key = ET.SubElement(authentication_key, "ke... | Auto Generated Code |
353,859 | def _generate_example(self, data_path, image_id):
image_filepath = os.path.join(
data_path, "VOCdevkit/VOC2007/JPEGImages", "{}.jpg".format(image_id))
annon_filepath = os.path.join(
data_path, "VOCdevkit/VOC2007/Annotations", "{}.xml".format(image_id))
def _get_example_objects():
... | Yields examples. |
353,860 | def locate_ami(product, region=None, channel="releases", stream="released", root_store="ssd", virt="hvm"):
if region is None:
region = clients.ec2.meta.region_name
if product.startswith("com.ubuntu.cloud"):
partition = "aws"
if region.startswith("cn-"):
partition = "aws-... | Examples::
locate_ami(product="com.ubuntu.cloud:server:16.04:amd64", channel="daily", stream="daily", region="us-west-2")
locate_ami(product="Amazon Linux AMI 2016.09") |
353,861 | def WriteUserNotification(self, notification, cursor=None):
args = {
"username_hash":
mysql_utils.Hash(notification.username),
"notification_state":
int(notification.state),
"notification":
notification.SerializeToString(),
}
query = "INS... | Writes a notification for a given user. |
353,862 | def reject(self, *, requeue=True):
self.sender.send_BasicReject(self.delivery_tag, requeue) | Reject the message.
:keyword bool requeue: if true, the broker will attempt to requeue the
message and deliver it to an alternate consumer. |
353,863 | def is_syntactic(self):
for term in self._terms:
if isinstance(term, Wildcard) and not term.fixed_size:
return False
if is_operation(term) and issubclass(term, (AssociativeOperation, CommutativeOperation)):
return False
return True | True, iff the flatterm is :term:`syntactic`. |
353,864 | def find_function_by_address(self, address):
cfg_rv = None
for cfg in self._cfgs:
if cfg.start_address == address:
cfg_rv = cfg
break
return cfg_rv | Return the cfg of the requested function by address. |
353,865 | def inurl(needles, haystack, position=):
count = 0
haystack2 = haystack.lower()
for needle in needles:
needle2 = needle.lower()
if position == :
if haystack2.find(needle2) > -1:
count += 1
elif position == :
if haystack2.endswith(n... | convenience function to make string.find return bool |
353,866 | def getToolchainFiles(self):
return reversed([
os.path.join(x.path, x.description[]) for x in self.hierarchy if in x.description
]) | return a list of toolchain file paths in override order (starting
at the bottom/leaf of the hierarchy and ending at the base).
The list is returned in the order they should be included
(most-derived last). |
353,867 | def validation_email_handler(notification):
base_subject = _().format(domain=notification.site.domain)
subject = getattr(settings, , base_subject)
notification.email_subject = subject
email_handler(notification, validation_email_context) | Validation email handler. |
353,868 | def parameter(self, name=None, value=None, **kwargs):
return self.nest(Parameter(name=name, value=value, **kwargs)) | Create a <Parameter> element
:param name: The name of the custom parameter
:param value: The value of the custom parameter
:param kwargs: additional attributes
:returns: <Parameter> element |
353,869 | def as_dict(df, ix=):
if isinstance(df.index, pd.DatetimeIndex):
df[] = df.index
return df.to_dict(orient=)[ix] | converts df to dict and adds a datetime field if df is datetime |
353,870 | def download_coding_sequences(patric_id, seqtype, outdir=, outfile=, force_rerun=False):
if seqtype == :
extension =
elif seqtype == :
extension =
else:
raise ValueError()
if outfile:
outfile = op.join(outdir, .format(outfile, extension))
else:
... | Download the entire set of DNA or protein sequences from protein-encoding genes in a genome from NCBI.
Saves a FASTA file in the optional directory specified.
Args:
genome_accession_or_id (str): PATRIC ID
seqtype (str): "dna" or "protein" - if you want the coding sequences in DNA or amino acid... |
353,871 | def create_order(self, **params):
for required in [, , ]:
if required not in params:
raise ValueError("Missing required parameter: %s" % required)
response = self._post(, , data=params)
return self._make_api_object(response, Order) | https://developers.coinbase.com/api/v2#create-an-order |
353,872 | def plotlyFrequencyHistogram(counts):
data = [
go.Histogram(
x=tuple(count for _, _, count in counts.getNonZerosSorted())
)
]
py.plot(data, filename=os.environ.get("HEATMAP_NAME",
str(datetime.datetime.now()))) | x-axis is a count of how many times a bit was active
y-axis is number of bits that have that frequency |
353,873 | def add_grid_data(self, data):
self.grid_data.append(data)
return len(self.grid_data) - 1 | Return id |
353,874 | def addLabel(self, start, end, labelName):
if len(self._recordsCache) == 0:
raise HTMPredictionModelInvalidRangeError("Invalid supplied range for . "
"Model has no saved records.")
try:
start = int(start)
except Exception:
start = 0
try:
end = int(end)
except E... | Add the label labelName to each record with record ROWID in range from
``start`` to ``end``, noninclusive of end.
This will recalculate all points from end to the last record stored in the
internal cache of this classifier.
:param start: (int) start index
:param end: (int) end index (noninclusive... |
353,875 | def make_html_words( self, words ):
line = ""
if words:
line = html_quote( words[0] )
for w in words[1:]:
line = line + " " + html_quote( w )
return line | convert a series of simple words into some HTML text |
353,876 | def read_from_memory_region(self, *, region_name: str):
warnings.warn("pyquil.api._qam.QAM.read_from_memory_region is deprecated, please use "
"pyquil.api._qam.QAM.read_memory instead.",
DeprecationWarning)
assert self.status ==
if region_nam... | Reads from a memory region named region_name on the QAM.
This is a shim over the eventual API and only can return memory from a region named
"ro" of type ``BIT``.
:param region_name: The string naming the declared memory region.
:return: A list of values of the appropriate type. |
353,877 | def predict(self, X):
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
for s in self.hmc_samples:
if self.model._fixes_ is None:
self.model[:] = s
else:
self.model[self.model._fix... | Predictions with the model for all the MCMC samples. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given. |
353,878 | def default_display(value, with_module=True):
object_type = type(value)
try:
name = object_type.__name__
module = object_type.__module__
if with_module:
return name + + module +
else:
return name
except:
type_str = to_text_string(object_... | Default display for unknown objects. |
353,879 | def _get_api_key(self):
conn = self.get_connection(self.http_conn_id)
api_key = conn.password
if not api_key:
raise AirflowException(
)
return api_key | Get Opsgenie api_key for creating alert |
353,880 | def example_camera():
logging.info()
img = imread(PATH_IMG_CAMERA)/255.0
callback = visual_callback_2d(img)
ms.morphological_chan_vese(img, 35,
smoothing=3, lambda1=1, lambda2=1,
iter_callback=callback) | Example with `morphological_chan_vese` with using the default
initialization of the level-set. |
353,881 | def get(key, default=-1):
if isinstance(key, int):
return ProtectionAuthority(key)
if key not in ProtectionAuthority._member_map_:
extend_enum(ProtectionAuthority, key, default)
return ProtectionAuthority[key] | Backport support for original codes. |
353,882 | def create_for_noise(other_param, threshold=(-10, 10), activated=True):
return Sigmoid(other_param, threshold, activated, mul=20, add=-10) | Creates a Sigmoid that is adjusted to be used with noise parameters,
i.e. with parameters which's output values are in the range [0.0, 1.0].
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
See :func:`imgaug.parameters.Sigmoid.__init__`.
thr... |
353,883 | def GetLoggingLocation():
frame = inspect.currentframe()
this_file = frame.f_code.co_filename
frame = frame.f_back
while frame:
if this_file == frame.f_code.co_filename:
if in frame.f_locals:
ret = frame.f_locals[]
if len(ret) != 3:
return (None, None, None)
retur... | Search for and return the file and line number from the log collector.
Returns:
(pathname, lineno, func_name) The full path, line number, and function name
for the logpoint location. |
353,884 | def instagram_user_recent_media(parser, token):
try:
tagname, username = token.split_contents()
return InstagramUserRecentMediaNode(username)
except ValueError:
raise template.TemplateSyntaxError(
"%r tag requires a single argument" % token.contents.split()[0]
) | Tag for getting data about recent media of an user.
:param parser:
:param token:
:return: |
353,885 | def emptyTrash(self):
key = % self.key
self._server.query(key, method=self._server._session.put) | If a section has items in the Trash, use this option to empty the Trash. |
353,886 | def aggregate(self, pipeline, session=None, **kwargs):
with self.__database.client._tmp_session(session, close=False) as s:
return self._aggregate(pipeline,
CommandCursor,
kwargs.get(),
... | Perform an aggregation using the aggregation framework on this
collection.
All optional `aggregate command`_ parameters should be passed as
keyword arguments to this method. Valid options include, but are not
limited to:
- `allowDiskUse` (bool): Enables writing to temporary f... |
353,887 | def _solidAngleCMD(self):
self.solid_angle_cmd = np.zeros([len(self.roi.centers_mag),
len(self.roi.centers_color)])
for index_mag in np.arange(len(self.roi.centers_mag)):
for index_color in np.arange(len(self.roi.centers_color)):
... | Compute solid angle within the mask annulus (deg^2) as a
function of color and magnitude. |
353,888 | def move_item_up(self, item):
prev_iter = self._prev_iter_for(item)
if prev_iter is not None:
self.model.swap(prev_iter, self._iter_for(item)) | Move an item up in the list.
Essentially swap it with the item above it.
:param item: The item to be moved. |
353,889 | def unsubscribe_all(self):
topics = list(self.topics.keys())
for topic in topics:
self.unsubscribe(topic) | Unsubscribe from all topics. |
353,890 | def get_random_hex(length):
if length <= 0:
return
return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length] | Return random hex string of a given length |
353,891 | def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
if self.username == "root":
exit_config_mode = False
return super(LinuxSSH, self).send_config_set(
config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
) | Can't exit from root (if root) |
353,892 | def complete_contexts(self):
if self._complete_contexts:
return self._complete_contexts
self.context()
return self._complete_contexts | Return a list of interfaces that have satisfied contexts. |
353,893 | def check_options(options, parser):
if not options.get(, None):
print("release environment is required")
parser.print_help()
return os.EX_USAGE
return 0 | check options requirements, print and return exit value |
353,894 | def get_semantic_data(self, path_as_list):
target_dict = self.semantic_data
for path_element in path_as_list:
if path_element in target_dict:
target_dict = target_dict[path_element]
else:
raise KeyError("The state with name {1} and id {2} ... | Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return: |
353,895 | def _object_with_attr(self, name):
for obj in self._objects:
if hasattr(obj, name):
return obj
raise AttributeError("No object has attribute {!r}".format(name)) | Returns the first object that has the attribute `name`
:param name: the attribute to filter by
:type name: `str`
:raises AttributeError: when no object has the named attribute |
353,896 | def update_or_create(cls, name, engine, translation_values=None, with_status=False):
updated, created = False, False
alias = cls.get(name, raise_exc=False)
if not alias:
alias = cls.create(name)
created = True
elements = element_resolver(translat... | Update or create an Alias and it's mappings.
:param str name: name of alias
:param Engine engine: engine to modify alias translation values
:param list(str,Element) translation_values: translation values
as elements. Can be None if you want to unset any existing values
... |
353,897 | def _insert(self, feature, cursor):
try:
cursor.execute(constants._INSERT, feature.astuple())
except sqlite3.ProgrammingError:
cursor.execute(
constants._INSERT, feature.astuple(self.default_encoding)) | Insert a feature into the database. |
353,898 | def unnest(self, data, fit=False):
with timer( % self.name, logging.DEBUG):
raw = self.series(data)
lengths = [0 if x is None or (isinstance(x, float) and numpy.isnan(x)) else len(x) for x in raw.values]
if fit and self.sequence_length is None:
... | :param data: a dataframe containing a column to be unnested
:param fit: if True, self.sequence_length will exactly accomodate the largest sequence length
:return: 1D array of values with length = rows * sequence_length |
353,899 | def _notebook(trigger, note_store):
note = Types.Note()
if trigger.notebook:
notebook_id = EvernoteMgr.get_notebook(note_store, trigger.notebook)
note.notebookGuid = EvernoteMgr.set_notebook(note_store, trigger.notebook, notebook_id)
... | :param trigger: trigger object
:param note_store: note_store object
:return: note object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.