Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
18,400 | def start(self):
log.debug()
if in self.address:
self.skt = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if self.reuse_port:
self.skt.setsockopt(socket.SOL_SOCKET, socke... | Start listening for messages. |
18,401 | def cursor_batch(self,
table_name,
start_timeperiod,
end_timeperiod):
raise NotImplementedError(.format(self.__class__.__name__)) | method returns batched DB cursor |
18,402 | def login(self, email=None, password=None):
if email is None:
if self._parent_class.email:
email = self._parent_class.email
else:
email = compat_input("login: ")
if password is None:
if self... | Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
- **email**: Email to log in for, will prompt if not entere... |
18,403 | def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
while True:
chunk = file.read(size)
if not chunk:
break
yield chunk | Yield pieces of data from a file-like object until EOF. |
18,404 | def get_discrete_grid(self):
sets_grid = []
for d in self.space:
if d.type == :
sets_grid.extend([d.domain]*d.dimensionality)
return np.array(list(itertools.product(*sets_grid))) | Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete
variables |
18,405 | def setbit(self, name, offset, val):
val = int(get_boolean(, val))
offset = get_positive_integer(, offset)
return self.execute_command(, name, offset, val) | Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
Like **Redis.SETBIT**
:param string name: the key name
:param int offset: the bit position
:param bool val: the bit value
:return: the previous b... |
18,406 | def add_class(self, node):
self.linker.visit(node)
self.classdiagram.add_object(self.get_title(node), node) | visit one class and add it to diagram |
18,407 | def parse(
idp_metadata,
required_sso_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
required_slo_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT,
entity_id=None):
data = {}
dom = fromstring(idp_metadata, forbid_dtd=True)
... | Parse the Identity Provider metadata and return a dict with extracted data.
If there are multiple <IDPSSODescriptor> tags, parse only the first.
Parse only those SSO endpoints with the same binding as given by
the `required_sso_binding` parameter.
Parse only those SLO endpoints with t... |
18,408 | def create(self, request):
self._site_login(request.repo)
self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number)
self._edit_main(request)
return self._create_new(request) | Creates a new wiki page for the specified PullRequest instance. The page
gets initialized with basic information about the pull request, the tests
that will be run, etc. Returns the URL on the wiki.
:arg request: the PullRequest instance with testing information. |
18,409 | def split_comp_info(self, catalog_name, split_ver, split_key):
return self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)][split_key] | Return the info for a particular split key |
18,410 | def _identity_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:
if not sctx.schema_data.if_features(stmt, sctx.text_mid):
return
id = (stmt.argument, sctx.schema_data.namespace(sctx.text_mid))
adj = sctx.schema_data.identity_adjs.setdefault(id, IdentityAdjacency())
... | Handle identity statement. |
18,411 | def build_tqdm_outer(self, desc, total):
return self.tqdm(desc=desc, total=total, leave=self.leave_outer, initial=self.initial) | Extension point. Override to provide custom options to outer progress bars (Epoch loop)
:param desc: Description
:param total: Number of epochs
:return: new progress bar |
18,412 | def render_view(parser, token):
bits = token.split_contents()
n = len(bits)
if n < 2:
raise TemplateSyntaxError(" takes at least one view as argument")
viewname = bits[1]
kwargs = {}
if n > 2:
for bit in bits[2:]:
match = kwarg_re.match(bit)
if not... | Return an string version of a View with as_string method.
First argument is the name of the view. Any other arguments
should be keyword arguments and will be passed to the view.
Example:
{% render_view viewname var1=xx var2=yy %} |
18,413 | def _set_attribute(self, name, value):
setattr(self, name, value)
self.namespace.update({name: getattr(self, name)}) | Make sure namespace gets updated when setting attributes. |
18,414 | def _cont_norm(fluxes, ivars, cont):
nstars = fluxes.shape[0]
npixels = fluxes.shape[1]
norm_fluxes = np.ones(fluxes.shape)
norm_ivars = np.zeros(ivars.shape)
bad = cont == 0.
norm_fluxes = np.ones(fluxes.shape)
norm_fluxes[~bad] = fluxes[~bad] / cont[~bad]
norm_ivars = cont**2 * iv... | Continuum-normalize a continuous segment of spectra.
Parameters
----------
fluxes: numpy ndarray
pixel intensities
ivars: numpy ndarray
inverse variances, parallel to fluxes
contmask: boolean mask
True indicates that pixel is continuum
Returns
-------
norm_flu... |
18,415 | def upload_plugin(self, plugin_path):
files = {
: open(plugin_path, )
}
headers = {
:
}
upm_token = self.request(method=, path=, headers=headers, trailing=True).headers[
]
url = .format(upm_token=upm_token)
return self... | Provide plugin path for upload into Jira e.g. useful for auto deploy
:param plugin_path:
:return: |
18,416 | def infer(self, sensationList, reset=True, objectName=None):
self._unsetLearningMode()
statistics = collections.defaultdict(list)
for sensations in sensationList:
for col in xrange(self.numColumns):
location, feature = sensations[col]
self.sensorInputs[col].addDataToQueue... | Infer on given sensations.
The provided sensationList is a list of sensations, and each sensation is
a mapping from cortical column to a tuple of two SDR's respectively
corresponding to the location in object space and the feature.
For example, the input can look as follows, if we are inferring a simp... |
18,417 | def is_authorization_expired(self):
if not self.auth.token_expiration:
return True
return (datetime.datetime.utcnow() > self.auth.token_expiration) | Checks if the authorization token (access_token) has expired.
:return: If expired.
:rtype: ``bool`` |
18,418 | def purgeCache(self, *args, **kwargs):
return self._makeApiCall(self.funcinfo["purgeCache"], *args, **kwargs) | Purge Worker Cache
Publish a purge-cache message to purge caches named `cacheName` with
`provisionerId` and `workerType` in the routing-key. Workers should
be listening for this message and purge caches when they see it.
This method takes input: ``v1/purge-cache-request.json#``
... |
18,419 | def safe_main():
try:
main()
except KeyboardInterrupt:
logger.info("Cancelled by user")
sys.exit(0)
except ProgramError as e:
logger.error(e.message)
parser.error(e.message) | A safe version of the main function (that catches ProgramError). |
18,420 | async def stdout_writer():
if sys.stdout.seekable():
return sys.stdout.buffer.raw
if os.isatty(sys.stdin.fileno()):
fd_to_use = 0
else:
fd_to_use = 1
twrite, pwrite = await loop.connect_write_pipe(
asyncio.streams.FlowControlMixin,
os.fdop... | This is a bit complex, as stdout can be a pipe or a file.
If it is a file, we cannot use
:meth:`asycnio.BaseEventLoop.connect_write_pipe`. |
18,421 | def generate_shared_access_signature(self, services, resource_types,
permission, expiry, start=None,
ip=None, protocol=None):
_validate_not_none(, self.account_name)
_validate_not_none(, self.account_key)
... | Generates a shared access signature for the account.
Use the returned signature with the sas_token parameter of the service
or to create a new account object.
:param Services services:
Specifies the services accessible with the account SAS. You can
combine values to pr... |
18,422 | def _handle_backend_error(self, exception, idp):
loaded_state = self.load_state(exception.state)
relay_state = loaded_state["relay_state"]
resp_args = loaded_state["resp_args"]
error_resp = idp.create_error_response(resp_args["in_response_to"],
... | See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAAuthenticationError
:type idp: saml.server.Server
:rtype: satosa.response.Response
:param exception: The SATOSAAuthenticationError
:param idp: The saml frontend idp server
:retu... |
18,423 | def prehook(self, **kwargs):
cmd = [, ]
logger.info("Starting smpd: "+" ".join(cmd))
rc = subprocess.call(cmd)
return rc | Launch local smpd. |
18,424 | def _preprocess(self, valid_features=["pcp", "tonnetz", "mfcc",
"cqt", "tempogram"]):
if self.feature_str not in valid_features:
raise RuntimeError("Feature %s in not valid for algorithm: %s "
"(valid features... | This method obtains the actual features. |
18,425 | def load_file_contents(cls, file_contents, seed_values=None):
@contextmanager
def opener(file_content):
with io.BytesIO(file_content.content) as fh:
yield fh
return cls._meta_load(opener, file_contents, seed_values) | Loads config from the given string payloads.
A handful of seed values will be set to act as if specified in the loaded config file's DEFAULT
section, and be available for use in substitutions. The caller may override some of these
seed values.
:param list[FileContents] file_contents: Load from these ... |
18,426 | def init_map(self):
d = self.declaration
if d.show_location:
self.set_show_location(d.show_location)
if d.show_traffic:
self.set_show_traffic(d.show_traffic)
if d.show_indoors:
self.set_show_indoors(d.show_indoors)
if d.show_buildings:... | Add markers, polys, callouts, etc.. |
18,427 | def _open_ds_from_store(fname, store_mod=None, store_cls=None, **kwargs):
if isinstance(fname, xr.Dataset):
return fname
if not isstring(fname):
try:
fname[0]
except TypeError:
pass
else:
if store_mod is not None and store_cls is not Non... | Open a dataset and return it |
18,428 | def convert_user_type(cls, name, value):
names = value._fields
values = [cls.convert_value(name, getattr(value, name)) for name in names]
return cls.generate_data_dict(names, values) | Converts a user type to RECORD that contains n fields, where n is the
number of attributes. Each element in the user type class will be converted to its
corresponding data type in BQ. |
18,429 | def merge_offsets_metadata(topics, *offsets_responses):
result = dict()
for topic in topics:
partition_offsets = [
response[topic]
for response in offsets_responses
if topic in response
]
result[topic] = merge_partition_offsets(*partition_offsets)... | Merge the offset metadata dictionaries from multiple responses.
:param topics: list of topics
:param offsets_responses: list of dict topic: partition: offset
:returns: dict topic: partition: offset |
18,430 | def _buildTemplates(self):
contents = self._renderTemplate("html-multi/index.html", extraContext={"theme": self.theme, "index_page_flag" : True})
FILE_NAME = "index.html"
main_url = self._save2File(contents, FILE_NAME, self.output_path)
contents = self._render... | OVERRIDING THIS METHOD from Factory |
18,431 | def create_surface_grid(nr_electrodes=None, spacing=None,
electrodes_x=None,
depth=None,
left=None,
right=None,
char_lengths=None,
lines=None,
... | This is a simple wrapper for cr_trig_create to create simple surface
grids.
Automatically generated electrode positions are rounded to the third
digit.
Parameters
----------
nr_electrodes: int, optional
the number of surface electrodes
spacing: float... |
18,432 | def _handle_http_error(self, url, response_obj, status_code, psp_ref,
raw_request, raw_response, headers, message):
if status_code == 404:
if url == self.merchant_specific_url:
erstr = "Received a 404 for url:. Please ensure that" \
... | This function handles the non 200 responses from Adyen, raising an
error that should provide more information.
Args:
url (str): url of the request
response_obj (dict): Dict containing the parsed JSON response from
Adyen
status_code (int): HTTP status ... |
18,433 | def intersect_leaderboards(self, destination, keys, aggregate=):
keys.insert(0, self.leaderboard_name)
self.redis_connection.zinterstore(destination, keys, aggregate) | Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the current leaderboard.
@param options [Hash] Options for intersecting the leaderboards. |
18,434 | def _arg(self, line):
t have support for ARG, so instead will issue
a warning to the console for the user to export the variable
with SINGULARITY prefixed at build.
Parameters
==========
line: the line from the recipe file to parse for ARG
ARG... | singularity doesn't have support for ARG, so instead will issue
a warning to the console for the user to export the variable
with SINGULARITY prefixed at build.
Parameters
==========
line: the line from the recipe file to parse for ARG |
18,435 | def file_list(*packages, **kwargs):
s package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt lowpkg.file_list httpd
salt lowpkg.file_list httpd postfix
salt lowpkg.file_list
dpkg -l {0} cmd.run_allretcodeError: stderrstdoutii versiondescr... | List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt '*' lowpkg.file_list httpd postfix
salt... |
18,436 | def insertRnaQuantificationSet(self, rnaQuantificationSet):
try:
models.Rnaquantificationset.create(
id=rnaQuantificationSet.getId(),
datasetid=rnaQuantificationSet.getParentContainer().getId(),
referencesetid=rnaQuantificationSet.getReference... | Inserts a the specified rnaQuantificationSet into this repository. |
18,437 | async def main() -> None:
logging.basicConfig(level=logging.INFO)
async with ClientSession() as websession:
try:
client = Client(websession)
await client.profile.login(, )
_LOGGER.info(, client.profile.account_id)
summary = await client.profile.sum... | Create the aiohttp session and run the example. |
18,438 | def embedding_density(
adata: AnnData,
basis: str,
*,
groupby: Optional[str] = None,
key_added: Optional[str] = None,
components: Union[str, Sequence[str]] = None
):
sanitize_anndata(adata)
logg.info({}\.format(basis), r=True)
basis = basis.lower()
if basis == :... | Calculate the density of cells in an embedding (per condition)
Gaussian kernel density estimation is used to calculate the density of
cells in an embedded space. This can be performed per category over a
categorical cell annotation. The cell density can be plotted using the
`sc.pl.embedding_density()`... |
18,439 | def build_docs(location="doc-source", target=None, library="icetea_lib"):
cmd_ar = ["sphinx-apidoc", "-o", location, library]
try:
print("Generating api docs.")
retcode = check_call(cmd_ar)
except CalledProcessError as error:
print("Documentation build failed. Return code: {}".f... | Build documentation for Icetea. Start by autogenerating module documentation
and finish by building html.
:param location: Documentation source
:param target: Documentation target path
:param library: Library location for autodoc.
:return: -1 if something fails. 0 if successfull. |
18,440 | def _gerritCmd(self, *args):
if self.gerrit_identity_file is not None:
options = [, self.gerrit_identity_file]
else:
options = []
return [] + options + [
.join((self.gerrit_username, self.gerrit_server)),
, str(self.gerrit_port),
... | Construct a command as a list of strings suitable for
:func:`subprocess.call`. |
18,441 | def analyze_bash_vars(job_input_file, job_homedir):
{"$dnanexus_link": "file-xxxx"}{"$dnanexus_link": "file-yyyy"}
_, file_entries, rest_hash = get_job_input_filenames(job_input_file)
patterns_dict = get_input_spec_patterns()
def get_prefix(basename, key):
best_prefix = None
patter... | This function examines the input file, and calculates variables to
instantiate in the shell environment. It is called right before starting the
execution of an app in a worker.
For each input key, we want to have
$var
$var_filename
$var_prefix
remove last dot (+gz), and/or remove pattern... |
18,442 | def _http_put(self, url, data, **kwargs):
kwargs.update({: json.dumps(data)})
return self._http_request(, url, kwargs) | Performs the HTTP PUT request. |
18,443 | def set_imap(self, imap, callback=True):
self.imap = imap
self.calc_imap()
with self.suppress_changed:
self.recalc()
self.t_.set(intensity_map=imap.name, callback=False) | Set the intensity map used by this RGBMapper.
`imap` specifies an IntensityMap object. If `callback` is True, then
any callbacks associated with this change will be invoked. |
18,444 | def subset(self, service=None):
if service is None:
for serviceName in self.ncssServiceNames:
if serviceName in self.access_urls:
service = serviceName
break
else:
raise RuntimeError()
elif service n... | Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'NetcdfSubset'
or 'NetcdfServer', in that order, depending on t... |
18,445 | def get_config_parameter_boolean(config: ConfigParser,
section: str,
param: str,
default: bool) -> bool:
try:
value = config.getboolean(section, param)
except (TypeError, ValueError, NoOptionError):
... | Get Boolean parameter from ``configparser`` ``.INI`` file.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
parameter value, or default |
18,446 | def search(self, query, nid=None):
r = self.request(
method="network.search",
nid=nid,
data=dict(query=query)
)
return self._handle_error(r, "Search with query failed."
.format(query)) | Search for posts with ``query``
:type nid: str
:param nid: This is the ID of the network to get the feed
from. This is optional and only to override the existing
`network_id` entered when created the class
:type query: str
:param query: The search query; should ... |
18,447 | def get_secret(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[Secret]:
partial_unlock_proof = end_state.secrethashes_to_unlockedlocks.get(secrethash)
if partial_unlock_proof is None:
partial_unlock_proof = end_state.secrethashes_to_onchain_unlockedlocks.g... | Returns `secret` if the `secrethash` is for a lock with a known secret. |
18,448 | def setRequest(self, endPointReference, action):
self._action = action
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
addressTo = self._addressTo
messageID = self._messageID = "uuid:%s" %time.time()
typecode = GE... | Call For Request |
18,449 | def get_logger(name):
log = logging.getLogger(name)
if not log.handlers:
log.addHandler(NullHandler())
return log | Return logger with null handle |
18,450 | def date_struct_nn(year, month, day, tz="UTC"):
if not day:
day = 1
if not month:
month = 1
return date_struct(year, month, day, tz) | Assemble a date object but if day or month is none set them to 1
to make it easier to deal with partial dates |
18,451 | def command(execute=None):
if connexion.request.is_json:
execute = Execute.from_dict(connexion.request.get_json())
return | Execute a Command
Execute a command # noqa: E501
:param execute: The data needed to execute this command
:type execute: dict | bytes
:rtype: Response |
18,452 | def _init_valid_functions(action_dimensions):
sizes = {
"screen": tuple(int(i) for i in action_dimensions.screen),
"screen2": tuple(int(i) for i in action_dimensions.screen),
"minimap": tuple(int(i) for i in action_dimensions.minimap),
}
types = actions.Arguments(*[
actions.ArgumentTyp... | Initialize ValidFunctions and set up the callbacks. |
18,453 | def _get_offset(text, visible_width, unicode_aware=True):
result = 0
width = 0
if unicode_aware:
for c in text:
if visible_width - width <= 0:
break
result += 1
width += wcwidth(c)
if visible_width - width < 0:
result -= 1
... | Find the character offset within some text for a given visible offset (taking into account the
fact that some character glyphs are double width).
:param text: The text to analyze
:param visible_width: The required location within that text (as seen on screen).
:return: The offset within text (as a char... |
18,454 | def get_file_type(filename):
txt_extensions = [".txt", ".dat", ".csv"]
hdf_extensions = [".hdf", ".h5", ".bkup", ".checkpoint"]
for ext in hdf_extensions:
if filename.endswith(ext):
with _h5py.File(filename, ) as fp:
filetype = fp.attrs[]
return filetypes... | Returns I/O object to use for file.
Parameters
----------
filename : str
Name of file.
Returns
-------
file_type : {InferenceFile, InferenceTXTFile}
The type of inference file object to use. |
18,455 | def _format_explain(self):
lines = []
for (command, kwargs) in self._call_list:
lines.append(command + " " + pformat(kwargs))
return "\n".join(lines) | Format the results of an EXPLAIN |
18,456 | def convert_graph(self, graph_file, input_format, output_formats,
email=None, use_threads=False, callback=None):
if email is None:
email = self.email
if input_format not in GraphFormats._any:
raise ValueError("Invalid input format {}.".format(input... | Convert a graph from one GraphFormat to another.
Arguments:
graph_file (str): Filename of the file to convert
input_format (str): A grute.GraphFormats
output_formats (str[]): A grute.GraphFormats
email (str: self.email)*: The email to notify
use_threa... |
18,457 | async def _request(self, *, http_verb, api_url, req_args):
if self.session and not self.session.closed:
async with self.session.request(http_verb, api_url, **req_args) as res:
self._logger.debug("Ran the request with existing session.")
return {
... | Submit the HTTP request with the running session or a new session.
Returns:
A dictionary of the response data. |
18,458 | def new(expr, *args, **kwargs):
current_args, current_var_args, current_kwargs = get_vars(expr)
new_kwargs = current_kwargs.copy()
recursive_arguments = {}
for key in tuple(kwargs):
if "__" in key:
value = kwargs.pop(key)
key, _, subkey = key.partition("__")
... | Template an object.
::
>>> class MyObject:
... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs):
... self.arg1 = arg1
... self.arg2 = arg2
... self.var_args = var_args
... self.foo = foo
... ... |
18,459 | def import_log_funcs():
global g_logger
curr_mod = sys.modules[__name__]
for func_name in _logging_funcs:
func = getattr(g_logger, func_name)
setattr(curr_mod, func_name, func) | Import the common log functions from the global logger to the module. |
18,460 | def add_dimension(self, dimension, dim_pos, dim_val, vdim=False, **kwargs):
dimension = asdim(dimension)
if dimension in self.dimensions():
raise Exception(.format(dim=dimension.name))
if vdim and self._deep_indexable:
raise Exception()
if vdim:
... | Adds a dimension and its values to the object
Requires the dimension name or object, the desired position in
the key dimensions and a key value scalar or sequence of the
same length as the existing keys.
Args:
dimension: Dimension or dimension spec to add
dim_po... |
18,461 | def _aggregation_op(cls,
op: Callable[[tf.Tensor, Optional[Sequence[int]]], tf.Tensor],
x: ,
vars_list: List[str]) -> :
s output.
'
axis = cls._varslist2axis(x, vars_list)
t = op(x.tensor, axis)
scope = []
for var in x.scope.as_list():... | Returns a TensorFluent for the aggregation `op` applied to fluent `x`.
Args:
op: The aggregation operation.
x: The input fluent.
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the aggregation operator's output. |
18,462 | def error_value_processor(value, error):
if isinstance(error, (str, unicode)):
try:
if "%" in error:
error_float = float(error.replace("%", ""))
error_abs = (value/100) * error_float
return error_abs
elif error == "":
... | If an error is a percentage, we convert to a float, then
calculate the percentage of the supplied value.
:param value: base value, e.g. 10
:param error: e.g. 20.0%
:return: the absolute error, e.g. 12 for the above case. |
18,463 | def build(self, lv2_uri):
try:
plugin = self._plugins[lv2_uri]
except KeyError:
raise Lv2EffectBuilderError(
"Lv2EffectBuilder not contains metadata information about the plugin . \n"
"Try re-scan the installed plugins using the reload met... | Returns a new :class:`.Lv2Effect` by the valid lv2_uri
:param string lv2_uri:
:return Lv2Effect: Effect created |
18,464 | def __response_message_descriptor(self, message_type, method_id):
descriptor = {: {: }}
if message_type != message_types.VoidMessage():
self.__parser.add_message(message_type.__class__)
self.__response_schema[method_id] = self.__parser.ref_for_message_type(
message_type.__class... | Describes the response.
Args:
message_type: messages.Message class, The message to describe.
method_id: string, Unique method identifier (e.g. 'myapi.items.method')
Returns:
Dictionary describing the response. |
18,465 | def _info_long(self) -> Optional[str]:
try:
return str(
html.unescape(self.journey.InfoTextList.InfoText.get("textL")).replace(
"<br />", "\n"
)
)
except AttributeError:
return None | Extract journey information. |
18,466 | def Case(self, caseVal, *statements):
"c-like case of switch statement"
assert self.parentStm is None
caseVal = toHVal(caseVal, self.switchOn._dtype)
assert isinstance(caseVal, Value), caseVal
assert caseVal._isFullVld(), "Cmp with invalid value"
assert caseVal not in se... | c-like case of switch statement |
18,467 | def remove_node(self, node, stop=False):
if node.kind not in self.nodes:
raise NodeNotFound("Unable to remove node %s: invalid node type `%s`.",
node.name, node.kind)
else:
try:
index = self.nodes[node.kind].index(node)
... | Removes a node from the cluster.
By default, it doesn't also stop the node, just remove from
the known hosts of this cluster.
:param node: node to remove
:type node: :py:class:`Node`
:param stop: Stop the node
:type stop: bool |
18,468 | def roll(self, speed, heading, state=1):
return self.write(request.Roll(self.seq, speed, heading, state )) | speed can have value between 0x00 and 0xFF
heading can have value between 0 and 359 |
18,469 | def blockSelectionSignals( self, state ):
if ( self._selectionSignalsBlocked == state ):
return
self._selectionSignalsBlocked = state
if ( not state ):
self.emitSelectionFinished() | Sets the state for the seleciton finished signal. When it \
is set to True, it will emit the signal. This is used \
internally to control selection signal propogation, so \
should not really be called unless you know why you are \
calling it.
:param s... |
18,470 | def _parseSCDOCDC(self, src):
while 1:
src = src.lstrip()
if src.startswith():
src = src[4:]
elif src.startswith():
src = src[3:]
else:
break
return src | [S|CDO|CDC]* |
18,471 | def storage(self, *, resource=None):
if not isinstance(self.protocol, MSGraphProtocol):
raise RuntimeError(
)
return Storage(parent=self, main_resource=resource) | Get an instance to handle file storage (OneDrive / Sharepoint)
for the specified account resource
:param str resource: Custom resource to be used in this drive object
(Defaults to parent main_resource)
:return: a representation of OneDrive File Storage
:rtype: Storage
:... |
18,472 | def by_value(self, value, default=None):
try:
return [k for k, v in self.items() if v == value][0]
except IndexError:
if default is not None:
return default
raise ValueError( % value) | Returns the key for the given value |
18,473 | def do_cd(self, line):
args = self.line_to_args(line)
if len(args) == 0:
dirname =
else:
if args[0] == :
dirname = self.prev_dir
else:
dirname = args[0]
dirname = resolve_path(dirname)
mode = auto(get_... | cd DIRECTORY
Changes the current directory. ~ expansion is supported, and cd -
goes to the previous directory. |
18,474 | def get(key, default=-1):
if isinstance(key, int):
return Suite(key)
if key not in Suite._member_map_:
extend_enum(Suite, key, default)
return Suite[key] | Backport support for original codes. |
18,475 | def exec_command(cmd, in_data=, chdir=None, shell=None, emulate_tty=False):
assert isinstance(cmd, mitogen.core.UnicodeType)
return exec_args(
args=[get_user_shell(), , cmd],
in_data=in_data,
chdir=chdir,
shell=shell,
emulate_tty=emulate_tty,
) | Run a command in a subprocess, emulating the argument handling behaviour of
SSH.
:param bytes cmd:
String command line, passed to user's shell.
:param bytes in_data:
Optional standard input for the command.
:return:
(return code, stdout bytes, stderr bytes) |
18,476 | def do_set_log_level(self, arg):
if arg in [, ]:
_LOGGING.info(, arg)
if arg == :
_LOGGING.setLevel(logging.INFO)
_INSTEONPLM_LOGGING.setLevel(logging.INFO)
else:
_LOGGING.setLevel(logging.DEBUG)
_INSTEO... | Set the log level.
Usage:
set_log_level i|v
Parameters:
log_level: i - info | v - verbose |
18,477 | def load(self, verbose=False):
self._songs = []
page_num = 1
total_pages = 1
while page_num <= total_pages:
if verbose:
print( % page_num)
page = requests.get(ARTIST_URL.format(artist=self.name,
... | Load the list of songs.
Note that this only loads a list of songs that this artist was the main
artist of. If they were only featured in the song, that song won't be
listed here. There is a list on the artist page for that, I just
haven't added any parsing code for that, since I don't... |
18,478 | def register_comet_callback(self, *args, **kwargs):
sijax.plugin.comet.register_comet_callback(self._sijax, *args, **kwargs) | Registers a single Comet callback function
(see :ref:`comet-plugin`).
Refer to :func:`sijax.plugin.comet.register_comet_callback`
for more details - its signature differs slightly.
This method's signature is the same, except that the first
argument that :func:`sijax.plugin.come... |
18,479 | def in_project_directory() -> bool:
current_directory = os.path.realpath(os.curdir)
project_path = os.path.join(current_directory, )
return os.path.exists(project_path) and os.path.isfile(project_path) | Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file. |
18,480 | def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
for gate in self.gates:
gate.plot(flip=flip, ax_channels=ax_channels, ax=ax, *args, **kwargs) | {_gate_plot_doc} |
18,481 | def _lazy_load_get_model():
if django is None:
def _get_model(app, model):
raise import_failure
else:
from django import apps as django_apps
_get_model = django_apps.apps.get_model
_LAZY_LOADS[] = _get_model | Lazy loading of get_model.
get_model loads django.conf.settings, which may fail if
the settings haven't been configured yet. |
18,482 | def get_new_selection_attr_state(self, selection, attr_key):
cell_attributes = self.grid.code_array.cell_attributes
attr_values = self.attr_toggle_values[attr_key]
attr_map = dict(zip(attr_values, attr_values[1:] + attr_values[:1]))
selection_attrs = \
(a... | Toggles new attr selection state and returns it
Parameters
----------
selection: Selection object
\tSelection for which attr toggle shall be returned
attr_key: Hashable
\tAttribute key |
18,483 | def update(self, cur_value, mesg=None):
self.cur_value = cur_value
progress = float(self.cur_value) / self.max_value
num_chars = int(progress * self.max_chars)
num_left = self.max_chars - num_chars
if mesg is not None:
self.mesg = ... | Update progressbar with current value of process
Parameters
----------
cur_value : number
Current value of process. Should be <= max_value (but this is not
enforced). The percent of the progressbar will be computed as
(cur_value / max_value) * 100
m... |
18,484 | def predict(self, X):
X_ = self._check_array(X)
return exp(dot(X_, self._coef)) | Predict count for samples in X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples,]
Predicted count for each sample |
18,485 | def late():
from rez.package_resources_ import package_rex_keys
def decorated(fn):
if fn.__name__ in package_rex_keys:
raise ValueError("Cannot use @late decorator on function "
% fn.__name__)
setattr(fn, "_late", True)
_... | Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is u... |
18,486 | def filter_human_only(stmts_in, **kwargs):
from indra.databases import uniprot_client
if in kwargs and kwargs[]:
remove_bound = True
else:
remove_bound = False
dump_pkl = kwargs.get()
logger.info( %
len(stmts_in))
stmts_out = []
def criterion(agent):
... | Filter out statements that are grounded, but not to a human gene.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
remove_bound: Optional[bool]
... |
18,487 | def prior_from_config(cp, prior_section=):
variable_params, _ = distributions.read_params_from_config(
cp, prior_section=prior_section, vargs_section=,
sargs_section=)
constraints = distributions.read_constraints_from_config(cp)
dists = distributions.read_distributio... | Loads a prior distribution from the given config file.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
The config file to read.
sections : list of str, optional
The sections to retrieve the prior from. If ``None`` (the default),
will look in sections starting with... |
18,488 | def kill(self, sig):
if self.is_alive() and self._loop:
self._loop.call_soon_threadsafe(self._loop.stop) | Invoke the stop on the event loop method. |
18,489 | def chrome_getdata_view(request):
data = {}
if request.user.is_authenticated:
notifs = GCMNotification.objects.filter(sent_to__user=request.user).order_by("-time")
if notifs.count() > 0:
notif = notifs.first()
ndata = notif.data
if "title" in nda... | Get the data of the last notification sent to the current user.
This is needed because Chrome, as of version 44, doesn't support
sending a data payload to a notification. Thus, information on what
the notification is actually for must be manually fetched. |
18,490 | def remove_reactions(self, reactions, remove_orphans=False):
if isinstance(reactions, string_types) or hasattr(reactions, "id"):
warn("need to pass in a list")
reactions = [reactions]
context = get_context(self)
for reaction in reactions:
... | Remove reactions from the model.
The change is reverted upon exit when using the model as a context.
Parameters
----------
reactions : list
A list with reactions (`cobra.Reaction`), or their id's, to remove
remove_orphans : bool
Remove orphaned genes an... |
18,491 | def _configure_send(self, request, **kwargs):
requests_kwargs = {}
session = kwargs.pop(, self.session)
if session is not self.session:
self._init_session(session)
session.max_redirects = int(self.config.redirect_policy())
session.trust_... | Configure the kwargs to use with requests.
See "send" for kwargs details.
:param ClientRequest request: The request object to be sent.
:returns: The requests.Session.request kwargs
:rtype: dict[str,str] |
18,492 | def pivot(self, index, **kwargs):
try:
df = self._pivot(index, **kwargs)
return pd.pivot_table(self.df, index=kwargs["index"], **kwargs)
except Exception as e:
self.err(e, "Can not pivot dataframe") | Pivots a dataframe |
18,493 | def run_updater_in_background(self):
thread = threading.Thread(target=self.updater_loop())
thread.daemon = True
thread.start() | Starts a thread that runs the updater in the background. |
18,494 | def parameter_to_field(self, name):
if name not in self._parameters:
raise ValueError("no parameter found" % (name))
if self._fields.count(name) > 0:
raise ValueError("field with name already exists" % (name))
data = np.array([self._parameters[name]]*self._num... | Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter. |
18,495 | def _related(self, concept):
return concept.hypernyms() + \
concept.hyponyms() + \
concept.member_meronyms() + \
concept.substance_meronyms() + \
concept.part_meronyms() + \
concept.member_holonyms() + \
con... | Returns related concepts for a concept. |
18,496 | def write_entity(self, entity):
db, db_object_id = self._split_prefix(entity)
taxon = normalize_taxon(entity["taxon"]["id"])
vals = [
db,
db_object_id,
entity.get(),
entity.get(),
entity.get(),
entity.get(),
... | Write a single entity to a line in the output file |
18,497 | def user_present(name,
password,
email,
tenant=None,
enabled=True,
roles=None,
profile=None,
password_reset=True,
project=None,
**connection_args):
ret = {: n... | Ensure that the keystone user is present with the specified properties.
name
The name of the user to manage
password
The password to use for this user.
.. note::
If the user already exists and a different password was set for
the user than the one specified he... |
18,498 | def add_header_part(self):
header_part = HeaderPart.new(self.package)
rId = self.relate_to(header_part, RT.HEADER)
return header_part, rId | Return (header_part, rId) pair for newly-created header part. |
18,499 | def volshow(
data,
lighting=False,
data_min=None,
data_max=None,
max_shape=256,
tf=None,
stereo=False,
ambient_coefficient=0.5,
diffuse_coefficient=0.8,
specular_coefficient=0.5,
specular_exponent=5,
downscale=1,
level=[0.1, 0.5, 0.9],
opacity=[0.01, 0.05, 0.1],
... | Visualize a 3d array using volume rendering.
Currently only 1 volume can be rendered.
:param data: 3d numpy array
:param origin: origin of the volume data, this is to match meshes which have a different origin
:param domain_size: domain size is the size of the volume
:param bool lighting: use lig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.