Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
369,600 | def _get_batch_name(items, skip_jointcheck=False):
batch_names = collections.defaultdict(int)
has_joint = any([is_joint(d) for d in items])
for data in items:
if has_joint and not skip_jointcheck:
batches = dd.get_sample_name(data)
else:
batches = dd.get_batches(... | Retrieve the shared batch name for a group of items. |
369,601 | def _trychar(char, fallback, asciimode=None):
if asciimode is True:
return fallback
if hasattr(sys.stdout, ) and sys.stdout.encoding:
try:
char.encode(sys.stdout.encoding)
except Exception:
pass
else:
return char
return ... | Logic from IPython timeit to handle terminals that cant show mu
Args:
char (str): character, typically unicode, to try to use
fallback (str): ascii character to use if stdout cannot encode char
asciimode (bool): if True, always use fallback
Example:
>>> char = _trychar('µs', 'u... |
369,602 | def build_date(self):
if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):
return self.dutinformation.get(0).build.date
return None | get build date.
:return: build date. None if not found |
369,603 | def move_window(self, destination="", session=None):
session = session or self.get()
proc = self.cmd(
,
% (self.get(), self.index),
% (session, destination),
)
if proc.stderr:
raise exc.LibTmuxException(proc.stderr)
sel... | Move the current :class:`Window` object ``$ tmux move-window``.
Parameters
----------
destination : str, optional
the ``target window`` or index to move the window to, default:
empty string
session : str, optional
the ``target session`` or index to mo... |
369,604 | def get_nearest_edges(G, X, Y, method=None, dist=0.0001):
start_time = time.time()
if method is None:
ne = [get_nearest_edge(G, (x, y)) for x, y in zip(X, Y)]
ne = [(u, v) for _, u, v in ne]
elif method == :
if not cKDTree:
raise ImportError()
... | Return the graph edges nearest to a list of points. Pass in points
as separate vectors of X and Y coordinates. The 'kdtree' method
is by far the fastest with large data sets, but only finds approximate
nearest edges if working in unprojected coordinates like lat-lng (it
precisely finds the nearest edge ... |
369,605 | def _extract(self, identifier):
conjugation = []
if self.tree.xpath( + identifier.decode() + ):
p = self.tree.xpath( + identifier.decode() + )[0].getparent()
for font in p.iterfind():
text = self._normalize(font.text_content())
next = font.getnext()
text += + self._normalize(next.text_content... | Extracts data from conjugation table. |
369,606 | def content_val(self, ymldata=None, messages=None):
self._ymlproc = YAMLProcessor(self._ymlfile, False)
log.debug("BEGIN: Content-based validation of Command dictionary")
if ymldata is not None:
cmddict = ymldata
elif ymldata is None and self._ymlproc.load... | Validates the Command Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc. |
369,607 | def _parse_module_with_import(self, uri):
mod = __import__(uri, fromlist=[uri])
obj_strs = [obj for obj in dir(mod) if not obj.startswith()]
functions = []
classes = []
for obj_str in obj_strs:
if obj_str not in mod.__dict__:
... | Look for functions and classes in an importable module.
Parameters
----------
uri : str
The name of the module to be parsed. This module needs to be
importable.
Returns
-------
functions : list of str
A list of (public) function names... |
369,608 | def _format_exitcodes(exitcodes):
str_exitcodes = ["{}({})".format(_get_exitcode_name(e), e)
for e in exitcodes if e is not None]
return "{" + ", ".join(str_exitcodes) + "}" | Format a list of exit code with names of the signals if possible |
369,609 | def regex(self, *pattern, **kwargs):
self.pattern(self.build_re(*pattern, **kwargs))
return self | Add re pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk |
369,610 | def _get_closest_ansi_color(r, g, b, exclude=()):
assert isinstance(exclude, tuple)
saturation = abs(r - g) + abs(g - b) + abs(b - r)
if saturation > 30:
exclude += (, , , )
distance = 257*257*3
match =
for name, (r2, g2, b2) in ANSI_COLORS_TO_RGB.items(... | Find closest ANSI color. Return it by name.
:param r: Red (Between 0 and 255.)
:param g: Green (Between 0 and 255.)
:param b: Blue (Between 0 and 255.)
:param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.) |
369,611 | def logger(self) -> Logger:
if self._logger is None:
self._logger = create_logger(self)
return self._logger | A :class:`logging.Logger` logger for the app.
This can be used to log messages in a format as defined in the
app configuration, for example,
.. code-block:: python
app.logger.debug("Request method %s", request.method)
app.logger.error("Error, of some kind") |
369,612 | def _run_qmc(self, boot):
self._tmp = os.path.join(self.dirs, ".tmpwtre")
cmd = [ip.bins.qmc, "qrtt="+self.files.qdump, "otre="+self._tmp]
proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
res = proc.communicate()
if proc... | runs quartet max-cut on a quartets file |
369,613 | def get_push_commits(self, repository_id, push_id, project=None, top=None, skip=None, include_links=None):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if repository_id is not None:
route_values[] = self._serialize.u... | GetPushCommits.
Retrieve a list of commits associated with a particular push.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param int push_id: The id of the push.
:param str project: Project ID or project... |
369,614 | def execute(self, query):
c = self.conn.cursor()
result = c.execute(query)
for i in result:
yield i | Execute a query directly on the database. |
369,615 | def get_element_tree(parent_to_parse):
if isinstance(parent_to_parse, ElementTree):
return parent_to_parse
element = get_element(parent_to_parse)
return ElementTree() if element is None else ElementTree(element) | :return: an ElementTree initialized with the parsed element.
:see: get_element(parent_to_parse, element_path) |
369,616 | def next_address_avoid_collision(self, start_addr):
i = 1
while self.is_address_in_use(next_addr(start_addr, i)):
i += 1
return next_addr(start_addr, i) | Finds the next address recursively which does not collide with any other address |
369,617 | def handle_POST(self, environ, start_response):
try:
length = int(environ[])
data = environ[].read(length)
response = self.dispatcher._marshaled_di... | Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. |
369,618 | def __on_message(self, ws, message):
message = json.loads(message)
self.logger.debug(json.dumps(message))
table = message[] if in message else None
action = message[] if in message else None
try:
if in message:
self.logger.debug("Subscribe... | Handler for parsing WS messages. |
369,619 | def is_number(obj):
try:
from numbers import Number
except ImportError:
from operator import isNumberType
return isNumberType(obj)
else:
return isinstance(obj, Number) | Helper function to determine numbers
across Python 2.x and 3.x |
369,620 | def update(self):
if self._receiver_type == AVR_X_2016.type:
return self._update_avr_2016()
else:
return self._update_avr() | Get the latest status information from device.
Method executes the update method for the current receiver type. |
369,621 | def dragMoveEvent( self, event ):
filt = self.dragDropFilter()
if not filt:
super(XTreeWidget, self).dragMoveEvent(event)
return
filt(self, event) | Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent> |
369,622 | def is_training():
curr = ctypes.c_bool()
check_call(_LIB.MXAutogradIsTraining(ctypes.byref(curr)))
return curr.value | Get status on training/predicting.
Returns
-------
Current state of training/predicting. |
369,623 | def __parseParameters(self):
self.__parameters = []
for parameter in self.__data[]:
self.__parameters.append(Parameter(parameter)) | Parses the parameters of data. |
369,624 | def _onLexerError(self, message):
self.isOK = False
if message.strip() != "":
self.lexerErrors.append(message) | Memorizes a lexer error message |
369,625 | def toupper(self):
return H2OFrame._expr(expr=ExprNode("toupper", self), cache=self._ex._cache) | Translate characters from lower to upper case for a particular column.
:returns: new H2OFrame with all strings in the current frame converted to the uppercase. |
369,626 | def modify_identity(self, identity, **kwargs):
if isinstance(identity, zobjects.Identity):
self.request(, {: identity._full_data})
return self.get_identities(identity=identity.name)[0]
else:
attrs = []
for attr, value in kwargs.items():
... | Modify some attributes of an identity or its name.
:param: identity a zobjects.Identity with `id` set (mandatory). Also
set items you want to modify/set and/or the `name` attribute to
rename the identity.
Can also take the name in string and then attributes to modif... |
369,627 | def sub_menu(request, page_id):
page = Page.objects.get(id=page_id)
pages = page.children.all()
page_languages = settings.PAGE_LANGUAGES
return render_to_response("admin/basic_cms/page/sub_menu.html", {
: page,
: pages,
: page_languages,
}, context_instance=RequestContex... | Render the children of the requested page with the sub_menu
template. |
369,628 | def validateDocumentFinal(self, doc):
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlValidateDocumentFinal(self._o, doc__o)
return ret | Does the final step for the document validation once all
the incremental validation steps have been completed
basically it does the following checks described by the XML
Rec Check all the IDREF/IDREFS attributes definition for
validity |
369,629 | def get_objective_hierarchy_design_session_for_objective_bank(self, objective_bank_id, proxy):
if not self.supports_objective_hierarchy_design():
raise errors.Unimplemented()
return sessions.ObjectiveHierarchyDesignSession(objective_bank_id, proxy... | Gets the ``OsidSession`` associated with the objective hierarchy design service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
objective bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveHierarchyDesignSession... |
369,630 | def only_horizon(meshes, xs, ys, zs, expose_horizon=False):
return {comp_no: mesh.visibilities * (mesh.mus > 0).astype(int) for comp_no, mesh in meshes.items()}, None, None | Check all visible or partial triangles to see if they're behind the horizon,
by checking the direction of the z-component of the normals (ie hidden if mu<0) |
369,631 | def DownloadData(name=, data_dir=DataPath()):
if name == :
for tmp_name in fits_collection.keys():
DownloadData(name=tmp_name, data_dir=data_dir)
return
if name not in fits_collection.keys():
raise Exception(%name)
print(%name)
data_url = fits_collection[name].... | Downloads fit data to DataPath() diretory.
If name='all', gets all fit data. |
369,632 | def p_file_cr_text_1(self, p):
try:
self.builder.set_file_copyright(self.document, p[2])
except OrderError:
self.order_error(, , p.lineno(1))
except CardinalityError:
self.more_than_one_error(, p.lineno(1)) | file_cr_text : FILE_CR_TEXT file_cr_value |
369,633 | def _append_national_number(self, national_number):
prefix_before_nn_len = len(self._prefix_before_national_number)
if (self._should_add_space_after_national_prefix and prefix_before_nn_len > 0 and
self._prefix_before_national_number[-1] != _SEPARATOR_BEFORE_NATIONAL_NUMBER):
... | Combines the national number with any prefix (IDD/+ and country
code or national prefix) that was collected. A space will be inserted
between them if the current formatting template indicates this to be
suitable. |
369,634 | def rebuild(self, scene=None):
rect = QRectF(0, 0, self.minimumWidth(), self.minimumHeight())
self.setRect(rect)
self._dirty = False
self.adjustTitleFont()
return True | This method is where you will rebuild the geometry and \
data for a node.
:param scene <QGraphicsScene> || None
:return <bool> success |
369,635 | def definition_rst(self, definition, spec_path=None):
spec_path = spec_path or self.models_path
definitions = self.spec[spec_path]
definition_property = definitions[definition][].copy()
if not definition_property:
self.write(, self.indent_depth)
return
... | Prepare and write information about definition
:param definition: --name of definition that would be prepared for render
:type definition: str, unicode
:param spec_path: --path to definitions
:type spec_path: str, unicode
:return: |
369,636 | def Write(self, schedule, output_file):
root = ET.Element()
root.attrib[] =
doc = ET.SubElement(root, )
open_tag = ET.SubElement(doc, )
open_tag.text =
self._CreateStopsFolder(schedule, doc)
if self.split_routes:
route_types = set()
for route in schedule.GetRouteList(... | Writes out a feed as KML.
Args:
schedule: A transitfeed.Schedule object containing the feed to write.
output_file: The name of the output KML file, or file object to use. |
369,637 | def save_to_file(filename, content):
import os.path
path = os.path.abspath(filename)
with open(path, "w") as text_file:
text_file.write("{}".format(content)) | Save content to file. Used by node initial contact but
can be used anywhere.
:param str filename: name of file to save to
:param str content: content to save
:return: None
:raises IOError: permissions issue saving, invalid directory, etc |
369,638 | def build_pydot(self, G=None):
import pydot
iamroot = False
if G is None:
G = pydot.Dot(graph_type=, bgcolor=None)
iamroot=True
node = pydot.Node(id(self), shape=, label=self.name)
G.add_node(node)
for child in self.parameters:
... | Build a pydot representation of this model. This needs pydot installed.
Example Usage::
np.random.seed(1000)
X = np.random.normal(0,1,(20,2))
beta = np.random.uniform(0,1,(2,1))
Y = X.dot(beta)
m = RidgeRegression(X, Y)
G = m.build_pydot(... |
369,639 | def peaking(GdB, fc, Q=3.5, fs=44100.):
mu = 10**(GdB/20.)
kq = 4/(1 + mu)*np.tan(2*np.pi*fc/fs/(2*Q))
Cpk = (1 + kq *mu)/(1 + kq)
b1 = -2*np.cos(2*np.pi*fc/fs)/(1 + kq*mu)
b2 = (1 - kq*mu)/(1 + kq*mu)
a1 = -2*np.cos(2*np.pi*fc/fs)/(1 + kq)
a2 = (1 - kq)/(1 + kq)
b = Cpk*np.array([1... | A second-order peaking filter having GdB gain at fc and approximately
and 0 dB otherwise.
The filter coefficients returns correspond to a biquadratic system function
containing five parameters.
Parameters
----------
GdB : Lowpass gain in dB
fc : Center frequency in Hz
Q : Filte... |
369,640 | def create_keypair(self, xml_bytes):
keypair_data = XML(xml_bytes)
key_name = keypair_data.findtext("keyName")
key_fingerprint = keypair_data.findtext("keyFingerprint")
key_material = keypair_data.findtext("keyMaterial")
return model.Keypair(key_name, key_fingerprint, ke... | Parse the XML returned by the C{CreateKeyPair} function.
@param xml_bytes: XML bytes with a C{CreateKeyPairResponse} root
element.
@return: The L{Keypair} instance created. |
369,641 | def signal_optimiser(d, analytes, min_points=5,
threshold_mode=,
threshold_mult=1., x_bias=0,
weights=None, ind=None, mode=):
errmsg =
if isinstance(analytes, str):
analytes = [analytes]
if ind is None:
ind = np.full(... | Optimise data selection based on specified analytes.
Identifies the longest possible contiguous data region in
the signal where the relative standard deviation (std) and
concentration of all analytes is minimised.
Optimisation is performed via a grid search of all possible
contiguous data regions... |
369,642 | def subnet2block(subnet):
if not validate_subnet(subnet):
return None
ip, netmask = subnet.split()
prefix = netmask2prefix(netmask)
network = ip2network(ip)
return _block_from_ip_and_prefix(network, prefix) | Convert a dotted-quad ip address including a netmask into a tuple
containing the network block start and end addresses.
>>> subnet2block('127.0.0.1/255.255.255.255')
('127.0.0.1', '127.0.0.1')
>>> subnet2block('127/255')
('127.0.0.0', '127.255.255.255')
>>> subnet2block('127.0.1/255.255')
... |
369,643 | def process_action(self, raw_user, channel, raw_message):
log.info("%s %s %s", channel, raw_user, raw_message)
if not raw_user:
return
target, message = re.match(
r
self.factory.history.setdefault(
... | Called when a message is received from a channel or user. |
369,644 | def get_pages(parser, token):
try:
tag_name, args = token.contents.split(None, 1)
except ValueError:
var_name =
else:
args = args.split()
if len(args) == 2 and args[0] == :
var_name = args[1]
else:
msg = % tag_name
raise... | Add to context the list of page links.
Usage:
.. code-block:: html+django
{% get_pages %}
This is mostly used for Digg-style pagination.
This call inserts in the template context a *pages* variable, as a sequence
of page links. You can use *pages* in different ways:
- just print *pa... |
369,645 | def do_cleaning(self, arg):
if arg is not None:
if isinstance(arg, list):
newlist = []
for entry in arg:
newlist.append(self.do_cleaning(entry))
return newlist
else:
if sys.version_info[0] < 3:
... | Does the actual cleaning by using the delete methods above.
:param arg: A string, the string which shell be cleaned. Or a list, in which case each of the strings within the
list is cleaned.
:return: A string, the cleaned string. Or a list with cleaned string entries. |
369,646 | def plot_root_to_tip(self, add_internal=False, label=True, ax=None):
Treg = self.setup_TreeRegression()
if self.clock_model and in self.clock_model:
cf = self.clock_model[]
else:
cf = False
Treg.clock_plot(ax=ax, add_internal=add_internal, confidence=cf,... | Plot root-to-tip regression
Parameters
----------
add_internal : bool
If true, plot inte`rnal node positions
label : bool
If true, label the plots
ax : matplotlib axes
If not None, use the provided matplotlib axes to plot the results |
369,647 | def restricted_cover(l, succsOf):
fzl = frozenset(l)
lut = dict()
for i in l:
lut[i] = fzl.intersection(succsOf(i))
return lambda x: lut[x] | Returns a restricted <succsOf> which only takes and yields
values from <l> |
369,648 | def execute(self, context):
hook = GoogleCloudStorageHook(
google_cloud_storage_conn_id=self.google_cloud_storage_conn_id,
delegate_to=self.delegate_to)
hook.upload(
bucket_name=self.bucket,
object_name=self.dst,
mime_type=self.mime_t... | Uploads the file to Google cloud storage |
369,649 | def lipd_read(path):
_j = {}
dir_original = os.getcwd()
try:
print("reading: {}".format(print_filename(path)))
if os.stat(path).st_size > 1000000:
_size = os.stat(path).st_size
print("{} :Thatt need the csv output here.
_j, _csv = get_csv_f... | Loads a LiPD file from local path. Unzip, read, and process data
Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp.
:param str path: Source path
:return none: |
369,650 | def get_seh_chain(self):
seh_chain = list()
try:
process = self.get_process()
seh = self.get_seh_chain_pointer()
while seh != 0xFFFFFFFF:
seh_func = process.read_pointer( seh + 4 )
seh_chain.append( (seh, seh_func) )
... | @rtype: list of tuple( int, int )
@return: List of structured exception handlers.
Each SEH is represented as a tuple of two addresses:
- Address of this SEH block
- Address of the SEH callback function
Do not confuse this with the contents of the SEH bloc... |
369,651 | def memory(self):
if self._memory is not None:
return self._memory
elif self._config is not None:
return self._config.defaultMemory
else:
raise AttributeError("Default value for cannot be determined") | The maximum number of bytes of memory the job will require to run. |
369,652 | def _remove_attributes(attrs, remove_list):
new_attrs = {}
for attr in attrs.keys():
if attr not in remove_list:
new_attrs[attr] = attrs[attr]
return new_attrs | Removes attributes in the remove list from the input attribute dict
:param attrs : Dict of operator attributes
:param remove_list : list of attributes to be removed
:return new_attr : Dict of operator attributes without the listed attributes. |
369,653 | def children(self, unroll=False, skip_not_present=True):
for child_inst in self.inst.children:
if skip_not_present:
if not child_inst.properties.get(, True):
continue
if unroll and isinstance(child_inst, ... | Returns an iterator that provides nodes for all immediate children of
this component.
Parameters
----------
unroll : bool
If True, any children that are arrays are unrolled.
skip_not_present : bool
If True, skips children whose 'ispresent' property is se... |
369,654 | def _findSwipl():
platform = sys.platform[:3]
if platform == "win":
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar":
(path, swiHome) = _findSwiplDar()
... | This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name... |
369,655 | def trt_pmf(matrices):
ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape
pmf = numpy.zeros(ntrts)
for t in range(ntrts):
pmf[t] = 1. - numpy.prod(
[1. - matrices[t, i, j, k, l, m]
for i in range(nmags)
for j in range(ndists)
for k in ra... | Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type |
369,656 | def _get_consumption(self, url, start, end, aggregation):
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
... | Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict |
369,657 | def rankdata(inlist):
n = len(inlist)
svec, ivec = shellsort(inlist)
sumranks = 0
dupcount = 0
newlist = [0] * n
for i in range(n):
sumranks = sumranks + i
dupcount = dupcount + 1
if i == n - 1 or svec[i] != svec[i + 1]:
averank = sumranks / float(dupcoun... | Ranks the data in inlist, dealing with ties appropritely. Assumes
a 1D inlist. Adapted from Gary Perlman's |Stat ranksort.
Usage: rankdata(inlist)
Returns: a list of length equal to inlist, containing rank scores |
369,658 | def load_system_host_keys(self, filename=None):
if filename is None:
filename = os.path.expanduser("~/.ssh/known_hosts")
try:
self._system_host_keys.load(filename)
except IOError:
pass
return
self._syst... | Load host keys from a system (read-only) file. Host keys read with
this method will not be saved back by `save_host_keys`.
This method can be called multiple times. Each new set of host keys
will be merged with the existing set (new replacing old if there are
conflicts).
If `... |
369,659 | def pool_create_event(self, pool_info):
pool_data = pool_info.get()
listeners = pool_data.get()
for listener in listeners:
l_id = listener.get()
l_info = self.neutronclient.show_listener(l_id)
self.listener_create_event(l_info) | Process pool create event.
Extract pool info and get listener info and call next
listen_create_event |
369,660 | def set_config_defaults(args):
defaults = {
: ,
:
}
for key in defaults:
if not args[key]:
args[key] = defaults[key]
return args | Set configuration defaults
:param args: a dict of arguments
:type args: dict
:return: a dict of arguments
:rtype: dict |
369,661 | def synchronize(self, func=None, wait=None, errors=()):
def decorator(func):
@wraps(func)
def outer(*args, **kwargs):
seconds = wait if wait is not None else capybara.default_max_wait_time
def inner():
return func(*args, **kw... | This method is Capybara's primary defense against asynchronicity problems. It works by
attempting to run a given decorated function until it succeeds. The exact behavior of this
method depends on a number of factors. Basically there are certain exceptions which, when
raised from the decorated fu... |
369,662 | def p_select_related_where_statement(self, p):
p[0] = SelectRelatedWhereNode(cardinality=p[2],
variable_name=p[3],
handle=p[6],
navigation_chain=p[7],
... | statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression
| SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression
| SELECT MANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression |
369,663 | def save_data(self, trigger_id, **data):
title, content = super(ServiceTodoist, self).save_data(trigger_id, **data)
if self.token:
if title or content or data.get():
content = title + + content + + data.get()
self.todoist.add_item(content)
... | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean |
369,664 | def from_xml(cls, data, api=None, parser=None):
if parser is None:
if isinstance(data, str):
parser = XML_PARSER_SAX
else:
parser = XML_PARSER_DOM
result = cls(api=api)
if parser == XML_PARSER_DOM:
import xml.etree.Ele... | Create a new instance and load data from xml data or object.
.. note::
If parser is set to None, the functions tries to find the best parse.
By default the SAX parser is chosen if a string is provided as data.
The parser is set to DOM if an xml.etree.ElementTree.Elem... |
369,665 | def get(self,request,*args,**kwargs):
try:
year = int(self.kwargs.get())
except (ValueError, TypeError):
year = getIntFromGet(request,)
kwargs.update({
: year,
: request.GET.get(),
})
if kwargs.get() not in EXPENSE_BASES.... | Allow passing of basis and time limitations |
369,666 | def _sample_chain(args):
n, idx = args
center = sampler.center
np.random.seed((sampler._seed + idx) % np.iinfo(np.int32).max)
pi = np.random.randint(sampler.n_warmup)
prev = sampler.warmup[pi, ]
prev = step(sampler, center, prev - center, 0.95)
n_samples = max(sampler.n_sample... | Sample a single chain for OptGPSampler.
center and n_samples are updated locally and forgotten afterwards. |
369,667 | def watch_log_for(self, exprs, from_mark=None, timeout=600, process=None, verbose=False, filename=):
start = time.time()
tofind = [exprs] if isinstance(exprs, string_types) else exprs
tofind = [re.compile(e) for e in tofind]
matchings = []
reads = ""
if len(tofin... | Watch the log until one or more (regular) expression are found.
This methods when all the expressions have been found or the method
timeouts (a TimeoutError is then raised). On successful completion,
a list of pair (line matched, match object) is returned. |
369,668 | def get_chain_details_by_related_pdb_chains(self, pdb_id, chain_id, pfam_accs):
if not pfam_accs:
return None
associated_pdb_chains = set()
pfam_api = self.get_pfam_api()
for pfam_acc in pfam_accs:
associated_pdb_chains = associated_pdb_chains.union(pfa... | Returns a dict of SCOPe details using info
This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned.
If there are SCOPe entries for the associated Pfam accession numbers which agree then this function returns
pretty compl... |
369,669 | def conv_cy(self, cy_cl):
if not isinstance(cy_cl, PrefixedUnit):
cy_cl = PrefixedUnit(cy_cl, , )
clock = self.machine[]
element_size = self.kernel.datatypes_size[self.kernel.datatype]
elements_per_cacheline = int(self.machine[]) // element_size
it_s = clock/... | Convert cycles (cy/CL) to other units, such as FLOP/s or It/s. |
369,670 | def by_interval_lookup(self, style_key, style_value):
style_attr = style_key if self.style_types[style_key] is bool else None
intervals = style_value["interval"]
def proc(value, result):
try:
value = float(value)
except TypeError:
... | Return a processor for an "interval" style value.
Parameters
----------
style_key : str
A style key.
style_value : dict
A dictionary with an "interval" key whose value consists of a
sequence of tuples where each tuple should have the form `(start,
... |
369,671 | def check_call(state, callstr, argstr=None, expand_msg=None):
state.assert_is(
["function_defs", "lambda_functions"],
"check_call",
["check_function_def", "check_lambda_function"],
)
if expand_msg is None:
expand_msg = "To verify it, we reran {{argstr}}. "
stu_par... | When checking a function definition of lambda function,
prepare has_equal_x for checking the call of a user-defined function.
Args:
callstr (str): call string that specifies how the function should be called, e.g. `f(1, a = 2)`.
``check_call()`` will replace ``f`` with the function/lambda yo... |
369,672 | def response(status, description, resource=DefaultResource):
def inner(o):
value = Response(status, description, resource)
try:
getattr(o, ).add(value)
except AttributeError:
setattr(o, , {value})
return o
return inner | Define an expected response.
The values are based off `Swagger <https://swagger.io/specification>`_. |
369,673 | def parse_subscription(self, params, region, subscription):
topic_arn = subscription.pop()
topic_name = topic_arn.split()[-1]
if topic_name in self.topics:
topic = self.topics[topic_name]
manage_dictionary(topic[], , {})
protocol = subscription.pop()
... | Parse a single subscription and reference it in its corresponding topic
:param params: Global parameters (defaults to {})
:param subscription: SNS Subscription |
369,674 | def escape(s):
if hasattr(s, ):
return s.__html__()
return Markup(text_type(s)
.replace(, )
.replace(, )
.replace(, )
.replace("&
) | Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string. |
369,675 | def openParametersDialog(params, title=None):
QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))
dlg = ParametersDialog(params, title)
dlg.exec_()
QApplication.restoreOverrideCursor()
return dlg.values | Opens a dialog to enter parameters.
Parameters are passed as a list of Parameter objects
Returns a dict with param names as keys and param values as values
Returns None if the dialog was cancelled |
369,676 | def _init_steps(self,):
self._check_old_yaml_format()
config_steps = self.flow_config.steps
self._check_infinite_flows(config_steps)
steps = []
for number, step_config in config_steps.items():
specs = self._visit_step(number, step_config)
steps.... | Given the flow config and everything else, create a list of steps to run, sorted by step number.
:return: List[StepSpec] |
369,677 | def cmd_export_all(*args):
(output_dir, quality, page_format) = _get_export_params(args)
dsearch = get_docsearch()
try:
os.mkdir(output_dir)
except FileExistsError:
pass
out = []
docs = [d for d in dsearch.docs]
docs.sort(key=lambda doc: doc.docid)
output_dir =... | Arguments:
<output folder> [-- [--quality <0-100>] [--page_format <page_format>]]
Export all documents as PDF files.
Default quality is 50.
Default page format is A4.
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
"reason": "xxxx", "... |
369,678 | def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
local_buffer = utils.BytearrayStream()
if self._maximum_items:
self._maximum_items.write(local_buffer, kmip_version=kmip_version)
if self._offset_items:
self._offset_items.write(local_buff... | Write the data encoding the Locate request payload to a buffer.
Args:
output_buffer (stream): A data buffer in which to encode object
data, supporting a write method.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the obje... |
369,679 | def clean_key(self):
key = self.cleaned_data["key"]
gpg = get_gpg()
result = gpg.import_keys(key)
if result.count == 0:
raise forms.ValidationError(_("Invalid Key"))
return key | Validate the key contains an email address. |
369,680 | def subscribe(self, user_token, topic):
response = _request(,
url=self.url_v1( + topic),
user_agent=self.user_agent,
user_token=user_token,
)
_raise_for_status(response) | Subscribe a user to the given topic.
:param str user_token: The token of the user.
:param str topic: The topic.
:raises `requests.exceptions.HTTPError`: If an HTTP error occurred. |
369,681 | def _compile(self, compile_request):
try:
argv = self._make_compile_argv(compile_request)
except self._HeaderOnlyLibrary:
self.context.log.debug(.format(compile_request))
return
compiler = compile_request.compiler
output_dir = compile_request.output_dir
env = compiler.invoca... | Perform the process of compilation, writing object files to the request's 'output_dir'.
NB: This method must arrange the output files so that `collect_cached_objects()` can collect all
of the results (or vice versa)! |
369,682 | def serialize_transaction(inputs, outputs, lock_time=0, version=1):
serialized_inputs = .join([serialize_input(input) for input in inputs])
serialized_outputs = .join([serialize_output(output) for output in outputs])
return .join([
hexlify(struct.pack(, version)),
... | Serializes a transaction. |
369,683 | def has_colors(stream):
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
return False | Determine if the terminal supports ansi colors. |
369,684 | def rnoncentral_t(mu, lam, nu, size=None):
tau = rgamma(nu / 2., nu / (2. * lam), size)
return rnormal(mu, tau) | Non-central Student's t random variates. |
369,685 | def show_stories(self, raw=False, limit=None):
show_stories = self._get_stories(, limit)
if raw:
show_stories = [story.raw for story in show_stories]
return show_stories | Returns list of item ids of latest Show HN stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to transform all
objects into raw json.
Returns:
`list` object containing ids of Show HN storie... |
369,686 | def clean_video_data(_data):
data = _data.copy()
title = data.get()
if title:
data[] = clean_title(title)
return data | Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data. |
369,687 | def RemoveNIC(self,network_id):
return(
clc.v2.Requests(
clc.v2.API.Call(,
% (self.alias,self.id,network_id),
session=self.session),
alias=self.alias,
session=self.session
)) | Remove the NIC associated with the provided network from the server.
https://www.ctl.io/api-docs/v2/#servers-remove-secondary-network
network_id - ID associated with the network to remove
>>> network = clc.v2.Networks(location="VA1").Get("10.128.166.0/24")
>>> clc.v2.Server(alias='BTDI',id='WA1BT... |
369,688 | def autosave(self, index):
finfo = self.stack.data[index]
document = finfo.editor.document()
if not document.changed_since_autosave or finfo.newly_created:
return
autosave_filename = self.get_autosave_filename(finfo.filename)
logger.debug(, finfo.filename, au... | Autosave a file.
Do nothing if the `changed_since_autosave` flag is not set or the file
is newly created (and thus not named by the user). Otherwise, save a
copy of the file with the name given by `self.get_autosave_filename()`
and clear the `changed_since_autosave` flag. Errors raised ... |
369,689 | def connect(self, nice_quit_ev):
_logger.debug("Connecting to discovered node: [%s]", self.server_host)
stop_epoch = time.time() + \
nsq.config.client.MAXIMUM_CONNECT_ATTEMPT_PERIOD_S
timeout_s = nsq.config.client.INITIAL_CONNECT_FAIL_WAIT_S
backoff_r... | Connect the server. We expect this to implement backoff and all
connection logistics for servers that were discovered via a lookup
node. |
369,690 | def docgraph2freqt(docgraph, root=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
if root is None:
return u"\n".join(
sentence2freqt(docgraph, sentence, include_pos=include_pos,
escape_func=escape_func)
for sentence in docgr... | convert a docgraph into a FREQT string. |
369,691 | def runStickyEregressions(infile_name,interval_size,meas_err,sticky,all_specs):
S A JOKE, FUTURE REFEREES.
interval_size : int
Number of periods in each sub-interval.
meas_err : bool
Indicator for whether to add measurement error to DeltaLogC.
sticky : bool
Indicator for whether ... | Runs regressions for the main tables of the StickyC paper and produces a LaTeX
table with results for one "panel".
Parameters
----------
infile_name : str
Name of tab-delimited text file with simulation data. Assumed to be in
the results directory, and was almost surely generated by ma... |
369,692 | def name(self):
return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self))) | Return the complete file and path name of the file. |
369,693 | def _deprecated_kwargs(kwargs, arg_newarg):
warn_for = []
for (arg, new_kw) in arg_newarg:
if arg in kwargs.keys():
val = kwargs.pop(arg)
kwargs[new_kw] = val
warn_for.append((arg, new_kw))
if len(warn_for) > 0:
if len(warn_for) == 1:
warn... | arg_newarg is a list of tuples, where each tuple has a pair of strings.
('old_arg', 'new_arg')
A DeprecationWarning is raised for the arguments that need to be
replaced. |
369,694 | def load(self, languages=[]):
duckling_load = self.clojure.var("duckling.core", "load!")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
clojure_list = self.clojure.var("clojure.core", "list")
if languages:
clojure_list.invoke(*is... | Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"]) |
369,695 | def name(function):
if isinstance(function, types.FunctionType):
return function.__name__
else:
return str(function) | Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name |
369,696 | def list_nodes_select(call=None):
if not call:
call =
if not get_configured_provider():
return
info = [, , , , , , ]
return salt.utils.cloud.list_nodes_select(
list_nodes_full(call=),
__opts__.get(, info), call) | Return a list of the VMs that are on the provider, with select fields |
369,697 | def rating(self, value):
self._rating = value
self._thumb = self._link_to_img() | Set the rating parameter and regenerate the thumbnail link. |
369,698 | def get_default_params(type=):
p = Parameters()
type = type.upper()
p.Metric =
p.NumberOfHistogramBins = 32
p.ImageSampler =
p.NumberOfSpatialSamples = 2048
p.NewSamplesEveryIteration = True
p.NumberOf... | get_default_params(type='BSPLINE')
Get `Parameters` struct with parameters that users may want to tweak.
The given `type` specifies the type of allowed transform, and can
be 'RIGID', 'AFFINE', 'BSPLINE'.
For detail on what parameters are available and how they should be used,
we refer to t... |
369,699 | def parse_delay_import_directory(self, rva, size):
import_descs = []
while True:
try:
data = self.get_data( rva, Structure(self.__IMAGE_DELAY_IMPORT_DESCRIPTOR_format__).sizeof() )
except PEFormatError, e:
... | Walk and parse the delay import directory. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.