Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,800 | def get_inertia(self):
def calculate_inertia_tensor(molecule):
masses = molecule.loc[:, ].values
pos = molecule.loc[:, [, , ]].values
inertia = np.sum(
masses[:, None, None]
* ((pos**2).sum(axis=1)[:, None, None]
* n... | Calculate the inertia tensor and transforms along
rotation axes.
This function calculates the inertia tensor and returns
a 4-tuple.
The unit is ``amu * length-unit-of-xyz-file**2``
Args:
None
Returns:
dict: The returned dictionary has four poss... |
345,801 | def notify_slack_channel(self):
message = get_template(template_file=, info=self.info)
if self.settings[][][]:
post_slack_message(
message=message,
channel=self.settings[][][],
username=,
icon_emoji=) | Post message to a defined Slack channel. |
345,802 | def latex_visit_inheritance_diagram(self, node):
graph = node[]
graph_hash = get_graph_hash(node)
name = % graph_hash
dotcode = graph.generate_dot(name, env=self.builder.env,
graph_attrs={: })
render_dot_latex(self, node, dotcode, {}, )
raise nodes.S... | Output the graph for LaTeX. This will insert a PDF. |
345,803 | def checkLimits(self, row, value):
param = self._parameters[row]
components = param[]
if len(components) == 0:
return False
ptype = param[]
mins = []
maxs = []
for comp in components:
try:
deta... | Check that *value* is within the minimum and maximum allowable
range for the parameter at index *row*
:param row: the ith parameter number
:type row: int
:param value: the candidate value to for start or stop fields
:returns: bool -- True if *value* within range |
345,804 | def dft_postprocess_data(arr, real_grid, recip_grid, shift, axes,
interp, sign=, op=, out=None):
arr = np.asarray(arr)
if is_real_floating_dtype(arr.dtype):
arr = arr.astype(complex_dtype(arr.dtype))
elif not is_complex_floating_dtype(arr.dtype):
raise ValueErro... | Post-process the Fourier-space data after DFT.
This function multiplies the given data with the separable
function::
q(xi) = exp(+- 1j * dot(x[0], xi)) * s * phi_hat(xi_bar)
where ``x[0]`` and ``s`` are the minimum point and the stride of
the real-space grid, respectively, and ``phi_hat(xi_ba... |
345,805 | def recv_file_from_remote(dev, src_filename, dst_file, filesize):
bytes_remaining = filesize
if not HAS_BUFFER:
bytes_remaining *= 2
buf_size = BUFFER_SIZE
write_buf = bytearray(buf_size)
while bytes_remaining > 0:
read_size = min(bytes_remaining, buf_size)
buf_remaini... | Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with send_file_to_host. |
345,806 | def split(self, frac):
from .. import preprocess
split_obj = getattr(preprocess, )(fraction=frac)
return split_obj.transform(self) | Split the DataFrame into two DataFrames with certain ratio.
:param frac: Split ratio
:type frac: float
:return: two split DataFrame objects
:rtype: list[DataFrame] |
345,807 | def _interpolate(self, factor, minInfo, maxInfo, round=True, suppressError=True):
minInfo = minInfo._toMathInfo()
maxInfo = maxInfo._toMathInfo()
result = interpolate(minInfo, maxInfo, factor)
if result is None and not suppressError:
raise FontPartsError(("Info from ... | Subclasses may override this method. |
345,808 | def get_pending_users_queryset(self, search_keyword, customer_uuid):
queryset = PendingEnterpriseCustomerUser.objects.filter(
enterprise_customer__uuid=customer_uuid
)
if search_keyword is not None:
queryset = queryset.filter(user_email__icontains=search_keyword... | Get the list of PendingEnterpriseCustomerUsers we want to render.
Args:
search_keyword (str): The keyword to search for in pending users' email addresses.
customer_uuid (str): A unique identifier to filter down to only pending users
linked to a particular EnterpriseCustomer. |
345,809 | def priority(self, item):
return % max(self.cache[item.pk][0] / self.max_entries, 0.1) | The priority of the item depends of the number of entries published
in the cache divided by the maximum of entries. |
345,810 | def beta_geometric_nbd_model(T, r, alpha, a, b, size=1):
if type(T) in [float, int]:
T = T * np.ones(size)
else:
T = np.asarray(T)
probability_of_post_purchase_death = random.beta(a, b, size=size)
lambda_ = random.gamma(r, scale=1.0 / alpha, size=size)
columns = ["frequency", ... | Generate artificial data according to the BG/NBD model.
See [1] for model details
Parameters
----------
T: array_like
The length of time observing new customers.
r, alpha, a, b: float
Parameters in the model. See [1]_
size: int, optional
The number of customers to gener... |
345,811 | def _write_num_zeros(self)->None:
"Writes the number of zeroes in the gradients to Tensorboard."
gradient_nps = [to_np(x.data) for x in self.gradients]
num_zeros = sum((np.asarray(x) == 0.0).sum() for x in gradient_nps)
self._add_gradient_scalar(, scalar_value=num_zeros) | Writes the number of zeroes in the gradients to Tensorboard. |
345,812 | def eval_file(conn, filename, strip_command=True, **kwargs):
parser_args = {: strip_command}
with open(filename, ) as fp:
return _run(conn, filename, fp.read(), parser_args, **kwargs) | Convenience wrapper around eval() that reads the template from a file
instead.
:type conn: Exscript.protocols.Protocol
:param conn: The connection on which to run the template.
:type filename: string
:param filename: The name of the template file.
:type strip_command: bool
:param strip_c... |
345,813 | def mfbe(a, b):
return 2 * bias(a, b) / (a.mean() + b.mean()) | Returns the mean fractionalized bias error |
345,814 | def _readFile(self, fileName):
with open(fileName, ) as binFile:
b = binFile.read()
return to_ubyte_array(b) | Returns the bytes of the file. |
345,815 | def worker(url_key, property_name, function, function_arguments):
error_msg = None
try:
data = function(*function_arguments)
except Exception as e:
data = []
error_msg = "Error: " + traceback.format_exc().strip()
error_msg += "\n" + str(e.message)
if error... | This function usually runs as process on the background.
It runs ``function(*function_arguments)`` and then stores them in REST API
storage.
Warning:
This function puts data into DB, isntead of returning them.
Args:
url_key (str): Key which will be used for database lookup.
pr... |
345,816 | def _decode_next_layer(self, dict_, length=None):
seek_cur = self._file.tell()
try:
next_ = self._import_next_layer(self._prot, length)
except Exception:
dict_[] = traceback.format_exc(limit=1).strip().split(os.linesep)[-1]
self._file.seek(seek_cur, o... | Decode next layer protocol.
Positional arguments:
dict_ -- dict, info buffer
proto -- str, next layer protocol name
length -- int, valid (not padding) length
Returns:
* dict -- current protocol with packet extracted |
345,817 | def set_global_config(path_dict_or_stream):
path = None
mapping = None
stream = None
global _config_file_path
global _config_cache
if isinstance(path_dict_or_stream, string_types):
path = path_dict_or_stream
if _config_file_path and _config_file_path != path:
r... | Set the global configuration.
Call this from `main()` with a file system path, stream
object, or a dict. Calling it repeatedly with the same path is
safe. Calling it with a different path or repeatedly with a
stream or dict requires an explicit call to :func:`clear_global_config`.
:param path_di... |
345,818 | def kill_process_from_pid_file_on_host(hostname, pid_file=):
status, pid = run_command_on_agent(hostname, .format(pid_file))
status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
if status:
print("Killed pid: {}".format(pid))
run_command_on_agent(hostname, .form... | Retrieves the PID of a process from a pid file on host and kills it.
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pid_file: pid file to use holding the pid number to kill |
345,819 | def index():
classes = []
with app.app_context():
classes = set(current_app.class_references.values())
if _get_acceptable_response_type() == JSON:
meta_data = {}
for cls in classes:
meta_data[cls.endpoint()] = {
: + cls.endpoint(),
: ... | Return information about each type of resource and how it can be
accessed. |
345,820 | def add(self, obj):
if not isinstance(obj, dict):
raise TypeError("Add object should be a dict object")
obj = self.validation(obj)
obj["id"] = self.maxId + 1
obj = self._cast_model(obj)
self.model.db.append(obj)
if not self._batch.enable.is_set():
... | Add a object
Args:
Object: Object will be added
Returns:
Object: Object with id
Raises:
TypeError: If add object is not a dict
MultipleInvalid: If input object is invaild |
345,821 | def _status_line(self, tense=):
action = {: , : }[tense]
line = .format(
label=self.label + if self.label else ,
action=action, num=self.num, bestof=min(self.bestof, self.num))
return line | Text indicating what has been / is being done.
Doctest:
>>> print(Timerit()._status_line(tense='past'))
Timed for: 1 loops, best of 1
>>> print(Timerit()._status_line(tense='present'))
Timing for: 1 loops, best of 1 |
345,822 | def delete_service(resource_root, name, cluster_name="default"):
return call(resource_root.delete,
"%s/%s" % (SERVICES_PATH % (cluster_name,), name),
ApiService) | Delete a service by name
@param resource_root: The root Resource object.
@param name: Service name
@param cluster_name: Cluster name
@return: The deleted ApiService object |
345,823 | def dot_product_unmasked_self_attention_relative_v2(
q, k, v, bias, max_relative_position=None, dropout_rate=0.0,
image_shapes=None, name=None, make_image_summary=True,
dropout_broadcast_dims=None, heads_share_relative_embedding=False,
add_relative_to_values=False):
if not max_relative_position:
... | Calculate relative position-aware dot-product self-attention.
The attention calculation is augmented with learned representations for the
relative position between each element in q and each element in k and v.
Args:
q: a Tensor with shape [batch, heads, length, depth].
k: a Tensor with shape [batch, he... |
345,824 | def fitlin_rscale(xy,uv,verbose=False):
mu = uv[:,0].mean()
mv = uv[:,1].mean()
mx = xy[:,0].mean()
my = xy[:,1].mean()
u = uv[:,0] - mu
v = uv[:,1] - mv
x = xy[:,0] - mx
y = xy[:,1] - my
Sxx = np.dot(x,x)
Syy = np.dot(y,y)
Sux = np.dot(u,x)
Suy = np.dot(u,y)
S... | Performs a linear, orthogonal fit between matched
lists of positions 'xy' (input) and 'uv' (output).
Output: (same as for fit_arrays_general) |
345,825 | def svd(self):
try:
svdPath = self._info.debugs[0].attrib[]
return self._pack.get_file(svdPath)
except (KeyError, IndexError):
return None | ! @brief File-like object for the device's SVD file.
@todo Support multiple cores. |
345,826 | def _OpenFileObject(self, path_spec):
if not path_spec.HasParent():
raise errors.PathSpecError(
)
parent_path_spec = path_spec.parent
file_system = resolver.Resolver.OpenFileSystem(
parent_path_spec, resolver_context=self._resolver_context)
segment_file_path_spe... | Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pysmraw.handle: a file-like object or None.
Raises:
PathSpecError: if the path specification is invalid. |
345,827 | def moderate_view(self, request, object_id, extra_context=None):
opts = self.model._meta
app_label = opts.app_label
view = CommentAdmin(model=Comment, admin_site=self.admin_site)
view.list_filter = ()
view.list_display = (
,
,
,
... | Handles moderate object tool through a somewhat hacky changelist view
whose queryset is altered via CommentAdmin.get_changelist to only list
comments for the object under review. |
345,828 | def setInterrupt(
self, endpoint, buffer_or_len, callback=None, user_data=None,
timeout=0):
if self.__submitted:
raise ValueError()
if self.__doomed:
raise DoomedTransferError()
string_buffer, self.__transfer_py_buffer = create_binary_buff... | Setup transfer for interrupt use.
endpoint
Endpoint to submit transfer to. Defines transfer direction (see
ENDPOINT_OUT and ENDPOINT_IN)).
buffer_or_len
Either a string (when sending data), or expected data length (when
receiving data)
To avoi... |
345,829 | def simulate(protocol_file,
propagate_logs=False,
log_level=) -> List[Mapping[str, Any]]:
stack_logger = logging.getLogger()
stack_logger.propagate = propagate_logs
contents = protocol_file.read()
if opentrons.config.feature_flags.use_protocol_api_v2():
try:
... | Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other
internal server infrastructure) sources.
To simulate an opentrons protocol from other places, pass in a file like
object as... |
345,830 | def post(self, command, output_dir, vars):
if command.simulate:
return
project_path = join(getcwd(), vars[], )
mods = self.get_mods(project_path, vars)
for target, linkfile in self.get_symlinks(project_path, vars,... | Do some tasks after install |
345,831 | def to_binary(value, encoding=):
if not value:
return b
if isinstance(value, six.binary_type):
return value
if isinstance(value, six.text_type):
return value.encode(encoding)
if six.PY3:
return six.binary_type(str(value), encoding)
return six.binary_type(value... | 将 values 转为 bytes,默认编码 utf-8
:param value: 待转换的值
:param encoding: 编码 |
345,832 | def WrapCFTypeInPython(self, obj):
obj_type = self.dll.CFGetTypeID(obj)
if obj_type == self.dll.CFBooleanGetTypeID():
return CFBoolean(obj)
elif obj_type == self.dll.CFNumberGetTypeID():
return CFNumber(obj)
elif obj_type == self.dll.CFStringGetTypeID():
return CFString(obj)
e... | Package a CoreFoundation object in a Python wrapper.
Args:
obj: The CoreFoundation object.
Returns:
One of CFBoolean, CFNumber, CFString, CFDictionary, CFArray.
Raises:
TypeError: If the type is not supported. |
345,833 | def _short_repr(obj):
stringified = pprint.saferepr(obj)
if len(stringified) > 200:
return % (stringified[:200], len(stringified))
return stringified | Helper function returns a truncated repr() of an object. |
345,834 | def read_as_binary(self):
return self.workspace._rest.read_intermediate_dataset_contents_binary(
self.workspace.workspace_id,
self.experiment.experiment_id,
self.node_id,
self.port_name
) | Read and return the dataset contents as binary. |
345,835 | def clear_annot(self):
msgBox = QMessageBox(QMessageBox.Question, ,
)
msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgBox.setDefaultButton(QMessageBox.Yes)
response = msgBox.exec_()
if response == QMessageBox.No:
r... | Action: clear all the annotations (ask for confirmation first). |
345,836 | def write_fits(self, data, outfile, extname="SKYMAP", clobber=True):
hdu_prim = fits.PrimaryHDU()
hdu_hpx = self.make_hdu(data, extname=extname)
hl = [hdu_prim, hdu_hpx]
if self.conv.energy_hdu == :
hdu_energy = self.make_energy_bounds_hdu()
elif self.conv.en... | Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files |
345,837 | def lookup_signum(name):
uname = name.upper()
if (uname.startswith() and hasattr(signal, uname)):
return getattr(signal, uname)
else:
uname = "SIG"+uname
if hasattr(signal, uname):
return getattr(signal, uname)
return None
return | Find the corresponding signal number for 'name'. Return None
if 'name' is invalid. |
345,838 | def expect_err(self, msg) -> E:
if self._is_ok:
raise ValueError(msg)
return cast(E, self._val) | Returns the error value in a :class:`Result`, or raises a
``ValueError`` with the provided message.
Args:
msg: The error message.
Returns:
The error value in the :class:`Result` if it is a
:meth:`Result.Err` value.
Raises:
``ValueError``... |
345,839 | def im_detect(self, im_list, root_dir=None, extension=None, show_timer=False):
test_db = TestDB(im_list, root_dir=root_dir, extension=extension)
test_iter = DetIter(test_db, 1, self.data_shape, self.mean_pixels,
is_train=False)
return self.detect_iter(test_it... | wrapper for detecting multiple images
Parameters:
----------
im_list : list of str
image path or list of image paths
root_dir : str
directory of input images, optional if image path already
has full directory information
extension : str
... |
345,840 | def clear_rules_from_all_proxies(self):
self._queue = []
if self.debug:
print
for service in self.app.get_services():
for instance in self.app.get_service_instances(service):
if self.debug:
print % (service, instance)... | Clear fault injection rules from all known service proxies. |
345,841 | def set_row_stretch(self, row=0, stretch=10):
self._layout.setRowStretch(row, stretch)
return self | Sets the row stretch. Larger numbers mean it will expand more to fill
space. |
345,842 | def parse_operand(string, location, tokens):
mod = " ".join(tokens.get("modifier", ""))
if "immediate" in tokens:
imm = parse_immediate("".join(tokens["immediate"]))
size = modifier_size.get(mod, None)
oprnd = X86ImmediateOperand(imm, size)
if "register" in tokens:
na... | Parse an x86 instruction operand. |
345,843 | def find_nonconsec_values(values, min_=None, max_=None):
if min_ is None:
min_ = values[0]
if max_ is None:
max_ = values[-1]
valx = 0
missing_values = []
for check in range(min_, max_ + 1):
if values[valx] != check:
missing_values.append(check)
... | Determines if a list of values is consecutive (ascending)
Args:
values (list): list of values, sorted and unique
min_(int): minimum value in range defaults min(values)
max_(int): maximum value in range defaults max(values)
Returns:
missing_values: missing values that would make... |
345,844 | def max_paths(self, **kwargs):
afi = kwargs.pop(, )
callback = kwargs.pop(, self._callback)
if afi not in [, ]:
raise AttributeError()
args = dict(rbridge_id=kwargs.pop(, ),
load_sharing_value=kwargs.pop(, ))
max_paths = getattr(self._rbri... | Set BGP max paths property.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
paths (str): Number of paths for BGP ECMP (default: 8).
afi (str): Address f... |
345,845 | def time_to_first_byte(self):
ttfb = []
for page in self.pages:
if page.time_to_first_byte is not None:
ttfb.append(page.time_to_first_byte)
return round(mean(ttfb), self.decimal_precision) | The aggregate time to first byte for all pages. |
345,846 | def action_handler_adapter(handler_cls: type, action_name: str) -> Callable:
if not hasattr(handler_cls(), action_name):
message = "{0} does'nt have attr:{1}".format(handler_cls, action_name)
raise ValueError(message)
def wsgiapp(environ, start_response):
handler = handle... | wraps class to wsgi application dispathing action |
345,847 | def _convert_pix_coords(self):
if self.region_type in [, ]:
coords[-1] = self.coord[-1]
return coords | Convert to pixel coordinates, `regions.PixCoord` |
345,848 | def paginate_request(self, path, method, data=None, **kwargs):
next_page = path
while next_page:
response = self.request(next_page, method, data=data, **kwargs)
if not isinstance(response.get(), list):
next_page = None
yield response[]
... | Handle paginated requests to API
:param str path: API endpoint's path to request
:param str method: HTTP method to use
:param dict data: Data to send (optional)
:return: Response data items (:class:`Generator`)
Cachet pagination is handled and next pages requested on demand.
... |
345,849 | def count_plus(self, uid):
self.set_header("Content-Type", "application/json")
output = {
: 1 if MPost.update_misc(uid, count=1) else 0
}
self.write(json.dumps(output)) | Ajax request, that the view count will plus 1. |
345,850 | def remove(self):
response = self._delete(self._delete_url)
if response.status_code != 204:
raise RuntimeError(.format(self.path)) | Remove this file from the remote storage. |
345,851 | async def handle_request(self, request: Request
) -> typing.Tuple[AsyncGeneratorType, Response]:
callback_result, response = None, None
await self._run_request_middleware(request)
try:
callback_result, response = await request.fetch_callback(sel... | Wrap request with middleware.
:param request:
:return: |
345,852 | def format_from_extension(self, extension):
formats = [name
for name, format in self._formats.items()
if format.get(, None) == extension]
if len(formats) == 0:
return None
elif len(formats) == 2:
raise RuntimeError("Several e... | Find a format from its extension. |
345,853 | def optimizely(parser, token):
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError(" takes no arguments" % bits[0])
return OptimizelyNode() | Optimizely template tag.
Renders Javascript code to set-up A/B testing. You must supply
your Optimizely account number in the ``OPTIMIZELY_ACCOUNT_NUMBER``
setting. |
345,854 | def load_building_sample_data(bd):
number_of_storeys = 6
interstorey_height = 3.4
masses = 40.0e3
bd.interstorey_heights = interstorey_height * np.ones(number_of_storeys)
bd.floor_length = 18.0
bd.floor_width = 16.0
bd.storey_masses = masses * np.ones(number_of_storeys) | Sample data for the Building object
:param bd:
:return: |
345,855 | def set_command_result(result, unpicklable=False):
if result is None:
return
if isinstance(result, basestring):
return result
json = jsonpickle.encode(result, unpicklable=unpicklable)
result_for_output = str(json)
return result_for_output | Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserialized as dictionary |
345,856 | def get(self, rel_path, cb=None):
t be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure.
t have an upstream, then we are done.
return None
stream = self.upstream.get_stream(rel_path, cb=cb)
if not stream:
... | Return the file path referenced but rel_path, or None if
it can't be found. If an upstream is declared, it will try to get the file
from the upstream before declaring failure. |
345,857 | def delete(self, instance, acl):
base_url = self._url.format(instance=instance)
url = .format(base=base_url, aclid=acl)
response = requests.delete(url, **self._default_request_kwargs)
if response.status_code == 200:
logger.info(.format(acl))
else:
... | Delete an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance on which the ACL exists.
:param str acll: The ID of the ACL to delete. |
345,858 | def add_path(self, path, attribs=None, group=None):
if group is None:
group = self.tree.getroot()
elif all(isinstance(elem, str) for elem in group):
group = self.get_or_add_group(group)
elif not isinstance(group, Element):
... | Add a new path to the SVG. |
345,859 | def set_option(self, scan_id, name, value):
self.scans_table[scan_id][][name] = value | Set a scan_id scan's name option to value. |
345,860 | def getgenes(args):
p = OptionParser(getgenes.__doc__)
p.add_option("--prefix", default="gbout",
help="prefix of output files [default: %default]")
p.add_option("--nopep", default=False, action="store_true",
help="Only get cds and bed, no pep [default: %default]")
filenames,... | %prog getgenes [--options]
Read GenBank file, or retrieve from web.
Output bed, cds files, and pep file (can turn off with --nopep).
Either --gb_dir or --id/--simple should be provided. |
345,861 | def covariance(self):
mu = self.moments_central
if mu[0, 0] != 0:
m = mu / mu[0, 0]
covariance = self._check_covariance(
np.array([[m[0, 2], m[1, 1]], [m[1, 1], m[2, 0]]]))
return covariance * u.pix**2
else:
return np.empt... | The covariance matrix of the 2D Gaussian function that has the
same second-order moments as the source. |
345,862 | def pickColor( self ):
color = QColorDialog.getColor( self.color(), self )
if ( color.isValid() ):
self.setColor(color) | Prompts the user to select a color for this button. |
345,863 | def cleanup_files(self):
logger.debug()
with indent_log():
for req in self.reqs_to_cleanup:
req.remove_temporary_source() | Clean up files, remove builds. |
345,864 | def _numToTwoByteString(value, numberOfDecimals=0, LsbFirst=False, signed=False):
_checkNumerical(value, description=)
_checkInt(numberOfDecimals, minvalue=0, description=)
_checkBool(LsbFirst, description=)
_checkBool(signed, description=)
multiplier = 10 ** numberOfDecimals
integer = int... | Convert a numerical value to a two-byte string, possibly scaling it.
Args:
* value (float or int): The numerical value to be converted.
* numberOfDecimals (int): Number of decimals, 0 or more, for scaling.
* LsbFirst (bol): Whether the least significant byte should be first in the resulting... |
345,865 | async def initialize(self) -> None:
if self._socket_type == zmq.ROUTER:
self._dealer_ident, _ = await self._sock.recv_multipart()
elif self._socket_type == zmq.DEALER:
await self._sock.send_multipart([b])
else:
raise Runti... | \
Initializes a `DEALER`/`ROUTER` based connection.
The DEALER side will send a `[b'']` message;
the router side will receive it and store the received identifier for sending messages later. |
345,866 | def n1ql_index_watch(self, indexes,
timeout=30, interval=0.2, watch_primary=False):
kwargs = {
: int(timeout * 1000000),
: int(interval * 1000000)
}
ixlist = [N1qlIndex.from_any(x, self._cb.bucket) for x in indexes]
if watch_prima... | Await completion of index building
This method will wait up to `timeout` seconds for every index in
`indexes` to have been built. It will poll the cluster every
`interval` seconds.
:param list indexes: A list of indexes to check. This is returned by
:meth:`build_deferred_in... |
345,867 | def request(self, action):
ev = threading.Event()
first = False
with self.__lock:
if len(self.__events) == 0:
first = True
self.__events.append(ev)
if first:
action()
return ev | Request an action to be performed, in case one. |
345,868 | def stats(syslog_ng_sbin_dir=None):
**
try:
ret = _run_command_in_extended_path(syslog_ng_sbin_dir,
,
(,))
except CommandExecutionError as err:
return _format_return_data(retcode=-1, stderr=six.text_type(... | Returns statistics from the running syslog-ng instance. If
syslog_ng_sbin_dir is specified, it is added to the PATH during the
execution of the command syslog-ng-ctl.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.stats
salt '*' syslog_ng.stats /home/user/install/syslog-ng/sbin |
345,869 | def showEvent(self, event):
QWidget.showEvent(self, event)
self.spinner.start() | Override show event to start waiting spinner. |
345,870 | def support_support_param_hostip(self, **kwargs):
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
support_param = ET.SubElement(support, "support-param")
hostip = ET.SubElement(support_param, "hostip")
ho... | Auto Generated Code |
345,871 | def merge_translation(self, context):
language = get_language()
i18n_service = context.get(, None)
if i18n_service:
if language not in self._translations:
self._translations[language] = trans_real.DjangoTranslation(language)
translat... | Context wrapper which modifies the given language's translation catalog using the i18n service, if found. |
345,872 | def get_redirect(self):
index_url = self.appbuilder.get_url_for_index
page_history = Stack(session.get("page_history", []))
if page_history.pop() is None:
return index_url
session["page_history"] = page_history.to_json()
url = page_history.pop() or index_url... | Returns the previous url. |
345,873 | def run_step(context):
logger.debug("started")
context.assert_key_has_value(key=, caller=__name__)
paths_to_check = context[]
if not paths_to_check:
raise KeyInContextHasNoValueError("context[] must have a "
f"value for {__name__}.")
if ... | pypyr step that checks if a file or directory path exists.
Args:
context: pypyr.context.Context. Mandatory.
The following context key must exist
- pathsToCheck. str/path-like or list of str/paths.
Path to file on disk to check.
All input... |
345,874 | def execute(self, conn, migration_url="", migration_input="", create_by="", migration_request_id="", oldest= False, transaction=False):
sql = self.sql
binds = {}
if migration_request_id:
sql += " WHERE MR.MIGRATION_REQUEST_ID=:migration_request_id"
binds[]=migration_request_id
... | Lists all requests if pattern is not provided. |
345,875 | def plotcdf(self, x=None, xmin=None, alpha=None, pointcolor=,
dolog=True, zoom=True, pointmarker=, **kwargs):
if x is None: x=self.data
if xmin is None: xmin=self._xmin
if alpha is None: alpha=self._alpha
x=np.sort(x)
n=len(x)
xcdf = np.arange(n,... | Plots CDF and powerlaw |
345,876 | def run(self, name, replace=None, actions=None):
self.actions = actions
action = actions.get(name)
if not action:
self.die("Action not found: {}", name)
action[] = name
action_type = action.get(, "none")
try:
func = getattr(self, + acti... | Do an action.
If `replace` is provided as a dictionary, do a search/replace using
%{} templates on content of action (unique to action type) |
345,877 | def read_welcome_message(self):
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match(
, ReplyCodes.service_ready_for_new_user, reply) | Read the welcome message.
Coroutine. |
345,878 | def tag_patches_branch(package, local_patches_branch, patches_branch,
force=False, push=False):
vr = specfile.Spec().get_vr(epoch=False)
nvr_tag = package + + vr
tag_cmd = [, nvr_tag, local_patches_branch]
if force:
tag_cmd.append()
git(*tag_cmd)
if push:
... | Tag the local_patches_branch with this package's NVR. |
345,879 | def search_alert_deleted_for_facet(self, facet, **kwargs):
kwargs[] = True
if kwargs.get():
return self.search_alert_deleted_for_facet_with_http_info(facet, **kwargs)
else:
(data) = self.search_alert_deleted_for_facet_with_http_info(facet, **kwargs)
... | Lists the values of a specific facet over the customer's deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_alert_deleted_for_facet(facet, async_req... |
345,880 | def queryProxy(self, query):
valid_proxies = []
query_scheme = query.url().scheme()
query_host = query.url().host()
query_scheme_host = .format(query_scheme, query_host)
proxy_servers = process_proxy_servers(self.proxy_servers)
if proxy_servers:
... | Override Qt method. |
345,881 | def convert_accents(self):
nkfd_form = unicodedata.normalize(, self.string)
return "".join([
char
for char in nkfd_form
if not unicodedata.combining(char)
]) | Removes accents from text
:return: input with converted accents chars |
345,882 | def fread(f,byteLocation,structFormat=None,nBytes=1):
f.seek(byteLocation)
if structFormat:
val = struct.unpack(structFormat, f.read(struct.calcsize(structFormat)))
val = val[0] if len(val)==1 else list(val)
return val
else:
return f.read(nBytes) | Given an already-open (rb mode) file object, return a certain number of bytes at a specific location.
If a struct format is given, calculate the number of bytes required and return the object it represents. |
345,883 | def call_method(self, method_name_or_object, params=None):
if isinstance(method_name_or_object, MethodCall):
req_obj = method_name_or_object
else:
req_obj = MethodCall(method_name_or_object, params)
raw_response = self.handle_single_request(req_obj)
respo... | Calls the ``method_name`` method from the given service and returns a
:py:class:`gemstone.client.structs.Result` instance.
:param method_name_or_object: The name of te called method or a ``MethodCall`` instance
:param params: A list of dict representing the parameters for the request
:r... |
345,884 | def setup_db(connection_string):
global DB_Session, engine
new_database = False
if connection_string == or not database_exists(connection_string):
new_database = True
engine = create_engine(connection_string, connect_args={: 20})
entities.Base.metadata.create_all(engine)
DB_Session... | Sets up the database schema and adds defaults.
:param connection_string: Database URL. e.g: sqlite:///filename.db
This is usually taken from the config file. |
345,885 | def parse_struct(path_dir):
with open(os.path.join(path_dir, "boltztrap.struct"), ) as f:
tokens = f.readlines()
return Lattice([[Length(float(tokens[i].split()[j]), "bohr").
to("ang") for j in range(3)] for i in
range(1, 4)... | Parses boltztrap.struct file (only the volume)
Args:
path_dir: (str) dir containing the boltztrap.struct file
Returns:
(float) volume |
345,886 | def _build_national_number_for_parsing(number):
index_of_phone_context = number.find(_RFC3966_PHONE_CONTEXT)
if index_of_phone_context >= 0:
phone_context_start = index_of_phone_context + len(_RFC3966_PHONE_CONTEXT)
if (phone_context_start < (len(number) - 1) and
... | Converts number to a form that we can parse and return it if it is
written in RFC3966; otherwise extract a possible number out of it and return it. |
345,887 | def moist_amplification_factor(Tkelvin, relative_humidity=0.8):
deltaT = 0.01
dqsdTs = (qsat(Tkelvin+deltaT/2, 1000.) - qsat(Tkelvin-deltaT/2, 1000.)) / deltaT
return const.Lhvap / const.cp * relative_humidity * dqsdTs | Compute the moisture amplification factor for the moist diffusivity
given relative humidity and reference temperature profile. |
345,888 | def generate(self, x, **kwargs):
assert self.parse_params(**kwargs)
asserts = []
if self.clip_min is not None:
asserts.append(utils_tf.assert_greater_equal(x,
tf.cast(self.clip_min,
... | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params` |
345,889 | def find_python(ignores, paths, explicit_file_mode, workdir=):
if explicit_file_mode:
return SingleFiles(paths, workdir or os.getcwd())
else:
assert len(paths) == 1
files, modules, directories, packages = _find_paths(ignores, paths[0], workdir)
return FoundFiles(workdir, fil... | Returns a FoundFiles class containing a list of files, packages, directories,
where files are simply all python (.py) files, packages are directories
containing an `__init__.py` file, and directories is a list of all directories.
All paths are relative to the dirpath argument. |
345,890 | def get_bandcamp_metadata(url):
request = requests.get(url)
try:
sloppy_json = request.text.split("var TralbumData = ")
sloppy_json = sloppy_json[1].replace(, "")
sloppy_json = sloppy_json.replace("")
sloppy_json = sloppy_json.split("};")[0] + "};"
sloppy_json = slop... | Read information from the Bandcamp JavaScript object.
The method may return a list of URLs (indicating this is probably a "main" page which links to one or more albums),
or a JSON if we can already parse album/track info from the given url.
The JSON is "sloppy". The native python JSON parser often can't dea... |
345,891 | def register_module_alias(self, alias, module_path, after_init=False):
command = if after_init else
self._set(command, % (alias, module_path), multi=True)
return self._section | Adds an alias for a module.
http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html
:param str|unicode alias:
:param str|unicode module_path:
:param bool after_init: add a python module alias after uwsgi module initialization |
345,892 | def yn(n, x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_yn,
(n, BigFloat._implicit_convert(x)),
context,
) | Return the value of the second kind Bessel function of order ``n`` at
``x``.
``n`` should be a Python integer. |
345,893 | def apply(self, cls, originalMemberNameList, memberName, classNamingConvention, getter, setter):
originalProperty = None
if memberName in originalMemberNameList:
member = getattr(cls, memberName)
if not isinstance(member, property):
... | :type cls: type
:type originalMemberNameList: list(str)
:type memberName: str
:type classNamingConvention: INamingConvention|None |
345,894 | def run_details(self, run):
run_data = dict(run=run)
req = urllib.request.Request("%s/nglims/api_run_details" % self._base_url,
urllib.parse.urlencode(run_data))
response = urllib.request.urlopen(req)
info = json.loads(response.read())
if "error" in info:... | Retrieve sequencing run details as a dictionary. |
345,895 | def __PrintMessageDocstringLines(self, message_type):
description = message_type.description or % (
message_type.name)
short_description = (
_EmptyMessage(message_type) and
len(description) < (self.__printer.CalculateWidth() - 6))
with self.__printer... | Print the docstring for this message. |
345,896 | def initializers(self, prefix: Optional[str] = None) -> List[str]:
if self._type_reference:
ref = self._context.reference(self._type_reference)
if not getattr(ref, , None):
raise NotImplementedError("Reference to " + self._type_reference... | Return the __init__ initializer assignment block |
345,897 | def init(ctx):
log.info()
ctx.invoke(migrate, record=True)
ctx.invoke(index)
if IS_TTY:
text = _()
if click.confirm(text, default=True):
user = ctx.invoke(user_commands.create)
ctx.invoke(user_commands.set_admin, email=user.email)
text = _()
... | Initialize your udata instance (search index, user, sample data...) |
345,898 | def _tee_output(make_proc, stdout=None, stderr=None, backend=):
logged_out = []
logged_err = []
if backend == :
backend =
if backend == :
if not POSIX:
raise NotImplementedError()
_proc_iteroutput = _proc_iteroutput_select
elif backend =... | Simultaneously reports and captures stdout and stderr from a process
subprocess must be created using (stdout=subprocess.PIPE,
stderr=subprocess.PIPE) |
345,899 | def add_dep(self, ):
i = self.dep_tablev.currentIndex()
item = i.internalPointer()
if item:
dep = item.internal_data()
dep.projects.add(self._project)
self.deps.append(dep)
item.set_parent(None) | Add a dep and store it in the self.deps
:returns: None
:rtype: None
:raises: None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.