Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
6,500 | def is_valid_python(code, reraise=True, ipy_magic_workaround=False):
import ast
try:
if ipy_magic_workaround:
code = .join([ if re.match(r, line) else line for line in code.split()])
ast.parse(code)
except SyntaxError:
if reraise:
import utool as ut
... | References:
http://stackoverflow.com/questions/23576681/python-check-syntax |
6,501 | def stream_replicate():
stream = primary.stream(SomeDataBlob, "trim_horizon")
next_heartbeat = pendulum.now()
while True:
now = pendulum.now()
if now >= next_heartbeat:
stream.heartbeat()
next_heartbeat = now.add(minutes=10)
record = next(stream)
... | Monitor changes in approximately real-time and replicate them |
6,502 | def set_polling_override(self, override):
polling_override = self.get_characteristic_handle_from_uuid(UUID_POLLING_OVERRIDE)
if polling_override is None:
logger.warn()
return False
if self.dongle._write_attribute(self.conn_handle, polling_override, struc... | Set the sensor polling timer override value in milliseconds.
Due to the time it takes to poll all the sensors on up to 5 IMUs, it's not
possible for the SK8 firmware to define a single fixed rate for reading
new samples without it being artificially low for most configurations.
... |
6,503 | def bls_stats_singleperiod(times, mags, errs, period,
magsarefluxes=False,
sigclip=10.0,
perioddeltapercent=10,
nphasebins=200,
mintransitduration=0.01,
maxtr... | This calculates the SNR, depth, duration, a refit period, and time of
center-transit for a single period.
The equation used for SNR is::
SNR = (transit model depth / RMS of LC with transit model subtracted)
* sqrt(number of points in transit)
NOTE: you should set the kwargs `sigclip... |
6,504 | def cluster_coincs_multiifo(stat, time_coincs, timeslide_id, slide, window, argmax=numpy.argmax):
time_coinc_zip = zip(*time_coincs)
if len(time_coinc_zip) == 0:
logging.info()
return numpy.array([])
time_avg_num = []
for tc in time_coinc_zip:
time_avg_num.append(mean_... | Cluster coincident events for each timeslide separately, across
templates, based on the ranking statistic
Parameters
----------
stat: numpy.ndarray
vector of ranking values to maximize
time_coincs: tuple of numpy.ndarrays
trigger times for each ifo, or -1 if an ifo does not particip... |
6,505 | def pemp(stat, stat0):
assert len(stat0) > 0
assert len(stat) > 0
stat = np.array(stat)
stat0 = np.array(stat0)
m = len(stat)
m0 = len(stat0)
statc = np.concatenate((stat, stat0))
v = np.array([True] * m + [False] * m0)
perm = np.argsort(-statc, kind="mergesort")
v = v... | Computes empirical values identically to bioconductor/qvalue empPvals |
6,506 | def c2ln(c,l1,l2,n):
"char[n] to two unsigned long???"
c = c + n
l1, l2 = U32(0), U32(0)
f = 0
if n == 8:
l2 = l2 | (U32(c[7]) << 24)
f = 1
if f or (n == 7):
l2 = l2 | (U32(c[6]) << 16)
f = 1
if f or (n == 6):
l2 = l2 | (U32(c[5]) << 8)
f = 1
... | char[n] to two unsigned long??? |
6,507 | def get_datasets_list(self, project_id=None):
dataset_project_id = project_id if project_id else self.project_id
try:
datasets_list = self.service.datasets().list(
projectId=dataset_project_id).execute(num_retries=self.num_retries)[]
self.log.info("Datas... | Method returns full list of BigQuery datasets in the current project
.. seealso::
For more information, see:
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list
:param project_id: Google Cloud Project for which you
try to get all datasets
... |
6,508 | def files_to_pif(files, verbose=0, quality_report=True, inline=True):
found_parser = False
for possible_parser in [PwscfParser, VaspParser]:
try:
parser = possible_parser(files)
found_parser = True
break
except InvalidIngesterException:
... | Given a directory that contains output from
a DFT calculation, parse the data and return
a pif object
Input:
files - [str] list of files from which the parser is allowed to read.
verbose - int, How much status messages to print
Output:
pif - ChemicalSystem, Results and settings... |
6,509 | def transform(function):
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
return function(result)
except:
exctype, value... | Return a processor for a style's "transform" function. |
6,510 | def vb_get_network_addresses(machine_name=None, machine=None, wait_for_pattern=None):
if machine_name:
machine = vb_get_box().findMachine(machine_name)
ip_addresses = []
log.debug("checking for power on:")
if machine.state == _virtualboxManager.constants.MachineState_Running:
log.... | TODO distinguish between private and public addresses
A valid machine_name or a machine is needed to make this work!
!!!
Guest prerequisite: GuestAddition
!!!
Thanks to Shrikant Havale for the StackOverflow answer http://stackoverflow.com/a/29335390
More information on guest properties: http... |
6,511 | def seq_2_StdStringVector(seq, vec=None):
if vec is None:
if isinstance(seq, StdStringVector):
return seq
vec = StdStringVector()
if not isinstance(vec, StdStringVector):
raise TypeError()
for e in seq:
vec.append(str(e))
return vec | Converts a python sequence<str> object to a :class:`tango.StdStringVector`
:param seq: the sequence of strings
:type seq: sequence<:py:obj:`str`>
:param vec: (optional, default is None) an :class:`tango.StdStringVector`
to be filled. If None is given, a new :class:`tango.Std... |
6,512 | def get_molo_comments(parser, token):
keywords = token.contents.split()
if len(keywords) != 5 and len(keywords) != 7 and len(keywords) != 9:
raise template.TemplateSyntaxError(
" tag takes exactly 2,4 or 6 arguments" % (keywords[0],))
if keywords[1] != :
raise template.Templ... | Get a limited set of comments for a given object.
Defaults to a limit of 5. Setting the limit to -1 disables limiting.
Set the amount of comments to
usage:
{% get_molo_comments for object as variable_name %}
{% get_molo_comments for object as variable_name limit amount %}
{% get_mo... |
6,513 | def user(self, login=None):
if login:
url = self._build_url(, login)
else:
url = self._build_url()
json = self._json(self._get(url), 200)
return User(json, self._session) if json else None | Returns a User object for the specified login name if
provided. If no login name is provided, this will return a User
object for the authenticated user.
:param str login: (optional)
:returns: :class:`User <github3.users.User>` |
6,514 | def dump(self):
return {
"key": self._key,
"status": self._status,
"ttl": self._ttl,
"answer": self._answer.word,
"mode": self._mode.dump(),
"guesses_made": self._guesses_made
} | Dump (return) a dict representation of the GameObject. This is a Python
dict and is NOT serialized. NB: the answer (a DigitWord object) and the
mode (a GameMode object) are converted to python objects of a list and
dict respectively.
:return: python <dict> of the GameObject as detailed ... |
6,515 | def get_surface_as_bytes(self, order=None):
arr8 = self.get_surface_as_array(order=order)
return arr8.tobytes(order=) | Returns the surface area as a bytes encoded RGB image buffer.
Subclass should override if there is a more efficient conversion
than from generating a numpy array first. |
6,516 | def keyword(self) -> Tuple[Optional[str], str]:
i1 = self.yang_identifier()
if self.peek() == ":":
self.offset += 1
i2 = self.yang_identifier()
return (i1, i2)
return (None, i1) | Parse a YANG statement keyword.
Raises:
EndOfInput: If past the end of input.
UnexpectedInput: If no syntactically correct keyword is found. |
6,517 | def get_episodes(self, series_id, **kwargs):
params = {: 1}
for arg, val in six.iteritems(kwargs):
if arg in EPISODES_BY:
params[arg] = val
return self._exec_request(
,
path_args=[series_id, , ], params=params)[] | All episodes for a given series.
Paginated with 100 results per page.
.. warning::
authorization token required
The following search arguments currently supported:
* airedSeason
* airedEpisode
* imdbId
* dvdSeason
* dvd... |
6,518 | def _fourier(self):
freq_bin_upper = 2000
freq_bin_lower = 40
fs = self._metadata[]
Y_transformed = {}
for key in self.Y_dict.keys():
fs = self._metadata["fs"]
Y_transformed[key] = (1./fs)*np.fft.fft(self.Y_dict[key])[freq_bin_lower:... | 1 side Fourier transform and scale by dt all waveforms in catalog |
6,519 | def callback(self, request, **kwargs):
try:
client = self.get_evernote_client()
us = UserService.objects.get(user=request.user, name=ServicesActivated.objects.get(name=))
us.token = client.... | Called from the Service when the user accept to activate it |
6,520 | def bresenham(x1, y1, x2, y2):
points = []
issteep = abs(y2-y1) > abs(x2-x1)
if issteep:
x1, y1 = y1, x1
x2, y2 = y2, x2
rev = False
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
rev = True
deltax = x2 - x1
deltay = abs(y2-y1)
error = int(deltax... | Return a list of points in a bresenham line.
Implementation hastily copied from RogueBasin.
Returns:
List[Tuple[int, int]]: A list of (x, y) points,
including both the start and end-points. |
6,521 | def upload_file(self, path=None, stream=None, name=None, **kwargs):
params = "&".join(["%s=%s" % (k, v) for k, v in kwargs.items()])
url = "http://{master_addr}:{master_port}/dir/assign{params}".format(
master_addr=self.master_addr,
master_port=self.master_port,
... | Uploads file to WeedFS
I takes either path or stream and name and upload it
to WeedFS server.
Returns fid of the uploaded file.
:param string path:
:param string stream:
:param string name:
:rtype: string or None |
6,522 | def _lemmatise_roman_numerals(self, form, pos=False, get_lemma_object=False):
if estRomain(form):
_lemma = Lemme(
cle=form, graphie_accentuee=form, graphie=form, parent=self, origin=0, pos="a",
modele=self.modele("inv")
)
yield Lemmati... | Lemmatise un mot f si c'est un nombre romain
:param form: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma |
6,523 | def configs_in(src_dir):
for filename in files_in_dir(src_dir, ):
with open(os.path.join(src_dir, filename), ) as in_f:
yield json.load(in_f) | Enumerate all configs in src_dir |
6,524 | def compute_bbox_with_margins(margin, x, y):
pos = np.asarray((x, y))
minxy, maxxy = pos.min(axis=1), pos.max(axis=1)
xy1 = minxy - margin*(maxxy - minxy)
xy2 = maxxy + margin*(maxxy - minxy)
return tuple(xy1), tuple(xy2) | Helper function to compute bounding box for the plot |
6,525 | def solve(self, assumptions=[]):
if self.minicard:
if self.use_timer:
start_time = time.clock()
def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL)
self.status = pysolvers.minicard_solve(self.minicard, assumptions)
... | Solve internal formula. |
6,526 | def supported_tags(self, interpreter=None, force_manylinux=True):
if interpreter and not self.is_extended:
return _get_supported_for_any_abi(
platform=self.platform,
impl=interpreter.identity.abbr_impl,
version=interpreter.identity.impl_ver,
force_many... | Returns a list of supported PEP425 tags for the current platform. |
6,527 | def unqueue(self, timeout=10, should_wait=False):
start, now = time.time(), time.time()
wait = self.queue.empty() and should_wait
while (not self.queue.empty() or wait) and (now - start) < timeout:
if wait and self.queue.empty():
time.sleep(0.25)
... | Unqueue all the received ensime responses for a given file. |
6,528 | def _check_all_devices_in_sync(self):
In Sync
if len(self._get_devices_by_failover_status()) != \
len(self.devices):
msg = "Expected all devices in group to have status."
raise UnexpectedDeviceGroupState(msg) | Wait until all devices have failover status of 'In Sync'.
:raises: UnexpectedClusterState |
6,529 | def get_top_sentences(self):
if isinstance(self.__top_sentences, int) is False:
raise TypeError("The type of __top_sentences must be int.")
return self.__top_sentences | getter |
6,530 | def create_fork(self, repo):
assert isinstance(repo, github.Repository.Repository), repo
url_parameters = {
"org": self.login,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
"/repos/" + repo.owner.login + "/" + repo.name + "/fo... | :calls: `POST /repos/:owner/:repo/forks <http://developer.github.com/v3/repos/forks>`_
:param repo: :class:`github.Repository.Repository`
:rtype: :class:`github.Repository.Repository` |
6,531 | def thresholdBlocks(self, blocks, recall_weight=1.5):
candidate_records = itertools.chain.from_iterable(self._blockedPairs(blocks))
probability = core.scoreDuplicates(candidate_records,
self.data_model,
sel... | Returns the threshold that maximizes the expected F score, a
weighted average of precision and recall for a sample of
blocked data.
Arguments:
blocks -- Sequence of tuples of records, where each tuple is a
set of records covered by a blocking predicate
recall... |
6,532 | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Optional[tuple] = None) -> List[IModel]:
raise NotImplementedError | Get aggregated results
: param query: Rulez based query
: param group: Grouping structure
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: todo: Grouping structure need to be documented |
6,533 | def get_season_stats(self, season_key):
season_stats_url = self.api_path + "season/" + season_key + "/stats/"
response = self.get_response(season_stats_url)
return response | Calling Season Stats API.
Arg:
season_key: key of the season
Return:
json data |
6,534 | def import_generators(self, session, debug=False):
def import_res_generators():
generators_sqla = session.query(
self.orm[].columns.id,
self.orm[].columns.subst_id,
self.orm[].columns.la_id,
self.orm... | Imports renewable (res) and conventional (conv) generators
Args:
session : sqlalchemy.orm.session.Session
Database session
debug: If True, information is printed during process
Notes:
Connection of generators is done later on in NetworkDing0's method ... |
6,535 | def plot_mixture(mixture, i=0, j=1, center_style=dict(s=0.15),
cmap=, cutoff=0.0, ellipse_style=dict(alpha=0.3),
solid_edge=True, visualize_weights=False):
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
from... | Plot the (Gaussian) components of the ``mixture`` density as
one-sigma ellipses in the ``(i,j)`` plane.
:param center_style:
If a non-empty ``dict``, plot mean value with the style passed to ``scatter``.
:param cmap:
The color map to which components are mapped in order to
choose ... |
6,536 | def addToLayout(self, analysis, position=None):
layout = self.getLayout()
container_uid = self.get_container_for(analysis)
if IRequestAnalysis.providedBy(analysis) and \
not IDuplicateAnalysis.providedBy(analysis):
container_uids = map(lambda slot: s... | Adds the analysis passed in to the worksheet's layout |
6,537 | def reset(name, soft=False, call=None):
if call != :
raise SaltCloudSystemExit(
)
vm_properties = [
"name",
"summary.runtime.powerState"
]
vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
... | To reset a VM using its name
.. note::
If ``soft=True`` then issues a command to the guest operating system
asking it to perform a reboot. Otherwise hypervisor will terminate VM and start it again.
Default is soft=False
For ``soft=True`` vmtools should be installed on guest system... |
6,538 | def stopped(name, connection=None, username=None, password=None):
return _virt_call(name, , , "Machine has been shut down",
connection=connection, username=username, password=password) | Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect w... |
6,539 | def new_figure_manager(num, *args, **kwargs):
DEBUG_MSG("new_figure_manager()", 3, None)
_create_wx_app()
FigureClass = kwargs.pop(, Figure)
fig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, fig) | Create a new figure manager instance |
6,540 | def on_service_arrival(self, svc_ref):
with self._lock:
new_ranking = svc_ref.get_property(SERVICE_RANKING)
if self._current_ranking is not None:
if new_ranking > self._current_ranking:
self._pending_ref = svc_ref
... | Called when a service has been registered in the framework
:param svc_ref: A service reference |
6,541 | def sg_expand_dims(tensor, opt):
r
opt += tf.sg_opt(axis=-1)
return tf.expand_dims(tensor, opt.axis, name=opt.name) | r"""Inserts a new axis.
See tf.expand_dims() in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : Dimension to expand. Default is -1.
name: If provided, it replaces current tensor's name.
Returns:
A `Tensor`. |
6,542 | async def purgeQueues(self, *args, **kwargs):
return await self._makeApiCall(self.funcinfo["purgeQueues"], *args, **kwargs) | Purge the SQS queues
This method is only for debugging the ec2-manager
This method is ``experimental`` |
6,543 | def updateVersions(region="us-east-1", table="credential-store"):
dynamodb = boto3.resource(, region_name=region)
secrets = dynamodb.Table(table)
response = secrets.scan(ProjectionExpression="
ExpressionAttributeNames={"
items = response["Items"]
for old_item in i... | do a full-table scan of the credential-store,
and update the version format of every credential if it is an integer |
6,544 | def extract_params(raw):
if isinstance(raw, (bytes, unicode_type)):
try:
params = urldecode(raw)
except ValueError:
params = None
elif hasattr(raw, ):
try:
dict(raw)
except ValueError:
params = None
except TypeError:
... | Extract parameters and return them as a list of 2-tuples.
Will successfully extract parameters from urlencoded query strings,
dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an
empty list of parameters. Any other input will result in a return
value of None. |
6,545 | def get_ticket_results(mgr, ticket_id, update_count=1):
ticket = mgr.get_ticket(ticket_id)
table = formatting.KeyValueTable([, ])
table.align[] =
table.align[] =
table.add_row([, ticket[]])
table.add_row([, ticket[]])
table.add_row([, PRIORITY_MAP[ticket.get(, 0)]])
if ticket.ge... | Get output about a ticket.
:param integer id: the ticket ID
:param integer update_count: number of entries to retrieve from ticket
:returns: a KeyValue table containing the details of the ticket |
6,546 | def parse_methodcall(self, tup_tree):
self.check_node(tup_tree, , (,), (),
(, , ))
path = self.list_of_matching(tup_tree,
(, ))
if not path:
raise CIMXMLParseError(
_format("Element {0!A} missing ... | ::
<!ELEMENT METHODCALL ((LOCALCLASSPATH | LOCALINSTANCEPATH),
PARAMVALUE*)>
<!ATTLIST METHODCALL
%CIMName;> |
6,547 | def change_password(self, id_user, user_current_password, password):
if not is_valid_int_param(id_user):
raise InvalidParameterError(
u)
if password is None or password == "":
raise InvalidParameterError(
u)
user_map = dict()
... | Change password of User from by the identifier.
:param id_user: Identifier of the User. Integer value and greater than zero.
:param user_current_password: Senha atual do usuário.
:param password: Nova Senha do usuário.
:return: None
:raise UsuarioNaoExisteError: User not regis... |
6,548 | def text(self):
text =
for run in self.runs:
text += run.text
return text | String formed by concatenating the text of each run in the paragraph.
Tabs and line breaks in the XML are mapped to ``\\t`` and ``\\n``
characters respectively.
Assigning text to this property causes all existing paragraph content
to be replaced with a single run containing the assigned... |
6,549 | def draw_tiling(coord_generator, filename):
im = Image.new(, size=(CANVAS_WIDTH, CANVAS_HEIGHT))
for shape in coord_generator(CANVAS_WIDTH, CANVAS_HEIGHT):
ImageDraw.Draw(im).polygon(shape, outline=)
im.save(filename) | Given a coordinate generator and a filename, render those coordinates in
a new image and save them to the file. |
6,550 | def pumper(html_generator):
source = html_generator()
parser = etree.HTMLPullParser(
events=(, ),
remove_comments=True
)
while True:
for element in parser.read_events():
yield element
try:
parser.feed(next(source))
except StopIteration... | Pulls HTML from source generator,
feeds it to the parser and yields
DOM elements. |
6,551 | def get_aggregations(metrics_dict, saved_metrics, adhoc_metrics=[]):
aggregations = OrderedDict()
invalid_metric_names = []
for metric_name in saved_metrics:
if metric_name in metrics_dict:
metric = metrics_dict[metric_name]
if metric.metric_t... | Returns a dictionary of aggregation metric names to aggregation json objects
:param metrics_dict: dictionary of all the metrics
:param saved_metrics: list of saved metric names
:param adhoc_metrics: list of adhoc metric names
:raise SupersetException: if one or more metr... |
6,552 | def replace(self, **kw):
if "tzinfo" in kw:
if kw["tzinfo"] is None:
raise TypeError("Can not remove the timezone use asdatetime()")
else:
tzinfo = kw["tzinfo"]
del kw["tzinfo"]
else:
tzinfo = None
is_dst = None
if "is_dst" in kw:
is_dst = kw["is_dst... | Return datetime with new specified fields given as arguments.
For example, dt.replace(days=4) would return a new datetime_tz object with
exactly the same as dt but with the days attribute equal to 4.
Any attribute can be replaced, but tzinfo can not be set to None.
Args:
Any datetime_tz attribu... |
6,553 | def get_agent(self, agent_id):
url = % agent_id
return Agent(**self._api._get(url)) | Fetches the agent for the given agent ID |
6,554 | def handle(data_type, data, data_id=None, caller=None):
if not data_id:
data_id = data_type
if data_id not in _handlers:
_handlers[data_id] = dict(
[(h.handle, h) for h in handlers.instantiate_for_data_type(data_type, data_id=data_id)])
for handler in list(_handlers[... | execute all data handlers on the specified data according to data type
Args:
data_type (str): data type handle
data (dict or list): data
Kwargs:
data_id (str): can be used to differentiate between different data
sets of the same data type. If not specified will default to
... |
6,555 | def listen(self, timeout=10):
self._socket.settimeout(float(timeout))
while not self.stopped.isSet():
try:
data, client_address = self._socket.recvfrom(4096)
except socket.timeout:
continue
try:
... | Listen for incoming messages. Timeout is used to check if the server must be switched off.
:param timeout: Socket Timeout in seconds |
6,556 | def feedforward(self):
m = self._numInputs
n = self._numColumns
W = np.zeros((n, m))
for i in range(self._numColumns):
self.getPermanence(i, W[i, :])
return W | Soon to be depriciated.
Needed to make the SP implementation compatible
with some older code. |
6,557 | def _search_for_user_dn(self):
search = self.settings.USER_SEARCH
if search is None:
raise ImproperlyConfigured(
"AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance."
)
results = search.execute(self.connection, {"user": self._username})
... | Searches the directory for a user matching AUTH_LDAP_USER_SEARCH.
Populates self._user_dn and self._user_attrs. |
6,558 | def allow(self, comment, content_object, request):
if self.enable_field:
if not getattr(content_object, self.enable_field):
return False
if self.auto_close_field and self.close_after is not None:
close_after_date = getattr(content_object, self.auto_close_... | Determine whether a given comment is allowed to be posted on
a given object.
Return ``True`` if the comment should be allowed, ``False
otherwise. |
6,559 | def _locate_index(self, index):
assert index >= 0 and index < self.num_images, "index out of range"
pos = self.image_set_index[index]
for k, v in enumerate(self.imdbs):
if pos >= v.num_images:
pos -= v.num_images
else:
return (k, p... | given index, find out sub-db and sub-index
Parameters
----------
index : int
index of a specific image
Returns
----------
a tuple (sub-db, sub-index) |
6,560 | def nlerp_quat(from_quat, to_quat, percent):
result = lerp_quat(from_quat, to_quat, percent)
result.normalize()
return result | Return normalized linear interpolation of two quaternions.
Less computationally expensive than slerp (which not implemented in this
lib yet), but does not maintain a constant velocity like slerp. |
6,561 | def factor_kkt(S_LU, R, d):
nBatch, nineq = d.size()
neq = S_LU[1].size(1) - nineq
oldPivotsPacked = S_LU[1][:, -nineq:] - neq
oldPivots, _, _ = torch.btriunpack(
T_LU[0], oldPivotsPacked, unpack_data=False)
newPivotsPacked = T_LU[1]
newPivots, _, _... | Factor the U22 block that we can only do after we know D. |
6,562 | def send_request(self, request, callback=None, timeout=None, no_response=False):
if callback is not None:
thread = threading.Thread(target=self._thread_body, args=(request, callback))
thread.start()
else:
self.protocol.send_message(request)
if n... | Send a request to the remote server.
:param request: the request to send
:param callback: the callback function to invoke upon response
:param timeout: the timeout of the request
:return: the response |
6,563 | def to_serializable(self, use_bytes=False, bias_dtype=np.float32,
bytes_type=bytes):
from dimod.package_info import __version__
schema_version = "2.0.0"
try:
variables = sorted(self.variables)
except TypeError:
variab... | Convert the binary quadratic model to a serializable object.
Args:
use_bytes (bool, optional, default=False):
If True, a compact representation representing the biases as bytes is used.
bias_dtype (numpy.dtype, optional, default=numpy.float32):
If `use_b... |
6,564 | def _formatters_default(self):
formatter_classes = [
PlainTextFormatter,
HTMLFormatter,
SVGFormatter,
PNGFormatter,
JPEGFormatter,
LatexFormatter,
JSONFormatter,
JavascriptFormatter
]
d = {}
... | Activate the default formatters. |
6,565 | def localize_field(self, value):
if self.default is not None:
if value is None or value == :
value = self.default
return value or | Method that must transform the value from object to localized string |
6,566 | def list_events(self, source=None, severity=None, text_filter=None,
start=None, stop=None, page_size=500, descending=False):
params = {
: if descending else ,
}
if source is not None:
params[] = source
if page_size is not None:
... | Reads events between the specified start and stop time.
Events are sorted by generation time, source, then sequence number.
:param str source: The source of the returned events.
:param str severity: The minimum severity level of the returned events.
One of ``INFO``... |
6,567 | def add_textop_iter(func):
op = type(func.__name__,(WrapOpIter,), {:staticmethod(func)})
setattr(textops.ops,func.__name__,op)
return op | Decorator to declare custom *ITER* function as a new textops op
An *ITER* function is a function that will receive the input text as a *LIST* of lines.
One have to iterate over this list and generate a result (it can be a list, a generator,
a dict, a string, an int ...)
Examples:
>>> @add_tex... |
6,568 | def get_member_brief(self, member_id=0):
title = % self.__class__.__name__
input_fields = {
: member_id
}
for key, value in input_fields.items():
if value:
object_title = % (title, key, str(value))
... | a method to retrieve member profile info
:param member_id: [optional] integer with member id from member profile
:return: dictionary with member profile inside [json] key
member_profile = self.objects.profile_brief.schema |
6,569 | def write(self, message, delay_seconds=None):
new_msg = self.connection.send_message(self, message.get_body_encoded(), delay_seconds)
message.id = new_msg.id
message.md5 = new_msg.md5
return message | Add a single message to the queue.
:type message: Message
:param message: The message to be written to the queue
:rtype: :class:`boto.sqs.message.Message`
:return: The :class:`boto.sqs.message.Message` object that was written. |
6,570 | def confd_state_internal_cdb_client_lock(self, **kwargs):
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.SubElement(confd_state, "internal")
cdb = ET.SubElement(internal, "cdb")
... | Auto Generated Code |
6,571 | def _set_gaussian_expected_stats(self, smoothed_mus, smoothed_sigmas, E_xtp1_xtT):
assert not np.isnan(E_xtp1_xtT).any()
assert not np.isnan(smoothed_mus).any()
assert not np.isnan(smoothed_sigmas).any()
assert smoothed_mus.shape == (self.T, self.D_latent)
assert smoothe... | Both meanfield and VBEM require expected statistics of the continuous latent
states, x. This is a helper function to take E[x_t], E[x_t x_t^T] and E[x_{t+1}, x_t^T]
and compute the expected sufficient statistics for the initial distribution,
dynamics distribution, and Gaussian observation distr... |
6,572 | def vclose(L, V):
lam, X = 0, []
for k in range(3):
lam = lam + V[k] * L[k]
beta = np.sqrt(1. - lam**2)
for k in range(3):
X.append((old_div((V[k] - lam * L[k]), beta)))
return X | gets the closest vector |
6,573 | def removeItem( self ):
item = self.uiMenuTREE.currentItem()
if ( not item ):
return
opts = QMessageBox.Yes | QMessageBox.No
answer = QMessageBox.question( self,
,
\
... | Removes the item from the menu. |
6,574 | def setup_logging():
logging.basicConfig(format=("[%(levelname)s\033[0m] "
"\033[1;31m%(module)s\033[0m: "
"%(message)s"),
level=logging.INFO,
stream=sys.stdout)
logging.addLevelName(logging.ERRO... | Logging config. |
6,575 | def _validate_format(req):
for key in SLOJSONRPC._min_keys:
if not key in req:
logging.debug( % key)
raise SLOJSONRPCError(-32600)
for key in req.keys():
if not key in SLOJSONRPC._allowed_keys:
logging.de... | Validate jsonrpc compliance of a jsonrpc-dict.
req - the request as a jsonrpc-dict
raises SLOJSONRPCError on validation error |
6,576 | def serial_assimilate(self, rootpath):
valid_paths = []
for (parent, subdirs, files) in os.walk(rootpath):
valid_paths.extend(self._drone.get_valid_paths((parent, subdirs,
files)))
data = []
count = 0
... | Assimilate the entire subdirectory structure in rootpath serially. |
6,577 | def encipher_shift(plaintext, plain_vocab, shift):
ciphertext = []
cipher = ShiftEncryptionLayer(plain_vocab, shift)
for _, sentence in enumerate(plaintext):
cipher_sentence = []
for _, character in enumerate(sentence):
encrypted_char = cipher.encrypt_character(character)
cipher_sentence.a... | Encrypt plain text with a single shift layer.
Args:
plaintext (list of list of Strings): a list of plain text to encrypt.
plain_vocab (list of Integer): unique vocabularies being used.
shift (Integer): number of shift, shift to the right if shift is positive.
Returns:
ciphertext (list of Strings): ... |
6,578 | def set_shuffle(self, shuffle):
if not self.my_osid_object_form._is_valid_boolean(
shuffle):
raise InvalidArgument()
self.my_osid_object_form._my_map[] = shuffle | stub |
6,579 | def _evaluate_model_single_file(target_folder, test_file):
logging.info("Create running model...")
model_src = get_latest_model(target_folder, "model")
model_file_pointer = tempfile.NamedTemporaryFile(delete=False)
model_use = model_file_pointer.name
model_file_pointer.close()
logging.info(... | Evaluate a model for a single recording.
Parameters
----------
target_folder : string
Folder where the model is
test_file : string
The test file (.hdf5) |
6,580 | def _parse(self, msg_dict):
error_present = False
for message in self.compiled_messages:
match_on = message[]
if match_on not in msg_dict:
continue
if message[] != msg_dict[match_on]... | Parse a syslog message and check what OpenConfig object should
be generated. |
6,581 | def parse_color(self, color):
if color == :
return None
return (
int(color[1:3], 16),
int(color[3:5], 16),
int(color[5:7], 16)) | color : string, eg: '#rrggbb' or 'none'
(where rr, gg, bb are hex digits from 00 to ff)
returns a triple of unsigned bytes, eg: (0, 128, 255) |
6,582 | def calculateLocalElasticity(self, bp, frames=None, helical=False, unit=):
r
acceptedUnit = [, , ]
if unit not in acceptedUnit:
raise ValueError(" {0} not accepted. Use any of the following: {1} ".format(unit, acceptedUnit))
frames = self._validateFrames(frames)
na... | r"""Calculate local elastic matrix or stiffness matrix for local DNA segment
.. note:: Here local DNA segment referred to less than 5 base-pair long.
In case of :ref:`base-step-image`: Shift (:math:`Dx`), Slide (:math:`Dy`), Rise (:math:`Dz`),
Tilt (:math:`\tau`), Roll (:math:`\rho`) and Twist... |
6,583 | def _retrieveRemoteCertificate(self, From, port=port):
CS = self.service.certificateStorage
host = str(From.domainAddress())
p = AMP()
p.wrapper = self.wrapper
f = protocol.ClientCreator(reactor, lambda: p)
connD = f.connectTCP(host, port)
def connected(... | The entire conversation, starting with TCP handshake and ending at
disconnect, to retrieve a foreign domain's certificate for the first
time. |
6,584 | def remove_labels(self, labels, relabel=False):
self.check_labels(labels)
self.reassign_label(labels, new_label=0)
if relabel:
self.relabel_consecutive() | Remove one or more labels.
Removed labels are assigned a value of zero (i.e., background).
Parameters
----------
labels : int, array-like (1D, int)
The label number(s) to remove.
relabel : bool, optional
If `True`, then the segmentation image will be re... |
6,585 | def will_set(self, topic, payload=None, qos=0, retain=False):
if topic is None or len(topic) == 0:
raise ValueError()
if qos<0 or qos>2:
raise ValueError()
if isinstance(payload, str):
self._will_payload = payload.encode()
elif isinstance(payl... | Set a Will to be sent by the broker in case the client disconnects unexpectedly.
This must be called before connect() to have any effect.
topic: The topic that the will message should be published on.
payload: The message to send as a will. If not given, or set to None a
zero length me... |
6,586 | def netconf_state_statistics_in_bad_rpcs(self, **kwargs):
config = ET.Element("config")
netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
statistics = ET.SubElement(netconf_state, "statistics")
in_bad_rpcs = ET.Su... | Auto Generated Code |
6,587 | def scale(self, x, y=None, z=None):
"Uniform scale, if only sx argument is specified"
if y is None:
y = x
if z is None:
z = x
m = self
for col in range(4):
m[0,col] *= x
m[1,col] *= y
m[2,col] *= z... | Uniform scale, if only sx argument is specified |
6,588 | def venv_bin(name=None):
if not hasattr(sys, "real_prefix"):
easy.error("ERROR: is not a virtualenv" % (sys.executable,))
sys.exit(1)
for bindir in ("bin", "Scripts"):
bindir = os.path.join(sys.prefix, bindir)
if os.path.exists(bindir):
if name:
... | Get the directory for virtualenv stubs, or a full executable path
if C{name} is provided. |
6,589 | def currentPage(self):
self._updateResults(self._sortAttributeValue(0), equalToStart=True, refresh=True)
return self._currentResults | Return a sequence of mappings of attribute IDs to column values, to
display to the user.
nextPage/prevPage will strive never to skip items whose column values
have not been returned by this method.
This is best explained by a demonstration. Let's say you have a table
viewing a... |
6,590 | def repartition(self, npartitions):
if self.mode == :
return self._constructor(self.values.repartition(npartitions)).__finalize__(self)
else:
notsupported(self.mode) | Repartition data (Spark only).
Parameters
----------
npartitions : int
Number of partitions after repartitions. |
6,591 | def minimize_metric(field, metric_func, nm, res, ival, roi=None,
coarse_acc=1, fine_acc=.005,
return_gradient=True, padding=True):
if roi is not None:
assert len(roi) == len(field.shape) * \
2, "ROI must match field dimension"
initshape = field.s... | Find the focus by minimizing the `metric` of an image
Parameters
----------
field : 2d array
electric field
metric_func : callable
some metric to be minimized
ival : tuple of floats
(minimum, maximum) of interval to search in pixels
nm : float
RI of medium
re... |
6,592 | def register(scheme):
scheme = nstr(scheme)
urlparse.uses_fragment.append(scheme)
urlparse.uses_netloc.append(scheme)
urlparse.uses_params.append(scheme)
urlparse.uses_query.append(scheme)
urlparse.uses_relative.append(scheme) | Registers a new scheme to the urlparser.
:param schema | <str> |
6,593 | def user_fields(self, user):
return self._query_zendesk(self.endpoint.user_fields, , id=user) | Retrieve the user fields for this user.
:param user: User object or id |
6,594 | def nlargest(self, n=5, keep=):
return algorithms.SelectNSeries(self, n=n, keep=keep).nlargest() | Return the largest `n` elements.
Parameters
----------
n : int, default 5
Return this many descending sorted values.
keep : {'first', 'last', 'all'}, default 'first'
When there are duplicate values that cannot all fit in a
Series of `n` elements:
... |
6,595 | def down(self, path, link, repo):
filename = link.split("/")[-1]
if not os.path.isfile(path + filename):
Download(path, link.split(), repo).start() | Download files |
6,596 | def start_polling(self, interval):
interval = float(interval)
self.polling = True
self.term_checker.reset()
logger.info("Starting polling for changes to the track list")
while self.polling:
loop_start = time()
self.update_stream()
... | Start polling for term updates and streaming. |
6,597 | def listen(self, timeout=10):
self._socket.settimeout(float(timeout))
while not self.stopped.isSet():
try:
data, client_address = self._socket.recvfrom(4096)
if len(client_address) > 2:
client_address = (client_address[0], client_a... | Listen for incoming messages. Timeout is used to check if the server must be switched off.
:param timeout: Socket Timeout in seconds |
6,598 | def isel_points(self, dim=, **indexers):
warnings.warn(
, DeprecationWarning, stacklevel=2)
indexer_dims = set(indexers)
def take(variable, slices):
if hasattr(variable.data, ):
... | Returns a new dataset with each array indexed pointwise along the
specified dimension(s).
This method selects pointwise values from each array and is akin to
the NumPy indexing behavior of `arr[[0, 1], [0, 1]]`, except this
method does not require knowing the order of each array's dimen... |
6,599 | def __coord_mel_hz(n, fmin=0, fmax=11025.0, **_kwargs):
if fmin is None:
fmin = 0
if fmax is None:
fmax = 11025.0
basis = core.mel_frequencies(n, fmin=fmin, fmax=fmax)
basis[1:] -= 0.5 * np.diff(basis)
basis = np.append(np.maximum(0, basis), [fmax])
return basis | Get the frequencies for Mel bins |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.