Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
337,900 | def availability_zone_list(request):
try:
return api.nova.availability_zone_list(request)
except Exception:
exceptions.handle(request,
_())
return [] | Utility method to retrieve a list of availability zones. |
337,901 | def path(self, path):
url = furl(self._request.rawurl)
url.path = path
self._request.url = url.url
self.add_matcher(matcher(, path)) | Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance. |
337,902 | def set_attr(self, name: str, values: np.ndarray, axis: int = 0, dtype: str = None) -> None:
deprecated(" is deprecated. Use or instead")
if axis == 0:
self.ra[name] = values
else:
self.ca[name] = values | **DEPRECATED** - Use `ds.ra.key = values` or `ds.ca.key = values` instead |
337,903 | def validate_all_keys_in_obj(obj_name, obj, validation_fun):
for key, value in obj.items():
validation_fun(obj_name, key)
if isinstance(value, dict):
validate_all_keys_in_obj(obj_name, value, validation_fun)
elif isinstance(value, list):
validate_all_items_in_lis... | Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the value
of `key`.
Returns:
None: indica... |
337,904 | def _format_listnodes(self, listnodes):
fields = list()
for name, node in listnodes:
fields.append((, , , ))
fields.append((, % name, , ))
for link in node.get_links():
linked_model = link[](super_context)
null = self._marker_... | Format ListNodes and their fields into tuples that can be printed with _print_fields(). |
337,905 | def fetch(self, keyDict):
for key in keyDict.keys():
keyDict[key] = self.tbl[key] | Like update(), but for retrieving values. |
337,906 | def drafts(self):
pub = self.on_site().filter(status=self.model.DRAFT)
if settings.PAGE_SHOW_START_DATE:
pub = pub.filter(publication_date__gte=datetime.now())
return pub | Creates a :class:`QuerySet` of drafts using the page's
:attr:`Page.publication_date`. |
337,907 | def render_latex_sub_super(
name, subs=None, supers=None, translate_symbols=True, sep=):
ralphamunu\\alpha_{\\mu,\\nu}^{2}alpha12(1)\\alpha_{12}^{(1)}
if subs is None:
subs = []
if supers is None:
supers = []
if translate_symbols:
supers = [_translate_symbols(str(sup)) fo... | r'''Assemble a string from the primary name and the given sub- and
superscripts::
>>> render_latex_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2])
'\\alpha_{\\mu,\\nu}^{2}'
>>> render_latex_sub_super(
... name='alpha', subs=['1', '2'], supers=['(1)'], sep='')
'\\... |
337,908 | def CreateDynamicDisplayAdSettings(client, opener):
media_service = client.GetService(, )
logo = {
: ,
: _CreateImage(media_service, opener, )
}
dynamic_settings = {
: logo,
: ,
:
}
return dynamic_settings | Creates dynamic display ad settings.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
Returns:
A dict containing the dynamic display ad settings. |
337,909 | def input_yes_no(msg=):
print +msg
while(True):
i=raw_input()
i=i.lower()
if i== or i==:
return True
elif i== or i==:
return False
else:
print | Simple helper function |
337,910 | def __RegisterDescriptor(self, new_descriptor):
if not isinstance(new_descriptor, (
extended_descriptor.ExtendedMessageDescriptor,
extended_descriptor.ExtendedEnumDescriptor)):
raise ValueError( % (
type(new_descriptor),))
full_name = ... | Register the given descriptor in this registry. |
337,911 | def parse_pretty_midi(self, pm, mode=, algorithm=,
binarized=False, skip_empty_tracks=True,
collect_onsets_only=False, threshold=0,
first_beat_time=None):
if mode not in (, ):
raise ValueError("`mode` must be one ... | Parse a :class:`pretty_midi.PrettyMIDI` object. The data type of the
resulting pianorolls is automatically determined (int if 'mode' is
'sum', np.uint8 if `mode` is 'max' and `binarized` is False, bool if
`mode` is 'max' and `binarized` is True).
Parameters
----------
pm... |
337,912 | def hash(ctx, message_id, message):
conf = Config(message_id=message_id)
mail = Mail(message, conf)
logger.info(mail.header_text)
logger.info( * 70)
logger.info(.format(mail.hash_key)) | Take a single mail message and show its canonicalised form and hash.
Mainly used to debug message hashing. |
337,913 | def service_confirmation(self, bslpdu):
if _debug: ProxyServiceNetworkAdapter._debug("service_confirmation %r", bslpdu)
pdu = NPDU(bslpdu.pduData)
pdu.pduSource = bslpdu.bslciAddress
if isinstance(bslpdu, ProxyToServerBroadcastNPDU):
pdu... | Receive packets forwarded by the proxy and send them upstream to the network service access point. |
337,914 | def save_form(self, request, form, change):
OwnableAdmin.save_form(self, request, form, change)
return DisplayableAdmin.save_form(self, request, form, change) | Super class ordering is important here - user must get saved first. |
337,915 | def libvlc_event_attach(p_event_manager, i_event_type, f_callback, user_data):
f = _Cfunctions.get(, None) or \
_Cfunction(, ((1,), (1,), (1,), (1,),), None,
ctypes.c_int, EventManager, ctypes.c_uint, Callback, ctypes.c_void_p)
return f(p_event_manager, i_event_type, f_callback,... | Register for an event notification.
@param p_event_manager: the event manager to which you want to attach to. Generally it is obtained by vlc_my_object_event_manager() where my_object is the object you want to listen to.
@param i_event_type: the desired event to which we want to listen.
@param f_callback: t... |
337,916 | def expand_permissions(self, permissions):
for p in permissions:
np = dict(p)
values = {}
for k in (u,
u,
u,
u):
values[k] = np.pop(k, ())
np[k] = []
for k, ... | Expand each list of cidr, prefix list, user id group pair
by port/protocol as an individual rule.
The console ux automatically expands them out as addition/removal is
per this expansion, the describe calls automatically group them. |
337,917 | def from_dict(event_dict):
return SnippetEvent(
callback_id=event_dict[],
name=event_dict[],
creation_time=event_dict[],
data=event_dict[]) | Create a SnippetEvent object from a dictionary.
Args:
event_dict: a dictionary representing an event.
Returns:
A SnippetEvent object. |
337,918 | def make_bigint_autoincrement_column(column_name: str,
dialect: Dialect) -> Column:
if dialect.name == SqlaDialectName.MSSQL:
return Column(column_name, BigInteger,
Sequence(, start=1, increment=1))
else:
rais... | Returns an instance of :class:`Column` representing a :class:`BigInteger`
``AUTOINCREMENT`` column in the specified :class:`Dialect`. |
337,919 | def _get_section_values(self, config, section):
src_host = self._get_hosts_from_names(config.get(section, )) \
if config.has_option(section, ) else None
src_file = [self._get_abs_filepath(config.get(section, ))] \
if config.has_option(section, ) else None
if src_... | extract src and dst values from a section |
337,920 | def preferences(self):
prefs = self._get()
class Proxy(Client):
def __init__(self, url, prefs, auth, session):
super(Proxy, self).__init__(url)
self.prefs = prefs
self._is_authenticated = auth
self.sessio... | Get the current qBittorrent preferences.
Can also be used to assign individual preferences.
For setting multiple preferences at once,
see ``set_preferences`` method.
Note: Even if this is a ``property``,
to fetch the current preferences dict, you are required
to call it ... |
337,921 | def update(self, copy=False, **params):
if copy:
self = deepcopy(self)
for k, v in params.items():
if not hasattr(self, k):
if not self.unrecognized_ok:
raise ArgumentError.pyexc("Unknown option", k)
self._set_common(k... | Chained assignment operator.
This may be used to quickly assign extra parameters to the
:class:`Query` object.
Example::
q = Query(reduce=True, full_sec=True)
# Someplace later
v = View(design, view, query=q.update(mapkey_range=["foo"]))
Its prim... |
337,922 | def is_admin(self, roles):
for r in roles:
if r in self.admin_roles:
return True
return False | determine from a list of roles if is ldapcherry administrator |
337,923 | def get_cse_code(self, exprs, basename=None,
dummy_groups=(), arrayify_groups=()):
if basename is None:
basename =
cse_defs, cse_exprs = sympy.cse(
exprs, symbols=sympy.numbered_symbols(basename))
cse_defs_code = [
(vna... | Get arrayified code for common subexpression.
Parameters
----------
exprs : list of sympy expressions
basename : str
Stem of variable names (default: cse).
dummy_groups : tuples |
337,924 | def approx_equals(self, other, atol):
if other is self:
return True
elif not isinstance(other, RectPartition):
return False
else:
return (self.set.approx_equals(other.set, atol=atol) and
self.grid.approx_equals(other.grid, atol=ato... | Return ``True`` in case of approximate equality.
Returns
-------
approx_eq : bool
``True`` if ``other`` is a `RectPartition` instance with
``self.set == other.set`` up to ``atol`` and
``self.grid == other.other`` up to ``atol``, ``False`` otherwise. |
337,925 | def effective_sample_size(data, *, var_names=None):
r
if isinstance(data, np.ndarray):
return _get_ess(data)
dataset = convert_to_dataset(data, group="posterior")
var_names = _var_names(var_names, dataset)
dataset = dataset if var_names is None else dataset[var_names]
return xr.apply_u... | r"""Calculate estimate of the effective sample size.
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az.convert_to_dataset for details
At least 2 posterior chains are needed to compute this diagnostic of one o... |
337,926 | def store_oath_entry(args, nonce, aead, oath_c):
data = {"key": args.uid,
"aead": aead.data.encode(),
"nonce": nonce.encode(),
"key_handle": args.key_handle,
"oath_C": oath_c,
"oath_T": None,
}
entry = ValOathEntry(data)
db = ValOa... | Store the AEAD in the database. |
337,927 | def app_id(iface=):
if iface:
return uniqid(iface)
if platform.system() == :
_ava_start = []
elif platform.system() == :
_ava_start = [, ]
else:
return None
nics = psutil.net_if_addrs()
_ifces = list(nics.keys())
_ifces.sort()
for _ in _ifces:
... | 依据指定的 ``iface`` 名, 来获取程序运行需要的唯一ID
- iface 为空, 则自动从系统选择第一个可用的网络接口 mac
- 顺序,自动获取编号最小的网络接口:
+ macosx: en0~n
+ linux: eth/wlan(0~n)
:param iface: ``系统中的网络接口名``
:type iface: str
:return:
:rtype: |
337,928 | def values(self):
args = []
for d in self.args, self.form:
if not isinstance(d, MultiDict):
d = MultiDict(d)
args.append(d)
return CombinedMultiDict(args) | A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
:attr:`args` and :attr:`form`. |
337,929 | def unpin_chat_message(chat_id, **kwargs):
params = dict(chat_id=chat_id)
return TelegramBotRPCRequest(, params=params, on_result=lambda result: result, **kwargs) | Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to
work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel.
:param chat_id: Unique identifier for the target chat or username ... |
337,930 | def to_dict(self):
if self.txid is None and self.output is None:
return None
else:
return {
: self.txid,
: self.output,
} | Transforms the object to a Python dictionary.
Returns:
(dict|None): The link as an alternative serialization format. |
337,931 | def gen_url_regex(resource):
" URL regex for resource class generator. "
if resource._meta.parent:
yield resource._meta.parent._meta.url_regex.rstrip().lstrip()
for p in resource._meta.url_params:
yield % dict(name=p)
if resource._meta.prefix:
yield resource._meta.prefix
... | URL regex for resource class generator. |
337,932 | def cholesky_concat(chol, cols, name=None):
with tf.compat.v2.name_scope(name or ):
dtype = dtype_util.common_dtype([chol, cols], preferred_dtype=tf.float32)
chol = tf.convert_to_tensor(value=chol, name=, dtype=dtype)
cols = tf.convert_to_tensor(value=cols, name=, dtype=dtype)
n = prefer_static.sha... | Concatenates `chol @ chol.T` with additional rows and columns.
This operation is conceptually identical to:
```python
def cholesky_concat_slow(chol, cols): # cols shaped (n + m) x m = z x m
mat = tf.matmul(chol, chol, adjoint_b=True) # batch of n x n
# Concat columns.
mat = tf.concat([mat, cols[...... |
337,933 | def edges_unique_length(self):
vector = np.subtract(*self.vertices[self.edges_unique.T])
length = np.linalg.norm(vector, axis=1)
return length | How long is each unique edge.
Returns
----------
length : (len(self.edges_unique), ) float
Length of each unique edge |
337,934 | def createSegments(self, cells):
segments = None
for connections in self.connectionsBySource.itervalues():
created = connections.createSegments(cells)
if segments is None:
segments = created
else:
np.testing.assert_equal(segments, created)
return segments | Create a segment on each of the specified cells.
@param cells (numpy array) |
337,935 | def from_random(self, power, gm, r0, omega=None, function=,
lmax=None, normalization=, csphase=1,
exact_power=False):
if type(normalization) != str:
raise ValueError(
.format(str(type(normaliz... | Initialize the class of gravitational potential spherical harmonic
coefficients as random variables with a given spectrum.
Usage
-----
x = SHGravCoeffs.from_random(power, gm, r0, [omega, function, lmax,
normalization,
... |
337,936 | def p_statement_declare(p):
p[0] = ast.Declare(p[3], p[5], lineno=p.lineno(1)) | statement : DECLARE LPAREN declare_list RPAREN declare_statement |
337,937 | def _get_input_target_path(self, local_file_path):
path, filename = os.path.split(local_file_path)
if in filename:
return path +
else:
return local_file_path | Returns a directory or file path to be the target for "gsutil cp".
If the filename contains a wildcard, then the target path must
be a directory in order to ensure consistency whether the source pattern
contains one or multiple files.
Args:
local_file_path: A full path terminating in a file or ... |
337,938 | def previous_page_url(self):
if in self._payload and in self._payload[]:
return self._payload[][]
elif in self._payload and self._payload[]:
return self._version.domain.absolute_url(self._payload[])
return None | :return str: Returns a link to the previous_page_url or None if doesn't exist. |
337,939 | def next_trials(self):
trials = list(self._trial_generator)
if self._shuffle:
random.shuffle(trials)
self._finished = True
return trials | Provides Trial objects to be queued into the TrialRunner.
Returns:
trials (list): Returns a list of trials. |
337,940 | def path(self, which=None):
if which:
return .format(
super(Template, self).path(which=), which)
return super(Template, self).path(which) | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
import
/templates/import
export
/templates/export |
337,941 | def goal(self, x, y, z, d=50.0):
return (x-self.x)/d, (y-self.y)/d, (z-self.z)/d | Tendency towards a particular place. |
337,942 | def pairs(args):
p = OptionParser(pairs.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
anchorfile, prefix = args
outfile = prefix + ".pairs"
fw = open(outfile, "w")
af = AnchorFile(anchorfile)
blocks = af.blocks
pad = len(str(... | %prog pairs anchorsfile prefix
Convert anchorsfile to pairsfile. |
337,943 | def write_extent(self):
self.extent_dialog.accept()
self.extent_dialog.clear_extent.disconnect(
self.parent.dock.extent.clear_user_analysis_extent)
self.extent_dialog.extent_defined.disconnect(
self.parent.dock.define_user_analysis_extent)
self.extent_dia... | After the extent selection, save the extent and disconnect signals. |
337,944 | def looping_call(f, sleep=5, inc_sleep=0, max_sleep=60, timeout=600,
exceptions=(), *args, **kwargs):
time_start = time.time()
expiration = time_start + timeout
retry = True
while retry:
expired = timeout and (time.time() > expiration)
LOG.debug(
"t... | Helper function that to run looping call with fixed/dynamical interval.
:param f: the looping call function or method.
:param sleep: initial interval of the looping calls.
:param inc_sleep: sleep time increment, default as 0.
:param max_sleep: max sleep time.
:param timeout: loop... |
337,945 | def consider_member(name_member, member, module, class_=None):
if name_member.startswith():
return False
if inspect.ismodule(member):
return False
real_module = getattr(member, , None)
if not real_module:
return True
if real_module != ... | Return |True| if the given member should be added to the
substitutions. If not return |False|.
Some examples based on the site-package |numpy|:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy
A constant like |nan| should be added:
>>> Substituter.... |
337,946 | def ebic(self, gamma=0):
if not self.is_fitted_:
return
if not isinstance(self.precision_, list):
return metrics.ebic(
self.sample_covariance_,
self.precision_,
self.n_samples_,
self.n_features_,
... | Compute EBIC scores for each model. If model is not "path" then
returns a scalar score value.
May require self.path_
See:
Extended Bayesian Information Criteria for Gaussian Graphical Models
R. Foygel and M. Drton
NIPS 2010
Parameters
----------
... |
337,947 | def get_symmetrically_distinct_miller_indices(structure, max_index):
r = list(range(-max_index, max_index + 1))
r.reverse()
conv_hkl_list = [miller for miller in itertools.product(r, r, r) if any([i != 0 for i in miller])]
sg = SpacegroupAnalyzer(structure)
if sg.get_crystal_system... | Returns all symmetrically distinct indices below a certain max-index for
a given structure. Analysis is based on the symmetry of the reciprocal
lattice of the structure.
Args:
structure (Structure): input structure.
max_index (int): The maximum index. For example, a max_index of 1
... |
337,948 | def can_transition(self, status_from: str, status_to: str) -> bool:
if not self.STATUSES.can_transition(status_from=status_from, status_to=status_to):
_logger.info(
,
str(self), status_from, status_to)
return False
return True | Update the status of the current instance.
Returns:
boolean: if the instance is updated. |
337,949 | def get_records(self, sql, parameters=None):
with closing(self.get_conn()) as conn:
with closing(conn.cursor()) as cur:
if parameters is not None:
cur.execute(sql, parameters)
else:
cur.execute(sql)
retu... | Executes the sql and returns a set of records.
:param sql: the sql statement to be executed (str) or a list of
sql statements to execute
:type sql: str or list
:param parameters: The parameters to render the SQL query with.
:type parameters: mapping or iterable |
337,950 | def write_function(self, job):
def mapping(self, input1, input2)job.fileStore.logToMaster()tempDir = fileStore.getLocalTempDir()
fn_section = self.write_function_header(job)
fn_section += self.write_function_cmdline(job)
if self.needsdocker(job):
... | Writes out a python function for each WDL "task" object.
Each python function is a unit of work written out as a string in
preparation to being written out to a file. In WDL, each "job" is
called a "task". Each WDL task is written out in multiple steps:
1: Header and inputs (e.g. 'de... |
337,951 | async def deregister(self, service):
service_id = extract_attr(service, keys=["ServiceID", "ID"])
response = await self._api.get(
"/v1/agent/service/deregister", service_id)
return response.status == 200 | Deregisters a local service
Parameters:
service (ObjectID): Service ID
Returns:
bool: ``True`` on success
The deregister endpoint is used to remove a service from the local
agent. The agent will take care of deregistering the service with the
Catalog. If... |
337,952 | def publish_multiple(self, msgs, hostname="localhost", port=1883,
client_id="", keepalive=60, will=None, auth=None,
tls=None, protocol=mqtt.MQTTv31):
logger.info( %
(hostname, port, msgs))
publish.multiple(msgs, hostname, port, client_id, keepalive,
... | Publish multiple messages and disconnect. This keyword uses the
[http://eclipse.org/paho/clients/python/docs/#multiple|multiple]
function of publish module.
`msgs` a list of messages to publish. Each message is either a dict
or a tuple. If a dict, it must be of the form:
... |
337,953 | def _authenticate_websocket(self, websocket, event_handler):
log.debug()
json_data = json.dumps({
"seq": 1,
"action": "authentication_challenge",
"data": {
"token": self._token
}
}).encode()
yield from websocket.send(json_data)
while True:
message = yield from websocket.recv()
status ... | Sends a authentication challenge over a websocket.
This is not needed when we just send the cookie we got on login
when connecting to the websocket. |
337,954 | def separate_string(string):
string_list = regex.split(r, regex.sub(r, , string))
return string_list[::2], string_list[1::2] | >>> separate_string("test <2>")
(['test ', ''], ['2']) |
337,955 | def last_midnight():
now = datetime.now()
return datetime(now.year, now.month, now.day) | return a datetime of last mid-night |
337,956 | def generate_travis_yml():
def get_mustache_file(file_name):
return pkg_resources.resource_string(__name__, file_name).decode()
template = get_mustache_file()
before_install_linux = get_mustache_file()
before_install_osx = get_mustache_file()
env_osx_with_pyenv = get_mustache_file()
docker_build_ima... | Generates content for a .travis.yml file from templates. |
337,957 | def _normalize_status(status):
formatted_status = status.lower().replace(" ", "_")
for normalized_status in Services.ALL_STATUSES:
if formatted_status.startswith(normalized_status):
return normalized_status
return formatted_status | Try to normalize the HAProxy status as one of the statuses defined in `ALL_STATUSES`,
if it can't be matched return the status as-is in a tag-friendly format
ex: 'UP 1/2' -> 'up'
'no check' -> 'no_check' |
337,958 | def prt_summary(self, prt=sys.stdout):
desc = "NtGoeaResults" if self.is_goterm else "namedtuple"
prt.write("{N} GOEA results from {O}. P-values stored in {P}.\n".format(
N=len(self.go2res), O=desc, P=self.pval_name)) | Print summary of GOEA plotting object. |
337,959 | def create_file_from_text(self, share_name, directory_name, file_name,
text, encoding=, content_settings=None,
metadata=None, timeout=None):
_validate_not_none(, share_name)
_validate_not_none(, file_name)
_validate_not_none(, text)... | Creates a new file from str/unicode, or updates the content of an
existing file, with automatic chunking and progress notifications.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_name:
... |
337,960 | def alpha(self, value):
if value != self._alpha and \
isinstance(value, int):
self._alpha = value | gets/sets the alpha value |
337,961 | def _shl32(ins):
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
output = _32bit_oper(op1)
if int(op2) == 0:
output.append()
output.append()
return output
if int(op2) > 1:
label = tmp_label()
output.append( % op2)
... | Logical Left shift 32bit unsigned integers.
The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 0, do nothing |
337,962 | def find_in_path(path, file):
for p in path.split(os.pathsep):
candidate = os.path.join(p, file)
if os.path.exists(candidate) and os.path.isfile(candidate):
return candidate
return False | Find a file in a given path string. |
337,963 | def sys_update_char(
asciiCode: int,
fontx: int,
fonty: int,
img: tcod.image.Image,
x: int,
y: int,
) -> None:
lib.TCOD_sys_update_char(_int(asciiCode), fontx, fonty, img, x, y) | Dynamically update the current font with img.
All cells using this asciiCode will be updated
at the next call to :any:`tcod.console_flush`.
Args:
asciiCode (int): Ascii code corresponding to the character to update.
fontx (int): Left coordinate of the character
in the ... |
337,964 | def _make_sparse_blocks_with_virtual(self, variable, records, data):
variablevariable
sparse_blocks = CDF._make_blocks(records)
sparse_data = []
if (isinstance(data, np.ndarray)):
for sblock in sparse_blocks:
asparse = []
... | Handles the data for the variable with sparse records.
Organizes the physical record numbers into blocks in a list:
[[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...]
Place consecutive physical records into a single block
Parameters:
variable: dict
... |
337,965 | def _walk(self) -> None:
incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in
self._world.get_valid_starting_types()]
self._completed_paths = []
actions = self._world.get_valid_actions()
multi_match_substi... | Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. |
337,966 | def encode_row(fields):
unicode_fields = [unicode(f) for f in fields]
escaped_fields = map(escape, unicode_fields)
return _field_delimiter.join(escaped_fields) | Encode a list of column values into a [incr tsdb()] profile line.
Encoding involves escaping special characters for each value, then
joining the values into a single string with the field delimiter
(`"@"` by default). It does not fill in default values (see
make_row()).
Args:
fields: a lis... |
337,967 | def _seed(self):
for name in self.__slots__:
setattr(self, name, getattr(logging, name)) | Seed initial fields |
337,968 | def _pad_add_1d(av, size, stlen):
assert len(size) == 1
padx = _get_pad_left_right(av.shape[0], size[0])
mask = np.zeros(av.shape, dtype=bool)
mask[stlen:-stlen] = True
border = av[~mask]
if av.dtype.name.count("complex"):
padval = np.average(np.abs(border)) * \
np.exp... | 2D component of `pad_add` |
337,969 | def move_in_16(library, session, space, offset, length, extended=False):
buffer_16 = (ViUInt16 * length)()
if extended:
ret = library.viMoveIn16Ex(session, space, offset, length, buffer_16)
else:
ret = library.viMoveIn16(session, space, offset, length, buffer_16)
return list(buffer... | Moves an 16-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (C... |
337,970 | def getCameraErrorNameFromEnum(self, eCameraError):
fn = self.function_table.getCameraErrorNameFromEnum
result = fn(eCameraError)
return result | Returns a string for an error |
337,971 | def set_webhook(dispatcher: Dispatcher, webhook_path: str, *, loop: Optional[asyncio.AbstractEventLoop] = None,
skip_updates: bool = None, on_startup: Optional[Callable] = None,
on_shutdown: Optional[Callable] = None, check_ip: bool = False,
retry_after: Optional[Union[st... | Set webhook for bot
:param dispatcher: Dispatcher
:param webhook_path: str
:param loop: Optional[asyncio.AbstractEventLoop] (default: None)
:param skip_updates: bool (default: None)
:param on_startup: Optional[Callable] (default: None)
:param on_shutdown: Optional[Callable] (default: None)
... |
337,972 | def train_agent(real_env, learner, world_model_dir, hparams, epoch):
initial_frame_chooser = rl_utils.make_initial_frame_chooser(
real_env, hparams.frame_stack_size, hparams.simulation_random_starts,
hparams.simulation_flip_first_random_for_beginning
)
env_fn = rl.make_simulated_env_fn_from_hparams... | Train the PPO agent in the simulated environment. |
337,973 | def nth(self, index):
def _transform(xs):
try:
return [next(islice(iter(xs), index, None))]
except (StopIteration, ValueError):
return []
return self.transform(_transform, ) | Return a query that selects the element at `index` (starts from 0).
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.nth(2).results
[2]
Args:
index ... |
337,974 | def get_one(slug):
item = Product.objects.published()\
.prefetch_related(Prefetch("paramvalue_set", queryset=ParamValue.objects.published().order_by().prefetch_related("param")))\
.filter(slug=slug).first()
return item | Возвращает один товар
:param slug: символьный код товара
:return: |
337,975 | def process_event(self, event):
new_event = event
if self._absolute:
new_event.y -= self._canvas.start_line
if self.is_mouse_over(new_event) and event.buttons != 0:
self._set_pos((new_event.y - self._y) / (self._height - 1))
return ... | Handle input on the scroll bar.
:param event: the event to be processed.
:returns: True if the scroll bar handled the event. |
337,976 | def get_interface_reactions(self, reactant1, reactant2,
open_el=None, relative_mu=None,
use_hull_energy=False):
payload = {"reactants": " ".join([reactant1, reactant2]),
"open_el": open_el,
"relative_m... | Gets critical reactions between two reactants.
Get critical reactions ("kinks" in the mixing ratio where
reaction products change) between two reactants. See the
`pymatgen.analysis.interface_reactions` module for more info.
Args:
reactant1 (str): Chemical formula for reacta... |
337,977 | def call_external_subprocess(command_list,
stdin_filename=None, stdout_filename=None, stderr_filename=None,
env=None):
if stdin_filename: stdin = open(stdin_filename, "r")
else: stdin = None
if stdout_filename: stdout = open(stdout_filename, "w")
else:... | Run the command and arguments in the command_list. Will search the system
PATH for commands to execute, but no shell is started. Redirects any selected
outputs to the given filename. Waits for command completion. |
337,978 | def py(sfn, string=False, **kwargs):
resultdata
if not os.path.isfile(sfn):
return {}
base_fname = os.path.basename(sfn)
name = base_fname.split()[0]
if USE_IMPORTLIB:
loader = importlib.machinery.SourceFileLoader(name, sfn)
spec = importlib.util.spec_from_file_l... | Render a template from a python source file
Returns::
{'result': bool,
'data': <Error data or rendered file path>} |
337,979 | def include_once(filename, lineno, local_first):
filename = search_filename(filename, lineno, local_first)
if filename not in INCLUDED.keys():
return include_file(filename, lineno, local_first)
if len(INCLUDED[filename]) > 1:
warning(lineno, "file already included more than o... | Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
The file is ignored if it was previuosly included (a warning will
be emitted though).
If local_first is True, then it will first search the file in the
loca... |
337,980 | def make_url(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0:
return args[0]
temp_args = unpack_args(*args)
temp_arg_count = len(temp_args)
if temp_arg_count > 1 and isinstance(temp_args[-1], list):
path_fragments = temp_args[0 : -1]
query_string = u... | >>> make_url("https://host/api", "users", "user-name", "projects", token="api_token")
'https://host/api/users/user-name/projects?token=api_token'
>>> make_url("https://host/api", "users", "user-name", "projects/", token="api_token")
'https://host/api/users/user-name/projects/?token=api_token'
>>> make_u... |
337,981 | def attribute_rewrite_map(self):
rewrite_map = dict()
token_rewrite_map = self.generate_attribute_token_rewrite_map()
for attribute_name, type_instance in self.getmembers():
if isinstance(type_instance, DataType):
attribute_tokens = attribute_name.split()
... | Example: long_name -> a_b
:return: the rewrite map
:rtype: dict |
337,982 | def get_api(version: str, ui_version: str=None) -> API_1:
ui_version = ui_version if ui_version else "~1.0"
return _get_api_with_app(version, ui_version, ApplicationModule.app) | Get a versioned interface matching the given version and ui_version.
version is a string in the form "1.0.2". |
337,983 | def debug(self, nest_level=1):
if self.children is None:
self._parse_children()
prefix = * nest_level
_basic_debug(prefix, self)
for child in self:
child.debug(nest_level + 1) | Show the binary data and parsed data in a tree structure |
337,984 | def get_operation_type(self, operation_name):
operations_map = self.operations_map
if not operation_name and len(operations_map) == 1:
return next(iter(operations_map.values()))
return operations_map.get(operation_name) | Returns the operation type ('query', 'mutation', 'subscription' or None)
for the given operation_name.
If no operation_name is provided (and only one operation exists) it will return the
operation type for that operation |
337,985 | def write_glossary(manuscript=os.path.expanduser(), linesep=None):
linesep = linesep or os.linesep
lines = [, , , ]
acronyms = get_acronyms(manuscript)
for a in acronyms:
lines.append(.format(a[0], a[1][0].upper() + a[1][1:]))
return linesep.join(lines) | Compose an asciidoc string with acronyms culled from the manuscript |
337,986 | def build_checkout_params(self, **kwargs):
params = kwargs or {}
if self.sender:
params[] = self.sender.get()
params[] = self.sender.get()
params[] = self.sender.get()
params[] = is_valid_email(self.sender.get())
params[] = is_valid_cp... | build a dict with params |
337,987 | def _resolve_command(self, command, target):
if command == "privmsg":
if irc.client.is_channel(target):
command = "pubmsg"
else:
if irc.client.is_channel(target):
command = "pubnotice"
else:
command = "privnotic... | Get the correct event for the command
Only for 'privmsg' and 'notice' commands.
:param command: The command string
:type command: :class:`str`
:param target: either a user or a channel
:type target: :class:`str`
:returns: the correct event type
:rtype: :class:`s... |
337,988 | def scalar_leaf_only(operator):
def decorator(f):
@wraps(f)
def wrapper(filter_operation_info, context, parameters, *args, **kwargs):
if in kwargs:
current_operator = kwargs[]
else:
current_operator ... | Ensure the filter function is only applied to scalar leaf types. |
337,989 | def reraise(error):
if hasattr(error, "_type_"):
six.reraise(type(error), error, error._traceback)
raise error | Re-raises the error that was processed by prepare_for_reraise earlier. |
337,990 | def _read(self, fileobj, amount, truncate=True):
if len(self._initial_data) == 0:
return fileobj.read(amount)
if amount <= len(self._initial_data):
data = self._initial_data[:amount]
if truncate:
self._initial_... | Reads a specific amount of data from a stream and returns it. If there
is any data in initial_data, that will be popped out first.
:type fileobj: A file-like object that implements read
:param fileobj: The stream to read from.
:type amount: int
:param amount: The number of byte... |
337,991 | def from_dict(cls, d):
return cls(
d[],
d[],
d[],
Lnk.charspan(d[], d[]) if in d else None,
form=d[],
surface=d.get(),
pos=zip(d.get(, []), d.get(, []))
) | Decode from a dictionary as from :meth:`to_dict`. |
337,992 | def stack_fits(fitslist, outname, axis=0, ctype=None, keep_old=False, fits=False):
import numpy
try:
import pyfits
except ImportError:
warnings.warn("Could not find pyfits on this system. FITS files will not be stacked")
sys.exit(0)
hdu = pyfits.open(fitslist[0])[0]
hdr... | Stack a list of fits files along a given axiis.
fitslist: list of fits file to combine
outname: output file name
axis: axis along which to combine the files
fits: If True will axis FITS ordering axes
ctype: Axis label in the fits header (if given, axis will be ignored)
... |
337,993 | def sites_at_edges( self ):
min_x = min( [ s.r[0] for s in self.sites ] )
max_x = max( [ s.r[0] for s in self.sites ] )
min_y = min( [ s.r[1] for s in self.sites ] )
max_y = max( [ s.r[1] for s in self.sites ] )
min_z = min( [ s.r[2] for s in self.sites ] )
max_z... | Finds the six sites with the maximum and minimum coordinates along x, y, and z.
Args:
None
Returns:
(List(List)): In the order [ +x, -x, +y, -y, +z, -z ] |
337,994 | def build_kernel_argv(self, argv=None):
if argv is None:
argv = sys.argv[1:]
self.kernel_argv = swallow_argv(argv, self.frontend_aliases, self.frontend_flags)
self.kernel_argv.append("--KernelApp.parent_appname="%self.name) | build argv to be passed to kernel subprocess |
337,995 | def _convert_to_clusters(c):
new_dict = {}
n_cluster = 0
logger.debug("_convert_to_cluster: loci %s" % c.loci2seq.keys())
for idl in c.loci2seq:
n_cluster += 1
new_c = cluster(n_cluster)
new_c.loci2seq[idl] = c.loci2seq[idl]
new_dict[n_cluster] = new_c
l... | Return 1 cluster per loci |
337,996 | def build_panel(panel_info, adapter):
panel_name = panel_info.get(, panel_info.get())
if not panel_name:
raise KeyError("Panel has to have a id")
panel_obj = dict(panel_name = panel_name)
LOG.info("Building panel with name: {0}".format(panel_name))
try:
institute_id =... | Build a gene_panel object
Args:
panel_info(dict): A dictionary with panel information
adapter (scout.adapter.MongoAdapter)
Returns:
panel_obj(dict)
gene_panel = dict(
panel_id = str, # required
institute = str, # institute_id, required
v... |
337,997 | def list_employees(order_by=):
ret = {}
status, result = _query(action=, command=)
root = ET.fromstring(result)
directory = root.getchildren()
for cat in directory:
if cat.tag != :
continue
for item in cat:
emp_id = item.items()[0][1]
emp_ret ... | Show all employees for this company.
CLI Example:
salt myminion bamboohr.list_employees
By default, the return data will be keyed by ID. However, it can be ordered
by any other field. Keep in mind that if the field that is chosen contains
duplicate values (i.e., location is used, for a compan... |
337,998 | def docserver(self, server_name, package_documentation, methods):
fdict = {}
for key, value in methods.items():
fdict[key] = + key
fdict[value] = fdict[key]
server_name = self.escape(server_name)
head = % server_name
result = self.heading(head... | Produce HTML documentation for an XML-RPC server. |
337,999 | def set_default_var(**vars):
for k, v in vars.iteritems():
current_context.vars.setdefault(k, v) | Sets context variables using the key/value provided in the options |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.