Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
373,500 | def get_open_port() -> int:
free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
free_socket.bind(("", 0))
free_socket.listen(1)
port = free_socket.getsockname()[1]
free_socket.close()
return port | Gets a PORT that will (probably) be available on the machine.
It is possible that in-between the time in which the open PORT of found and when it is used, another process may
bind to it instead.
:return: the (probably) available PORT |
373,501 | def set_functions(self, f=, p=, c=None, bg=None, **kwargs):
self._pnames = []
self._cnames = []
self._pguess = []
self._constants = []
self._globals.update(kwargs)
self._f_raw = f
self._bg_raw = bg
... | Sets the function(s) used to describe the data.
Parameters
----------
f=['a*x*cos(b*x)+c', 'a*x+c']
This can be a string function, a defined function
my_function(x,a,b), or a list of some combination
of these two types of objects. The length of such
... |
373,502 | def _request(self, method, path, data=None, reestablish_session=True):
if path.startswith("http"):
url = path
else:
url = self._format_path(path)
headers = {"Content-Type": "application/json"}
if self._user_agent:
headers[] = self._user_age... | Perform HTTP request for REST API. |
373,503 | def encode_timestamp(timestamp: hints.Buffer) -> str:
length = len(timestamp)
if length != 6:
raise ValueError(.format(length))
encoding = ENCODING
return \
encoding[(timestamp[0] & 224) >> 5] + \
encoding[timestamp[0] & 31] + \
encoding[(timestamp[1] & 248) >> 3] ... | Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the first 6 bytes of a ULID, which
are a timestamp in milliseconds.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifically and is n... |
373,504 | def expectScreen(self, filename, maxrms=0):
log.debug(, filename)
return self._expectFramebuffer(filename, 0, 0, maxrms) | Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image |
373,505 | def setSubTitle(self, title):
self._subTitleLabel.setText(title)
self._subTitleLabel.adjustSize()
self.adjustMargins() | Sets the sub-title for this page to the inputed title.
:param title | <str> |
373,506 | def send(self, message_id, args=[], kwargs={}):
self._logger.debug(.format(message_id, self.id))
self._driver._add_event(
event_id=message_id, args=args, kwargs=kwargs, stm=self) | Send a message to this state machine.
To send a message to a state machine by its name, use
`stmpy.Driver.send` instead. |
373,507 | def is_feasible(self, solution):
newvars = solution.new.keys()
for newvar in newvars:
for c in self._constraints_for_var.get(newvar, []):
values = c.extract_values(solution, use_defaults=True)
if not c(*values):
return False
... | Returns True if the given solution's derivatives may have potential
valid, complete solutions. |
373,508 | def resize(image, target_size, **kwargs):
if isinstance(target_size, int):
target_size = (target_size, target_size)
if not isinstance(target_size, (list, tuple, np.ndarray)):
message = (
"`target_size` should be a single number (width) or a list"
"/tuple/ndarray (w... | Resize an ndarray image of rank 3 or 4.
target_size can be a tuple `(width, height)` or scalar `width`. |
373,509 | def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None,
tags=None, region=None, key=None, keyid=None, profile=None):
dhcp-a0bl34pp
if name:
log.warning(
)
dhcp_options_name = name
return resource_exists(, name=dhcp_option... | Check if a dhcp option exists.
Returns True if the dhcp option exists; Returns False otherwise.
CLI Example:
.. code-block:: bash
salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' |
373,510 | def preprocess_dict(d):
out_env = {}
for k, v in d.items():
if not type(v) in PREPROCESSORS:
raise KeyError(.format(type(v)))
out_env[k] = PREPROCESSORS[type(v)](v)
return out_env | Preprocess a dict to be used as environment variables.
:param d: dict to be processed |
373,511 | def signalflow(self, token, endpoint=None, timeout=None, compress=None):
from . import signalflow
compress = compress if compress is not None else self._compress
return signalflow.SignalFlowClient(
token=token,
endpoint=endpoint or self._stream_endpoint,
... | Obtain a SignalFlow API client. |
373,512 | def _ast_option_group_to_code(self, option_group, **kwargs):
lines = ["option("]
lines.extend(self._indent(self._ast_to_code(option_group.expression)))
lines.append(")")
return lines | Convert an AST option group to python source code. |
373,513 | def resizeToContents(self):
if self.count():
item = self.item(self.count() - 1)
rect = self.visualItemRect(item)
height = rect.bottom() + 8
height = max(28, height)
self.setFixedHeight(height)
else:
self.setFixedHe... | Resizes the list widget to fit its contents vertically. |
373,514 | def contigs_to_positions(contigs, binning=10000):
positions = np.zeros_like(contigs)
index = 0
for _, chunk in itertools.groubpy(contigs):
l = len(chunk)
positions[index : index + l] = np.arange(list(chunk)) * binning
index += l
return positions | Build positions from contig labels
From a list of contig labels and a binning parameter,
build a list of positions that's essentially a
concatenation of linspaces with step equal to the
binning.
Parameters
----------
contigs : list or array_like
The list of contig labels, must be s... |
373,515 | def logical_chassis_fwdl_sanity_input_cluster_options_auto_activate_auto_activate(self, **kwargs):
config = ET.Element("config")
logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity")
config = logical_chassis_fwdl_sanity
input = ET.SubElement(logical_chassis_fwd... | Auto Generated Code |
373,516 | def _sample_orthonormal_to(mu):
v = np.random.randn(mu.shape[0])
proj_mu_v = mu * np.dot(mu, v) / np.linalg.norm(mu)
orthto = v - proj_mu_v
return orthto / np.linalg.norm(orthto) | Sample point on sphere orthogonal to mu. |
373,517 | def getVersionFromArchiveId(git_archive_id=):
if not git_archive_id.startswith():
match = re.search(r, git_archive_id)
if match:
return gitDescribeToPep440(match.group(1))
tstamp = git_archive_id.strip().split()[0]
d = d... | Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX timestamp
%d: ref names, like the --decorate option of git-l... |
373,518 | def normalize(text, mode=, ignore=):
text = text.replace(, ).replace(, )
text = text.replace("’", "”"“``―-‐-˗-֊-‐-‑-‒-–-⁃-⁻-₋-−-﹣ー-ー—ー―ー━ー─ー')
return unicodedata.normalize(mode, text) | Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana,
Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII
and DIGIT.
Additionally, Full-width wave dash (〜) etc. are normalized
Parameters
----------
text : str
Source string.
mode : str
Unicode... |
373,519 | def list_cubes(self):
for file_name in os.listdir(self.directory):
if in file_name:
name, ext = file_name.rsplit(, 1)
if ext.lower() == :
yield name | List all available JSON files. |
373,520 | def _sm_to_pain(self, *args, **kwargs):
_logger.info("Starting chaos for blockade %s" % self._blockade_name)
self._do_blockade_event()
millisec = random.randint(self._run_min_time, self._run_max_time)
self._timer = threading.Timer(millisec / 1000.0, self.event_timeout)
... | Start the blockade event |
373,521 | def field_exists(self, well_x, well_y, field_x, field_y):
"Check if field exists ScanFieldArray."
return self.field(well_x, well_y, field_x, field_y) != None | Check if field exists ScanFieldArray. |
373,522 | def _get_underlying_data(self, instance):
self._touch(instance)
return self.data.get(instance, None) | Return data from raw data store, rather than overridden
__get__ methods. Should NOT be overwritten. |
373,523 | def ssh(cmd=):
with settings(warn_only=True):
local( % (
env.key_filename, env.user, env.host, cmd)) | SSH into the server(s) (sequentially if more than one)
Args:
cmd (str) ='': Command to run on the server |
373,524 | def string(value,
allow_empty = False,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError( % value)
elif not value... | Validate that ``value`` is a valid string.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator... |
373,525 | def add(ctx, alias, mapping, backend):
if not backend:
backends_list = ctx.obj[].get_backends()
if len(backends_list) > 1:
raise click.UsageError(
"You're using more than 1 backend. Please set the backend to "
"add the alias to with the --backend opti... | Add a new alias to your configuration file. |
373,526 | def login(self, verify_code=):
url =
payload = {
: self.__username,
: self.__password,
: verify_code,
: ,
}
headers = {
: ,
: ,
: self.__cookies,
}
r = requests.post(url, data=pa... | 登录微信公众平台
注意在实例化 ``WechatExt`` 的时候,如果没有传入 ``token`` 及 ``cookies`` ,将会自动调用该方法,无需手动调用
当且仅当捕获到 ``NeedLoginError`` 异常时才需要调用此方法进行登录重试
:param verify_code: 验证码, 不传入则为无验证码
:raises LoginVerifyCodeError: 需要验证码或验证码出错,该异常为 ``LoginError`` 的子类
:raises LoginError: 登录出错异常,异常内容为微信服务器响应的内容,可作为日志记录下... |
373,527 | def fit(self, X, y=None, **kwargs):
if y is not None:
self.classes_ = np.unique(y)
elif y is None and self.labels is not None:
self.classes_ = np.array([self.labels[0]])
else:
self.classes_ = np.array([self.NULL_CLASS])
self.indexed... | The fit method is the primary drawing input for the dispersion
visualization.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
that yields a list of documents that contain a list of
words in the ord... |
373,528 | def pypi():
if query_yes_no():
print(cyan())
execute(clean)
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
highest_minor = _highest_minor(latest_pythons)
python = flo()
print(cyan())
_local_needs_pythons(flo(... | Build package and upload to pypi. |
373,529 | def verify_docker_image_sha(chain, link):
cot = link.cot
task = link.task
errors = []
if isinstance(task[].get(), dict):
docker_image_task_id = task[][][][]
log.debug("Verifying {} {} against docker-image {}".format(
link.name, link.task_id, docker_image_task_i... | Verify that built docker shas match the artifact.
Args:
chain (ChainOfTrust): the chain we're operating on.
link (LinkOfTrust): the task link we're checking.
Raises:
CoTError: on failure. |
373,530 | def write_to_file(self, file_path=, date=(datetime.date.today()),
organization=):
with open(file_path, ) as out:
out.write()
sorted_stargazers = sorted(self.stargazers)
for star in sorted_stargazers:
out.write(star + + str(self.stargazers[sta... | Writes stargazers data to file. |
373,531 | def is_text(bytesio):
text_chars = (
bytearray([7, 8, 9, 10, 11, 12, 13, 27]) +
bytearray(range(0x20, 0x7F)) +
bytearray(range(0x80, 0X100))
)
return not bool(bytesio.read(1024).translate(None, text_chars)) | Return whether the first KB of contents seems to be binary.
This is roughly based on libmagic's binary/text detection:
https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228 |
373,532 | def load(self, file_key):
var = self.sd.select(file_key)
data = xr.DataArray(from_sds(var, chunks=CHUNK_SIZE),
dims=[, ]).astype(np.float32)
data = data.where(data != var._FillValue)
try:
data = data * np.float32(var.scale_factor)
... | Load the data. |
373,533 | def from_url(cls, url):
parsed_url = urllib.parse.urlparse(url)
kwargs = dict(urllib.parse.parse_qsl(parsed_url.query))
cache_class = Cache.get_scheme_class(parsed_url.scheme)
if parsed_url.path:
kwargs.update(cache_class.parse_uri_path(parsed_url.path))
if... | Given a resource uri, return an instance of that cache initialized with the given
parameters. An example usage:
>>> from aiocache import Cache
>>> Cache.from_url('memory://')
<aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00>
a more advanced usage using querypar... |
373,534 | def draw_on_image(self, image,
color=(0, 255, 0), color_lines=None, color_points=None,
alpha=1.0, alpha_lines=None, alpha_points=None,
size=1, size_lines=None, size_points=None,
antialiased=True,
raise_if_out_o... | Draw all line strings onto a given image.
Parameters
----------
image : ndarray
The `(H,W,C)` `uint8` image onto which to draw the line strings.
color : iterable of int, optional
Color to use as RGB, i.e. three values.
The color of the lines and poin... |
373,535 | def _get_plugin_module_paths(self, plugin_dir):
filepaths = [
fp for fp in glob.glob(.format(plugin_dir), recursive=True)
if not fp.endswith()
]
rel_paths = [re.sub(plugin_dir.rstrip() + , , fp) for fp in filepaths]
module_paths = [rp.replace(, ).replace(... | Return a list of every module in `plugin_dir`. |
373,536 | def check_learns_zero_output_rnn(model, sgd, X, Y, initial_hidden=None):
outputs, get_dX = model.begin_update(X, initial_hidden)
Yh, h_n = outputs
tupleDy = (Yh - Y, h_n)
dX = get_dX(tupleDy, sgd=sgd)
prev = numpy.abs(Yh.sum())
print(prev)
for i in range(1000):
outputs, get_dX =... | Check we can learn to output a zero vector |
373,537 | def uri(self, value):
jsonpointer.set_pointer(self.record, self.pointer, value) | Set new uri value in record.
It will not change the location of the underlying file! |
373,538 | def A(g,i):
g1 = g&(2**i)
if i:
n = Awidth(i)
An = A(g,i-1)
if g1:
return An<<n | An
else:
return int(*n,2)<<n | An
else:
if g1:
return int(,2)
else:
return int(,2) | recursively constructs A line for g; i = len(g)-1 |
373,539 | def close(self):
for tif in self._files.values():
tif.filehandle.close()
self._files = {} | Close open file handle(s). |
373,540 | def _set_bottomMargin(self, value):
diff = value - self.bottomMargin
self.moveBy((0, diff))
self.height += diff | value will be an int or float.
Subclasses may override this method. |
373,541 | def clear_high_level_pars(self):
for val in [, , , , , , , ]:
COMMAND = % (val)
exec(COMMAND)
if self.ie_open:
for val in [, , , , , , , ]:
COMMAND = % (val)
exec(COMMAND)
self.set_mean_stats_color() | clears all high level pars display boxes |
373,542 | def serialize_instance(instance):
attr_count = 0
metaclass = xtuml.get_metaclass(instance)
s = % metaclass.kind
for name, ty in metaclass.attributes:
value = getattr(instance, name)
s +=
s += serialize_value(value, ty)
attr_count += 1
if attr_... | Serialize an *instance* from a metamodel. |
373,543 | def set_form_widgets_attrs(form, attrs):
for _, field in form.fields.items():
attrs_ = dict(attrs)
for name, val in attrs.items():
if hasattr(val, ):
attrs_[name] = val(field)
field.widget.attrs = field.widget.build_attrs(attrs_) | Applies a given HTML attributes to each field widget of a given form.
Example:
set_form_widgets_attrs(my_form, {'class': 'clickable'}) |
373,544 | def create_unique_transfer_operation_id(src_ase, dst_ase):
return .join(
(src_ase._client.primary_endpoint, src_ase.path,
dst_ase._client.primary_endpoint, dst_ase.path)
) | Create a unique transfer operation id
:param blobxfer.models.azure.StorageEntity src_ase: src storage entity
:param blobxfer.models.azure.StorageEntity dst_ase: dst storage entity
:rtype: str
:return: unique transfer id |
373,545 | def dyn_attr(self, dev_list):
for dev in dev_list:
init_dyn_attrs = getattr(dev,
"initialize_dynamic_attributes",
None)
if init_dyn_attrs and callable(init_dyn_attrs):
try:
... | Invoked to create dynamic attributes for the given devices.
Default implementation calls
:meth:`TT.initialize_dynamic_attributes` for each device
:param dev_list: list of devices
:type dev_list: :class:`tango.DeviceImpl` |
373,546 | def get_parcel(resource_root, product, version, cluster_name="default"):
return _get_parcel(resource_root, PARCEL_PATH % (cluster_name, product, version)) | Lookup a parcel by name
@param resource_root: The root Resource object.
@param product: Parcel product name
@param version: Parcel version
@param cluster_name: Cluster name
@return: An ApiService object |
373,547 | def LdKL_dot(self, v, v1=None):
self._init_svd()
def dot(a, b):
r = tensordot(a, b, axes=([1], [0]))
if a.ndim > b.ndim:
return r.transpose([0, 2, 1])
return r
Lh = self.Lh
V = unvec(v, (self.Lx.shape[0], -1) + v.shape[1:])
... | Implements L(∂K)Lᵀv.
The array v can have one or two dimensions and the first dimension has to have
size n⋅p.
Let vec(V) = v. We have
L(∂K)Lᵀ⋅v = ((Lₕ∂C₀Lₕᵀ) ⊗ (LₓGGᵀLₓᵀ))vec(V) = vec(LₓGGᵀLₓᵀVLₕ∂C₀Lₕᵀ),
when the derivative is over the parameters of C₀. Similarly,
... |
373,548 | def make_channel(name, samples, data=None, verbose=False):
if verbose:
llog = log[]
llog.info("creating channel {0}".format(name))
chan = Channel(.format(name))
chan.SetStatErrorConfig(0.05, "Poisson")
if data is not None:
if verbose:
llog.info("setting dat... | Create a Channel from a list of Samples |
373,549 | def OpenEnumerateInstancePaths(self, ClassName, namespace=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=None, **extra):
exc... | Open an enumeration session to enumerate the instance paths of
instances of a class (including instances of its subclasses) in
a namespace.
*New in pywbem 0.9.*
This method performs the OpenEnumerateInstancePaths operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a... |
373,550 | def move_right(self):
self.at(ardrone.at.pcmd, True, self.speed, 0, 0, 0) | Make the drone move right. |
373,551 | def _init_hex(self, hexval: str) -> None:
self.hexval = hex2termhex(fix_hex(hexval))
self.code = hex2term(self.hexval)
self.rgb = hex2rgb(self.hexval) | Initialize from a hex value string. |
373,552 | def separated(p, sep, mint, maxt=None, end=None):
maxt = maxt if maxt else mint
@Parser
def sep_parser(text, index):
cnt, values, res = 0, Value.success(index, []), None
while cnt < maxt:
if end in [False, None] and cnt > 0:
res = sep(text, index)
... | Repeat a parser `p` separated by `s` between `mint` and `maxt` times.
When `end` is None, a trailing separator is optional.
When `end` is True, a trailing separator is required.
When `end` is False, a trailing separator is not allowed.
MATCHES AS MUCH AS POSSIBLE.
Return list of values returned by `... |
373,553 | def get_submission_filenames(self, tournament=None, round_num=None):
query =
data = self.raw_query(query, authorization=True)[][]
filenames = [{"round_num": item[][],
"tournament": item[][],
"filename": item[]}
for item ... | Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames (`dict`)
Each filenames in the list as the following str... |
373,554 | def window_size(self):
the_size = self.app_window.baseSize()
return the_size.width(), the_size.height() | returns render window size |
373,555 | def Trim(lst, limit):
limit = max(0, limit)
clipping = lst[limit:]
del lst[limit:]
return clipping | Trims a given list so that it is not longer than given limit.
Args:
lst: A list to trim.
limit: A maximum number of elements in the list after trimming.
Returns:
A suffix of the input list that was trimmed. |
373,556 | def validate_username(username):
if not username.islower():
raise UsernameInvalid(six.u())
if len(username) < 2:
raise UsernameInvalid(six.u())
if not username_re.search(username):
raise UsernameInvalid(settings.USERNAME_VALIDATION_ERROR_MSG)
return username | Validate the new username. If the username is invalid, raises
:py:exc:`UsernameInvalid`.
:param username: Username to validate. |
373,557 | def switch(self):
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
.format(
self.idx[idx], t)) | Switch if time for eAgc has come |
373,558 | def get_object(model, meteor_id, *args, **kwargs):
meta = model._meta
if isinstance(meta.pk, AleaIdField):
return model.objects.filter(*args, **kwargs).get(pk=meteor_id)
alea_unique_fields = [
field
for field in meta.local_fields
if isinstance(field, AleaI... | Return an object for the given meteor_id. |
373,559 | def _send_request(self, path, data, method):
response_body = self._transport.send_request(path, data, method)
root = etree.fromstring(response_body)
return root | Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
:param data: The params to send along with th... |
373,560 | def add_tags(self):
if self.tags is None:
self.tags = VCFLACDict()
self.metadata_blocks.append(self.tags)
else:
raise FLACVorbisError("a Vorbis comment already exists") | Add a Vorbis comment block to the file. |
373,561 | def filter(objects, Type=None, min=-1, max=-1):
res = []
if min > max:
raise ValueError("minimum must be smaller than maximum")
if Type is not None:
res = [o for o in objects if isinstance(o, Type)]
if min > -1:
res = [o for o in res if _getsizeof(o) < min]
if max > -1:... | Filter objects.
The filter can be by type, minimum size, and/or maximum size.
Keyword arguments:
Type -- object type to filter by
min -- minimum object size
max -- maximum object size |
373,562 | async def query_presence(self, query_presence_request):
response = hangouts_pb2.QueryPresenceResponse()
await self._pb_request(,
query_presence_request, response)
return response | Return presence status for a list of users. |
373,563 | def HashFilePath(self, path, byte_count):
with open(path, "rb") as fd:
self.HashFile(fd, byte_count) | Updates underlying hashers with file on a given path.
Args:
path: A path to the file that is going to be fed to the hashers.
byte_count: A maximum numbers of bytes that are going to be processed. |
373,564 | def queue_resize(self):
self._children_resize_queued = True
parent = getattr(self, "parent", None)
if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"):
parent.queue_resize() | request the element to re-check it's child sprite sizes |
373,565 | def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, keep_logs=False, **kwargs):
self.lock()
jobs = self.get_jobs(job_ids)
if new_command is not None:
if len(jobs) == 1:
jobs[0].set_command_line(new_command)
else:
logger.warn(... | Re-submit jobs automatically |
373,566 | def hdr(data, filename):
hdrobj = data if isinstance(data, HDRobject) else HDRobject(data)
hdrobj.write(filename) | write ENVI header files
Parameters
----------
data: str or dict
the file or dictionary to get the info from
filename: str
the HDR file to write
Returns
------- |
373,567 | def init(self, xml, port, server=None,
server2=None, port2=None,
role=0, exp_uid=None, episode=0,
action_filter=None, resync=0, step_options=0, action_space=None):
if action_filter is None:
action_filter = {"move", "turn", "use", "attack"}
if ... | Initialize a Malmo environment.
xml - the mission xml.
port - the MalmoEnv service's port.
server - the MalmoEnv service address. Default is localhost.
server2 - the MalmoEnv service address for given role if not 0.
port2 - the MalmoEnv service port for given ... |
373,568 | def coupling_to_arc(coupling_map:List[List[int]]) -> Architecture:
coupling = CouplingMap(couplinglist=coupling_map)
return DirectedGraph(coupling_map,coupling.size()) | Produces a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` corresponding to a (directed) coupling map,
stating the pairs of qubits between which two-qubit interactions
(e.g. CXs) can be applied.
:param coupling_map: Pairs of indices where each pair [control, target]
permits the use of... |
373,569 | def _get_stddevs(self, C, rup, shape, stddev_types):
weight = self._compute_weight_std(C, rup.mag)
std_intra = weight * C["sd1"] * np.ones(shape)
std_inter = weight * C["sd2"] * np.ones(shape)
stddevs = []
for stddev_type in stddev_types:
ass... | Return standard deviations as defined in p. 971. |
373,570 | def predict_mu(self, X):
if not self._is_fitted:
raise AttributeError()
X = check_X(X, n_feats=self.statistics_[],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
lp = self._linear_predict... | preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
containing expected values under the mo... |
373,571 | def save_auxiliary_files(self, layer, destination):
enable_busy_cursor()
auxiliary_files = [, ]
for auxiliary_file in auxiliary_files:
source_basename = os.path.splitext(layer.source())[0]
source_file = "%s.%s" % (source_basename, auxiliary_file)
... | Save auxiliary files when using the 'save as' function.
If some auxiliary files (.xml, .json) exist, this function will
copy them when the 'save as' function is used on the layer.
:param layer: The layer which has been saved as.
:type layer: QgsMapLayer
:param destination: The... |
373,572 | def nnz_obs(self):
nnz = 0
for w in self.observation_data.weight:
if w > 0.0:
nnz += 1
return nnz | get the number of non-zero weighted observations
Returns
-------
nnz_obs : int
the number of non-zeros weighted observations |
373,573 | def parallel_evaluation_mp(candidates, args):
import time
import multiprocessing
logger = args[].logger
try:
evaluator = args[]
except KeyError:
logger.error(mp_evaluator\)
raise
try:
nprocs = args[]
except KeyError:
nprocs = multiprocessing... | Evaluate the candidates in parallel using ``multiprocessing``.
This function allows parallel evaluation of candidate solutions.
It uses the standard multiprocessing library to accomplish the
parallelization. The function assigns the evaluation of each
candidate to its own job, all of which are then di... |
373,574 | def batch_filter(self, zs, Fs=None, Qs=None, Hs=None,
Rs=None, Bs=None, us=None, update_first=False,
saver=None):
n = np.size(zs, 0)
if Fs is None:
Fs = [self.F] * n
if Qs is None:
Qs = [self.Q] * n
if H... | Batch processes a sequences of measurements.
Parameters
----------
zs : list-like
list of measurements at each time step `self.dt`. Missing
measurements must be represented by `None`.
Fs : None, list-like, default=None
optional value or list of valu... |
373,575 | def getSiblings(self, textId, subreference):
textId = "{}:{}".format(textId, subreference)
return self.getPrevNextUrn(urn=textId) | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:param reference: CapitainsCtsPassage Reference
:return: GetPrevNextUrn request response from the endpoint |
373,576 | def acknowledge_host_problem(self, host, sticky, notify, author, comment):
notification_period = None
if getattr(host, , None) is not None:
notification_period = self.daemon.timeperiods[host.notification_period]
host.acknowledge_problem(notification_period, self.hosts, self.... | Acknowledge a host problem
Format of the line that triggers function call::
ACKNOWLEDGE_HOST_PROBLEM;<host_name>;<sticky>;<notify>;<persistent:obsolete>;<author>;
<comment>
:param host: host to acknowledge the problem
:type host: alignak.objects.host.Host
:param sticky:... |
373,577 | def create_url(urlbase, urlargd, escape_urlargd=True, urlhash=None):
separator =
output = urlbase
if urlargd:
output +=
if escape_urlargd:
arguments = [escape(quote(str(key)), quote=True) + +
escape(quote(str(urlargd[key])), quote=True)
... | Creates a W3C compliant URL. Output will look like this:
'urlbase?param1=value1&param2=value2'
@param urlbase: base url (e.g. config.CFG_SITE_URL/search)
@param urlargd: dictionary of parameters. (e.g. p={'recid':3, 'of'='hb'}
@param escape_urlargd: boolean indicating if the function should escape
... |
373,578 | def is_python_binding_installed_on_pip(self):
pip_version = self._get_pip_version()
Log.debug(.format(pip_version))
pip_major_version = int(pip_version.split()[0])
installed = False
if pip_major_version >= 9:
json_obj = self._get_pip_list_j... | Check if the Python binding has already installed. |
373,579 | def assertFileSizeLess(self, filename, size, msg=None):
s size is not less than ``size`` as
determined by the operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided, the :mod:`marbles.mixins` or
... | Fail if ``filename``'s size is not less than ``size`` as
determined by the '<' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` standard mess... |
373,580 | def _printf(self, *args, **kwargs):
if self._stream and not kwargs.get():
kwargs[] = self._stream
_printf(*args, **kwargs) | Print to configured stream if any is specified and the file argument
is not already set for this specific call. |
373,581 | def _get_deploy_image_params(data_holder, host_info, vm_name):
image_params = OvfImageParams()
if hasattr(data_holder, ) and data_holder.vcenter_image_arguments:
image_params.user_arguments = data_holder.vcenter_image_arguments
if hasattr(data_holder, ) and data_holder.vm_lo... | :type data_holder: models.vCenterVMFromImageResourceModel.vCenterVMFromImageResourceModel |
373,582 | def _asciify_dict(data):
ret = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = _remove_accents(key)
key = key.encode()
if isinstance(value, unicode):
value = _remove_accents(value)
value = value.encode()
... | Ascii-fies dict keys and values |
373,583 | def do_ranges_intersect(begin, end, old_begin, old_end):
return (old_begin <= begin < old_end) or \
(old_begin < end <= old_end) or \
(begin <= old_begin < end) or \
(begin < old_end <= end) | Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_begin: int
@param old_begin: Start address of the second range.
... |
373,584 | def merge_and_fit(self, segment):
self.points = sort_segment_points(self.points, segment.points)
return self | Merges another segment with this one, ordering the points based on a
distance heuristic
Args:
segment (:obj:`Segment`): Segment to merge with
Returns:
:obj:`Segment`: self |
373,585 | def fill_subparser(subparser):
subparser.add_argument(
, type=str, required=True,
help=("The YouTube ID of the video from which to extract audio, "
"usually an 11-character string.")
)
subparser.add_argument(
, type=int, default=1,
help=("The number of audi... | Sets up a subparser to convert YouTube audio files.
Adds the compulsory `--youtube-id` flag as well as the optional
`sample` and `channels` flags.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `youtube_audio` command. |
373,586 | def open(self, name, flags, preferred_fd=None):
if len(name) == 0:
return None
if type(name) is str:
name = name.encode()
if self.uid != 0 and name.startswith(b):
return None
else:
simfile = SimFile(nam... | Open a symbolic file. Basically open(2).
:param name: Path of the symbolic file, as a string or bytes.
:type name: string or bytes
:param flags: File operation flags, a bitfield of constants from open(2), as an AST
:param preferred_fd: Assign this fd ... |
373,587 | def sub_path(self):
try:
return os.path.join(*(self._local_parts()))
except TypeError as e:
raise TypeError(
"Path failed for partition {} : {}".format(
self.name,
e.message)) | The path of the partition source, excluding the bundle path parts.
Includes the revision. |
373,588 | def _sortkey(self, key=, language=):
if key == :
return self.uri
else:
l = label(self.labels, language, key == )
return l.label.lower() if l else | Provide a single sortkey for this conceptscheme.
:param string key: Either `uri`, `label` or `sortlabel`.
:param string language: The preferred language to receive the label in
if key is `label` or `sortlabel`. This should be a valid IANA language tag.
:rtype: :class:`str` |
373,589 | def _bundle_exists(self, path):
for attached_bundle in self._attached_bundles:
if path == attached_bundle.path:
return True
return False | Checks if a bundle exists at the provided path
:param path: Bundle path
:return: bool |
373,590 | def QueryUsers(self, database_link, query, options=None):
if options is None:
options = {}
path = base.GetPathFromLink(database_link, )
database_id = base.GetResourceIdOrFullNameFromLink(database_link)
def fetch_fn(options):
return self.__QueryFeed(path,... | Queries users in a database.
:param str database_link:
The link to the database.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of Users.
:rtype:
query_iterable.Que... |
373,591 | def from_environment_or_defaults(cls, environment=None):
if environment is None:
environment = os.environ
run_id = environment.get(env.RUN_ID)
resume = environment.get(env.RESUME)
storage_id = environment.get(env.RUN_STORAGE_ID)
mode = environment.get(env.MOD... | Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run directory comes from WANDB_RUN_DIR or is generated from the run ID.
... |
373,592 | def clean(tf_matrix,
tf_matrix_gene_names,
target_gene_name):
if target_gene_name not in tf_matrix_gene_names:
clean_tf_matrix = tf_matrix
else:
clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1)
clean_tf_names = [tf for tf in t... | :param tf_matrix: numpy array. The full transcription factor matrix.
:param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns.
:param target_gene_name: the target gene to remove from the tf_matrix and tf_names.
:return: a tuple of (matrix, names) equal... |
373,593 | def runExperiment(args, model=None):
opt = _parseCommandLineOptions(args)
model = _runExperimentImpl(opt, model)
return model | Run a single OPF experiment.
.. note:: The caller is responsible for initializing python logging before
calling this function (e.g., import :mod:`nupic.support`;
:meth:`nupic.support.initLogging`)
See also: :meth:`.initExperimentPrng`.
:param args: (string) Experiment command-line args list. Too see ... |
373,594 | def debug(self, msg, indent=0, **kwargs):
return self.logger.debug(self._indent(msg, indent), **kwargs) | invoke ``self.logger.debug`` |
373,595 | def shift (*args):
if len(args) > 2:
raise ValueError("shift() takes 0, 1 or 2 arguments.")
n = 1
l = ayrton.runner.globals[]
logger.debug2("%s(%d)", args, len(args))
if len(args) == 1:
value = args[0]
logger.debug2(type(value))
if isinstance(value, int):
... | `shift()` returns the leftmost element of `argv`.
`shitf(integer)` return the `integer` leftmost elements of `argv` as a list.
`shift(iterable)` and `shift(iterable, integer)` operate over `iterable`. |
373,596 | def decode_to_unicode(content):
if content and not isinstance(content, str):
try:
return content.decode("ISO-8859-1")
except UnicodeEncodeError:
return content
return content | decode ISO-8859-1 to unicode, when using sf api |
373,597 | def _render_mail(self, rebuild, success, auto_canceled, manual_canceled):
subject_template =
body_template = .join([
,
,
,
,
])
log_files = self._fetch_log_files()
return (subject_template ... | Render and return subject and body of the mail to send. |
373,598 | async def _discard(self, path, *, recurse=None, separator=None, cas=None):
path = "/v1/kv/%s" % path
response = await self._api.delete(path, params={
"cas": cas,
"recurse": recurse,
"separator": separator
})
return response | Deletes the Key |
373,599 | def normalize_bbox(bbox, rows, cols):
if rows == 0:
raise ValueError()
if cols == 0:
raise ValueError()
x_min, y_min, x_max, y_max = bbox[:4]
normalized_bbox = [x_min / cols, y_min / rows, x_max / cols, y_max / rows]
return normalized_bbox + list(bbox[4:]) | Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.