Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
381,000 | def to_string(x):
if isinstance(x, bytes):
return x.decode()
if isinstance(x, basestring):
return x | Utf8 conversion
:param x:
:return: |
381,001 | def cache_from_source(path, debug_override=None):
debug = not sys.flags.optimize if debug_override is None else debug_override
if debug:
suffixes = DEBUG_BYTECODE_SUFFIXES
else:
suffixes = OPTIMIZED_BYTECODE_SUFFIXES
pass
head, tail = os.path.split(path)
base_filename, s... | Given the path to a .py file, return the path to its .pyc/.pyo file.
The .py file does not need to exist; this simply returns the path to the
.pyc/.pyo file calculated as if the .py file were imported. The extension
will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo.
If debug_ov... |
381,002 | def Parse(self,url,song_name,flag):
file_download=FileDownload()
html=file_download.get_html_response(url)
if flag == False:
soup=BeautifulSoup(html)
a_list=soup.findAll(,)
text=[str(x) for x in a_list]
text=.join(text)
text=text.lower()
string1=
string2=
string3=
href=
if st... | It will the resource URL if song is found,
Otherwise it will return the list of songs that can be downloaded |
381,003 | def get_file_link(self, file_key):
self._raise_unimplemented_error()
uri = .join([self.api_uri,
self.files_suffix,
file_key,
self.file_link_suffix,
])
return self._req(, uri) | Gets link to file
Args:
file_key key for the file
return (status code, ?) |
381,004 | def check_exc_info(self, node):
if self.current_logging_level not in (, ):
return
for kw in node.keywords:
if kw.arg == :
if self.current_logging_level == :
violation = ERROR_EXC_INFO_VIOLATION
else:
... | Reports a violation if exc_info keyword is used with logging.error or logging.exception. |
381,005 | def rm_parameter(self, name):
if name not in self._parameters:
raise ValueError("no parameter found" % (name))
del self._parameters[name]
del self.__dict__[name] | Removes a parameter to the existing Datamat.
Fails if parameter doesn't exist. |
381,006 | def scale_subplots(subplots=None, xlim=, ylim=):
auto_axis =
if xlim == :
auto_axis +=
if ylim == :
auto_axis +=
autoscale_subplots(subplots, auto_axis)
for loc, ax in numpy.ndenumerate(subplots):
if not in auto_axis:
ax.set_xlim(xlim)
if not i... | Set the x and y axis limits for a collection of subplots.
Parameters
-----------
subplots : ndarray or list of matplotlib.axes.Axes
xlim : None | 'auto' | (xmin, xmax)
'auto' : sets the limits according to the most
extreme values of data encountered.
ylim : None | 'auto' | (ymin, y... |
381,007 | def build_modules(is_training, vocab_size):
if is_training:
estimator_mode = tf.constant(bbb.EstimatorModes.sample)
else:
estimator_mode = tf.constant(bbb.EstimatorModes.mean)
lstm_bbb_custom_getter = bbb.bayes_by_backprop_getter(
posterior_builder=lstm_posterior_builder,
prior_builder=... | Construct the modules used in the graph. |
381,008 | def visitArrayExpr(self, ctx: jsgParser.ArrayExprContext):
from pyjsg.parser_impl.jsg_ebnf_parser import JSGEbnf
from pyjsg.parser_impl.jsg_valuetype_parser import JSGValueType
self._types = [JSGValueType(self._context, vt) for vt in ctx.valueType()]
if ctx.ebnfSuffix():
... | arrayExpr: OBRACKET valueType (BAR valueType)* ebnfSuffix? CBRACKET; |
381,009 | def send_s3_xsd(self, url_xsd):
if self.check_s3(self.domain, urlparse(url_xsd).path[1:]):
return url_xsd
response = urllib2.urlopen(url_xsd)
content = response.read()
cached = NamedTemporaryFile(delete=False)
named = cached.name
urls =... | This method will not be re-run always, only locally and when xsd
are regenerated, read the test_008_force_s3_creation on test folder |
381,010 | def _add_references(self, rec):
for ref in self.document.getElementsByTagName():
for ref_type, doi, authors, collaboration, journal, volume, page, year,\
label, arxiv, publisher, institution, unstructured_text,\
external_link, report_no, editors in se... | Adds the reference to the record |
381,011 | def log_loss(oracle, test_seq, ab=[], m_order=None, verbose=False):
if not ab:
ab = oracle.get_alphabet()
if verbose:
print()
logP = 0.0
context = []
increment = np.floor((len(test_seq) - 1) / 100)
bar_count = -1
maxContextLength = 0
avgContext = 0
for i, t in ... | Evaluate the average log-loss of a sequence given an oracle |
381,012 | def _sort_resources_per_hosting_device(resources):
hosting_devices = {}
for key in resources.keys():
for r in resources.get(key) or []:
if r.get() is None:
continue
hd_id = r[][]
hosting_devices.setdefault(hd_id, {}... | This function will sort the resources on hosting device.
The sorting on hosting device is done by looking up the
`hosting_device` attribute of the resource, and its `id`.
:param resources: a dict with key of resource name
:return dict sorted on the hosting device of input resource. For... |
381,013 | def stop(self):
unit, start_instant, size = self
year, month, day = start_instant
if unit == ETERNITY:
return Instant((float("inf"), float("inf"), float("inf")))
if unit == :
if size > 1:
day += size - 1
month_last_day = ca... | Return the last day of the period as an Instant instance.
>>> period('year', 2014).stop
Instant((2014, 12, 31))
>>> period('month', 2014).stop
Instant((2014, 12, 31))
>>> period('day', 2014).stop
Instant((2014, 12, 31))
>>> period('year', '2012-2-29').stop
... |
381,014 | def brightness(im):
im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(im_hsv)
height, weight = v.shape[:2]
total_bright = 0
for i in v:
total_bright = total_bright+sum(i)
return float(total_bright)/(height*weight) | Return the brightness of an image
Args:
im(numpy): image
Returns:
float, average brightness of an image |
381,015 | def complete_extra(self, args):
"Completions for the command."
if len(args) == 0:
return self._listdir()
return self._complete_path(args[-1]) | Completions for the 'extra' command. |
381,016 | def setEditorData( self, editor, value ):
if ( isinstance(editor, XMultiTagEdit) ):
if ( not isinstance(value, list) ):
value = [nativestring(value)]
else:
value = map(nativestring, value)
editor... | Sets the value for the given editor to the inputed value.
:param editor | <QWidget>
value | <variant> |
381,017 | def strfdelta(tdelta: Union[datetime.timedelta, int, float, str],
fmt=,
inputtype=):
if inputtype == :
remainder = int(tdelta.total_seconds())
elif inputtype in [, ]:
remainder = int(tdelta)
elif inputtype in [, ]:
remainder = int(tdelta) * 60... | Convert a ``datetime.timedelta`` object or a regular number to a custom-
formatted string, just like the ``strftime()`` method does for
``datetime.datetime`` objects.
The ``fmt`` argument allows custom formatting to be specified. Fields can
include ``seconds``, ``minutes``, ``hours``, ``days``, and ``w... |
381,018 | def components(self):
from pandas import DataFrame
columns = [, , , ,
, , ]
hasnans = self._hasnans
if hasnans:
def f(x):
if isna(x):
return [np.nan] * len(columns)
return x.components
el... | Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame |
381,019 | def _structure_frozenset(self, obj, cl):
if is_bare(cl) or cl.__args__[0] is Any:
return frozenset(obj)
else:
elem_type = cl.__args__[0]
dispatch = self._structure_func.dispatch
return frozenset(dispatch(elem_type)(e, elem_type) for e in obj) | Convert an iterable into a potentially generic frozenset. |
381,020 | def _handle_msg(self, msg):
LOG.debug(, self._remotename, msg)
if msg.type == BGP_MSG_OPEN:
if self.state == BGP_FSM_OPEN_SENT:
self._validate_open_msg(msg)
self.recv_open_msg = msg
self.state = BGP_FSM_OPEN_... | When a BGP message is received, send it to peer.
Open messages are validated here. Peer handler is called to handle each
message except for *Open* and *Notification* message. On receiving
*Notification* message we close connection with peer. |
381,021 | def add_fs(self, name, fs, write=False, priority=0):
if isinstance(fs, text_type):
fs = open_fs(fs)
if not isinstance(fs, FS):
raise TypeError("fs argument should be an FS object or FS URL")
self._filesystems[name] = _PrioritizedFS(
priorit... | Add a filesystem to the MultiFS.
Arguments:
name (str): A unique name to refer to the filesystem being
added.
fs (FS or str): The filesystem (instance or URL) to add.
write (bool): If this value is True, then the ``fs`` will
be used as the wri... |
381,022 | def remove_ip(enode, portlbl, addr, shell=None):
assert portlbl
assert ip_interface(addr)
port = enode.ports[portlbl]
cmd = .format(addr=addr, port=port)
response = enode(cmd, shell=shell)
assert not response | Remove an IP address from an interface.
All parameters left as ``None`` are ignored and thus no configuration
action is taken for that parameter (left "as-is").
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param str portlbl: Port label to configure.... |
381,023 | def send(self, target, nick, msg, msgtype, ignore_length=False, filters=None):
if not isinstance(msg, str):
raise Exception("Trying to send a %s to irc, only strings allowed." % type(msg).__name__)
if filters is None:
filters = self.outputfilter[target]
for i in ... | Send a message.
Records the message in the log. |
381,024 | def policy_present(name, rules):
url = "v1/sys/policy/{0}".format(name)
response = __utils__[](, url)
try:
if response.status_code == 200:
return _handle_existing_policy(name, rules, response.json()[])
elif response.status_code == 404:
return _create_new_policy(n... | Ensure a Vault policy with the given name and rules is present.
name
The name of the policy
rules
Rules formatted as in-line HCL
.. code-block:: yaml
demo-policy:
vault.policy_present:
- name: foo/bar
- rules: |
path "secret/top-... |
381,025 | def plot_di(fignum, DIblock):
global globals
X_down, X_up, Y_down, Y_up = [], [], [], []
plt.figure(num=fignum)
for rec in DIblock:
Up, Down = 0, 0
XY = pmag.dimap(rec[0], rec[1])
if rec[1] >= 0:
X_down.append(XY[0])
Y_down.append(XY[1])
... | plots directions on equal area net
Parameters
_________
fignum : matplotlib figure number
DIblock : nested list of dec, inc pairs |
381,026 | def get_current_span():
context = RequestContextManager.current_context()
if context is not None:
return context.span
active = opentracing.tracer.scope_manager.active
return active.span if active else None | Access current request context and extract current Span from it.
:return:
Return current span associated with the current request context.
If no request context is present in thread local, or the context
has no span, return None. |
381,027 | def emotes(self, emotes):
if emotes is None:
self._emotes = []
return
es = []
for estr in emotes.split():
es.append(Emote.from_str(estr))
self._emotes = es | Set the emotes
:param emotes: the key of the emotes tag
:type emotes: :class:`str`
:returns: None
:rtype: None
:raises: None |
381,028 | def name(self) -> str:
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | OpenSSL uses a different naming convention than the corresponding RFCs. |
381,029 | def show_user(self, user):
url = % (user)
d = defer.Deferred()
self.__downloadPage(url, txml.Users(lambda u: d.callback(u))) \
.addErrback(lambda e: d.errback(e))
return d | Get the info for a specific user.
Returns a delegate that will receive the user in a callback. |
381,030 | def get_i_name(self, num, is_oai=None):
if num not in (1, 2):
raise ValueError("`num` parameter have to be 1 or 2!")
if is_oai is None:
is_oai = self.oai_marc
i_name = "ind" if not is_oai else "i"
return i_name + str(num) | This method is used mainly internally, but it can be handy if you work
with with raw MARC XML object and not using getters.
Args:
num (int): Which indicator you need (1/2).
is_oai (bool/None): If None, :attr:`.oai_marc` is
used.
Returns:
s... |
381,031 | def scan(repos, options):
ignore_set = set()
repos = repos[::-1]
while repos:
directory, dotdir = repos.pop()
ignore_this = any(pat in directory for pat in options.ignore_patterns)
if ignore_this:
if options.verbose:
output(b % directory)
... | Given a repository list [(path, vcsname), ...], scan each of them. |
381,032 | def train_with_graph(p_graph, qp_pairs, dev_qp_pairs):
global sess
with tf.Graph().as_default():
train_model = GAG(cfg, embed, p_graph)
train_model.build_net(is_training=True)
tf.get_variable_scope().reuse_variables()
dev_model = GAG(cfg, embed, p_graph)
dev_model.bu... | Train a network from a specific graph. |
381,033 | def construct_routes(self):
modules = self.evernode_app.get_modules()
for module_name in modules:
with self.app.app_context():
module = importlib.import_module(
% (module_name))
for route in module.routes:
... | Gets modules routes.py and converts to module imports |
381,034 | def object_clean(self):
for sample in self.metadata:
try:
delattr(sample[self.analysistype], )
delattr(sample[self.analysistype], )
delattr(sample[self.analysistype], )
delattr(sample[self.analysistype], )
delat... | Remove large attributes from the metadata objects |
381,035 | def get_key(dotenv_path, key_to_get, verbose=False):
key_to_get = str(key_to_get)
if not os.path.exists(dotenv_path):
if verbose:
warnings.warn(f"Cant exist.")
return None
dotenv_as_dict = dotenv_values(dotenv_path)
if key_to_get in dotenv_as_dict:
return dotenv_... | Gets the value of a given key from the given .env
If the .env path given doesn't exist, fails
:param dotenv_path: path
:param key_to_get: key
:param verbose: verbosity flag, raise warning if path does not exist
:return: value of variable from environment file or None |
381,036 | def create_from_xml(resultFile, resultElem, columns=None,
all_columns=False, columns_relevant_for_diff=set()):
attributes = RunSetResult._extract_attributes_from_result(resultFile, resultElem)
if not columns:
columns = RunSetResult._extract_existing_columns_... | This function extracts everything necessary for creating a RunSetResult object
from the "result" XML tag of a benchmark result file.
It returns a RunSetResult object, which is not yet fully initialized.
To finish initializing the object, call collect_data()
before using it for anything e... |
381,037 | def plot2dhist(xdata,ydata,cmap=,interpolation=,
fig=None,logscale=True,xbins=None,ybins=None,
nbins=50,pts_only=False,**kwargs):
setfig(fig)
if pts_only:
plt.plot(xdata,ydata,**kwargs)
return
ok = (~np.isnan(xdata) & ~np.isnan(ydata) &
~np.is... | Plots a 2d density histogram of provided data
:param xdata,ydata: (array-like)
Data to plot.
:param cmap: (optional)
Colormap to use for density plot.
:param interpolation: (optional)
Interpolation scheme for display (passed to ``plt.imshow``).
:param fig: (optional)
... |
381,038 | def update_dns_server(self, service_name, deployment_name, dns_server_name, address):
_validate_not_none(, service_name)
_validate_not_none(, deployment_name)
_validate_not_none(, dns_server_name)
_validate_not_none(, address)
return self._perform_put(
self._... | Updates the ip address of a DNS server.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
dns_server_name:
Specifies the name of the DNS server.
address:
Specifies the IP address of the DNS server. |
381,039 | def _get_curvature(nodes, tangent_vec, s):
r
_, num_nodes = np.shape(nodes)
if num_nodes == 2:
return 0.0
first_deriv = nodes[:, 1:] - nodes[:, :-1]
second_deriv = first_deriv[:, 1:] - first_deriv[:, :-1]
concavity = (
(num_nodes - 1)
* (num_nodes - 2)
* e... | r"""Compute the signed curvature of a curve at :math:`s`.
Computed via
.. math::
\frac{B'(s) \times B''(s)}{\left\lVert B'(s) \right\rVert_2^3}
.. image:: ../images/get_curvature.png
:align: center
.. testsetup:: get-curvature
import numpy as np
import bezier
fro... |
381,040 | def _getTransformation(self):
CheckParent(self)
val = _fitz.Page__getTransformation(self)
val = Matrix(val)
return val | _getTransformation(self) -> PyObject * |
381,041 | def from_mask(cls, dh_mask, lwin, nwin=None, weights=None):
if nwin is None:
nwin = (lwin + 1)**2
else:
if nwin > (lwin + 1)**2:
raise ValueError( +
.format(lwin, nwin))
if dh_mas... | Construct localization windows that are optimally concentrated within
the region specified by a mask.
Usage
-----
x = SHWindow.from_mask(dh_mask, lwin, [nwin, weights])
Returns
-------
x : SHWindow class instance
Parameters
----------
dh... |
381,042 | def server_sends_binary(self, message, name=None, connection=None, label=None):
server, name = self._servers.get_with_name(name)
server.send(message, alias=connection)
self._register_send(server, label, name, connection=connection) | Send raw binary `message`.
If server `name` is not given, uses the latest server. Optional message
`label` is shown on logs.
Examples:
| Server sends binary | Hello! |
| Server sends binary | ${some binary} | Server1 | label=DebugMessage |
| Server sends binary | ${some... |
381,043 | async def sinter(self, keys, *args):
"Return the intersection of sets specified by ``keys``"
args = list_or_args(keys, args)
return await self.execute_command(, *args) | Return the intersection of sets specified by ``keys`` |
381,044 | def leaders_in(self, leaderboard_name, current_page, **options):
if current_page < 1:
current_page = 1
page_size = options.get(, self.page_size)
index_for_redis = current_page - 1
starting_offset = (index_for_redis * page_size)
if starting_offset < 0:
... | Retrieve a page of leaders from the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param current_page [int] Page to retrieve from the named leaderboard.
@param options [Hash] Options to be used when retrieving the page from the named leaderboard.
@return a... |
381,045 | def load_json(file):
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, file)) as jfile:
data = json.load(jfile)
return data | Load JSON file at app start |
381,046 | def _clean_record(self, record):
for k, v in dict(record).items():
if isinstance(v, dict):
v = self._clean_record(v)
if v is None:
record.pop(k)
return record | Remove all fields with `None` values |
381,047 | def getAllAnnotationSets(self):
for variantSet in self.getAllVariantSets():
iterator = self._client.search_variant_annotation_sets(
variant_set_id=variantSet.id)
for variantAnnotationSet in iterator:
yield variantAnnotationSet | Returns all variant annotation sets on the server. |
381,048 | def config(self, averaging=1, datarate=15, mode=MODE_NORMAL):
averaging_conf = {
1: 0,
2: 1,
4: 2,
8: 3
}
if averaging not in averaging_conf.keys():
raise Exception()
datarates = {
0.75: 0,
1.5:... | Set the base config for sensor
:param averaging: Sets the numer of samples that are internally averaged
:param datarate: Datarate in hertz
:param mode: one of the MODE_* constants |
381,049 | def show_top_losses(self, k:int, max_len:int=70)->None:
from IPython.display import display, HTML
items = []
tl_val,tl_idx = self.top_losses()
for i,idx in enumerate(tl_idx):
if k <= 0: break
k -= 1
tx,cl = self.data.dl(self.ds_type).dataset[i... | Create a tabulation showing the first `k` texts in top_losses along with their prediction, actual,loss, and probability of
actual class. `max_len` is the maximum number of tokens displayed. |
381,050 | def _edges_replaced(self, object, name, old, new):
self._delete_edges(old)
self._add_edges(new) | Handles a list of edges being set. |
381,051 | def add_data(self, id, key, value):
self[str(id)][].setdefault(key, [])
self[str(id)][][key].append(value) | Add new data item.
:param str id: Entry id within ``SDfile``.
:param str key: Data item key.
:param str value: Data item value.
:return: None.
:rtype: :py:obj:`None`. |
381,052 | def most_even_chunk(string, group):
counts = [0] + most_even(len(string), group)
indices = accumulate(counts)
slices = window(indices, 2)
return [string[slice(*one)] for one in slices] | Divide a string into a list of strings as even as possible. |
381,053 | def in_domain(self, points):
return all([
domain.in_domain(array)
for domain, array in
zip(self._domains, separate_struct_array(points, self._dtypes))
]) | Returns ``True`` if all of the given points are in the domain,
``False`` otherwise.
:param np.ndarray points: An `np.ndarray` of type `self.dtype`.
:rtype: `bool` |
381,054 | def vertical_gradient(self, x0, y0, x1, y1, start, end):
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
grad = gradient_list(start, end, y1 - y0)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
self.point(x, y, grad[y - y0]) | Draw a vertical gradient |
381,055 | def shuffle_step(entries, step):
answer = []
for i in range(0, len(entries), step):
sub = entries[i:i+step]
shuffle(sub)
answer += sub
return answer | Shuffle the step |
381,056 | def paste_buffer(pymux, variables):
pane = pymux.arrangement.get_active_pane()
pane.process.write_input(get_app().clipboard.get_data().text, paste=True) | Paste clipboard content into buffer. |
381,057 | def _default_return_columns(self):
return_columns = []
parsed_expr = []
for key, value in self.components._namespace.items():
if hasattr(self.components, value):
sig = signature(getattr(self.components, value))
if len(set(sig... | Return a list of the model elements that does not include lookup functions
or other functions that take parameters. |
381,058 | def update_record(self, name, new_data, condition, update_only=False,
debug=False):
self.df[] = list(range(len(self.df)))
df_data = self.df
condition2 = (df_data.index == name)
if len(df_data[condition & condition2]) > 0:
... | Find the first row in self.df with index == name
and condition == True.
Update that record with new_data, then delete any
additional records where index == name and condition == True.
Change is inplace |
381,059 | def pipe():
r, w = os.pipe()
return File.fromfd(r, ), File.fromfd(w, ) | create an inter-process communication pipe
:returns:
a pair of :class:`File` objects ``(read, write)`` for the two ends of
the pipe |
381,060 | def start_session(self):
if self.has_active_session():
raise Exception("Session already in progress.")
response = requests.post(self._get_login_url(),
headers=self._get_login_headers(),
data=self._get_login_xml())
... | Starts a Salesforce session and determines which SF instance to use for future requests. |
381,061 | def get_sql_type(self, instance, counter_name):
with self.get_managed_cursor(instance, self.DEFAULT_DB_KEY) as cursor:
cursor.execute(COUNTER_TYPE_QUERY, (counter_name,))
(sql_type,) = cursor.fetchone()
if sql_type == PERF_LARGE_RAW_BASE:
self.log.war... | Return the type of the performance counter so that we can report it to
Datadog correctly
If the sql_type is one that needs a base (PERF_RAW_LARGE_FRACTION and
PERF_AVERAGE_BULK), the name of the base counter will also be returned |
381,062 | def route(**kwargs):
def routed(request, *args2, **kwargs2):
method = request.method
if method in kwargs:
req_method = kwargs[method]
return req_method(request, *args2, **kwargs2)
elif in kwargs:
return kwargs[](request, *args2, **kwargs2)
el... | Route a request to different views based on http verb.
Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE',
where the first four map to a view to route to for that type of
request method/verb, and 'ELSE' maps to a view to pass the request
to if the given request method/verb was not specified. |
381,063 | def sample_initial(self, nlive=500, update_interval=None,
first_update=None, maxiter=None, maxcall=None,
logl_max=np.inf, dlogz=0.01, live_points=None):
if maxcall is None:
maxcall = sys.maxsize
if maxiter is None:
... | Generate a series of initial samples from a nested sampling
run using a fixed number of live points using an internal
sampler from :mod:`~dynesty.nestedsamplers`. Instantiates a
generator that will be called by the user.
Parameters
----------
nlive : int, optional
... |
381,064 | def fromid(self, item_id):
if not item_id:
raise Exception()
soup = get_item_soup(item_id)
story_id = item_id
rank = -1
info_table = soup.findChildren()[2]
info_rows = info_table.findChildren()
... | Initializes an instance of Story for given item_id.
It is assumed that the story referenced by item_id is valid
and does not raise any HTTP errors.
item_id is an int. |
381,065 | def main(arguments=None):
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="DEBUG",
options_first=False,
projectName="tastic"
)
arguments, settings, log, dbConn = su.setup()
for arg, val in arguments.iteritems():
if arg[0] ... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* |
381,066 | def intervalAdd(self, a, b, val):
self.add(a, +val)
self.add(b + 1, -val) | Variant, adds val to t[a], to t[a + 1] ... and to t[b]
:param int a b: with 1 <= a <= b |
381,067 | def check_can_approve(self, request, application, roles):
try:
authorised_persons = self.get_authorised_persons(application)
authorised_persons.get(pk=request.user.pk)
return True
except Person.DoesNotExist:
return False | Check the person's authorization. |
381,068 | def get_bundle(self, bundle_id=None):
if bundle_id is None:
return self.__bundle
elif isinstance(bundle_id, Bundle):
bundle_id = bundle_id.get_bundle_id()
return self.__framework.get_bundle_by_id(bundle_id) | Retrieves the :class:`~pelix.framework.Bundle` object for the bundle
matching the given ID (int). If no ID is given (None), the bundle
associated to this context is returned.
:param bundle_id: A bundle ID (optional)
:return: The requested :class:`~pelix.framework.Bundle` object
... |
381,069 | def disable(self, name=None):
if name is None:
for name in self._actions_dict:
self.disable(name)
return
self._actions_dict[name].qaction.setEnabled(False) | Disable one or all actions. |
381,070 | def _get_results(self, page):
soup = _get_soup(page)
details = soup.find_all("tr", class_="odd")
even = soup.find_all("tr", class_="even")
for i in range(len(even)):
details.insert((i * 2)+1, even[i])
return self._parse_details(details) | Find every div tag containing torrent details on given page,
then parse the results into a list of Torrents and return them |
381,071 | def rowsBeforeRow(self, rowObject, count):
webID = rowObject[]
return self.rowsBeforeItem(
self.webTranslator.fromWebID(webID),
count) | Wrapper around L{rowsBeforeItem} which accepts the web ID for a item
instead of the item itself.
@param rowObject: a dictionary mapping strings to column values, sent
from the client. One of those column values must be C{__id__} to
uniquely identify a row.
@param count: an int... |
381,072 | def request(schema):
def wrapper(func):
setattr(func, REQUEST, schema)
return func
return wrapper | Decorate a function with a request schema. |
381,073 | def _discarded_reads2_out_file_name(self):
if self.Parameters[].isOn():
discarded_reads2 = self._absolute(str(self.Parameters[].Value))
else:
raise ValueError(
"No discarded-reads2 (flag -4) output path specified")
return discarded_reads2 | Checks if file name is set for discarded reads2 output.
Returns absolute path. |
381,074 | def paste(location):
copyData = settings.getDataFile()
if not location:
location = "."
try:
data = pickle.load(open(copyData, "rb"))
speech.speak("Pasting " + data["copyLocation"] + " to current directory.")
except:
speech.fail("It doesnve copied anything yet.")
speech.fail("Type to copy a file or fold... | paste a file or directory that has been previously copied |
381,075 | def match(self, other_version):
major, minor, patch = _str_to_version(other_version, allow_wildcard=True)
return (major in [self.major, "*"] and minor in [self.minor, "*"]
and patch in [self.patch, "*"]) | Returns True if other_version matches.
Args:
other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a
number or a wildcard. |
381,076 | def _compute_video_hash(videofile):
seek_positions = [None] * 4
hash_result = []
with open(videofile, ) as fp:
total_size = os.fstat(fp.fileno()).st_size
if total_size < 8192 + 4096:
raise exceptions.InvalidFileError(
.format(o... | compute videofile's hash
reference: https://docs.google.com/document/d/1w5MCBO61rKQ6hI5m9laJLWse__yTYdRugpVyz4RzrmM/preview |
381,077 | def list_theme():
from engineer.themes import ThemeManager
themes = ThemeManager.themes()
col1, col2 = map(max, zip(*[(len(t.id) + 2, len(t.root_path) + 2) for t in themes.itervalues()]))
themes = ThemeManager.themes_by_finder()
for finder in sorted(themes.iterkeys()):
if len(themes[f... | List all available Engineer themes. |
381,078 | def random_density(qubits: Union[int, Qubits]) -> Density:
N, qubits = qubits_count_tuple(qubits)
size = (2**N, 2**N)
ginibre_ensemble = (np.random.normal(size=size) +
1j * np.random.normal(size=size)) / np.sqrt(2.0)
matrix = ginibre_ensemble @ np.transpose(np.conjugate(gini... | Returns: A randomly sampled Density from the Hilbert–Schmidt
ensemble of quantum states
Ref: "Induced measures in the space of mixed quantum states" Karol
Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001)
https://arxiv.org/abs/quant-ph/0012101 |
381,079 | def handle_device_json(self, data):
self._device_json.insert(0, data)
self._device_json.pop() | Manage the device json list. |
381,080 | def extract_token_and_qualifier(text, line=0, column=0):
qualifier = temp_token[-1]
else:
qualifier = temp_token
return TokenAndQualifier(token, qualifier) | Extracts the token a qualifier from the text given the line/colum
(see test_extract_token_and_qualifier for examples).
:param unicode text:
:param int line: 0-based
:param int column: 0-based |
381,081 | def plot(self):
figure()
plot_envelope(self.M, self.C, self.xplot)
for i in range(3):
f = Realization(self.M, self.C)
plot(self.xplot,f(self.xplot))
plot(self.abundance, self.frye, , markersize=4)
xlabel()
ylabel()
title(self.name... | Plot posterior from simple nonstochetric regression. |
381,082 | def prepend_to_file(path, data, bufsize=1<<15):
backupname = path + os.extsep +
try: os.unlink(backupname)
except OSError: pass
os.rename(path, backupname)
outputfile.write(data)
buf = inputfile.read(bufsize)
while buf:
outputfile.... | TODO:
* Add a random string to the backup file.
* Restore permissions after copy. |
381,083 | def ai(board, who=):
return sorted(board.possible(), key=lambda b: value(b, who))[-1] | Returns best next board
>>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']]
>>> ai(b)
< Board |xo.xo.x..| > |
381,084 | def read_namespaced_network_policy(self, name, namespace, **kwargs):
kwargs[] = True
if kwargs.get():
return self.read_namespaced_network_policy_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_network_policy_with_http_info(name, name... | read the specified NetworkPolicy
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_network_policy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req ... |
381,085 | def get_preview_url(self, data_type=):
if self.data_source is DataSource.SENTINEL2_L1C or self.safe_type is EsaSafeType.OLD_TYPE:
return self.get_url(AwsConstants.PREVIEW_JP2)
return self.get_qi_url(.format(data_type)) | Returns url location of full resolution L1C preview
:return: |
381,086 | def load_vcf(
path,
genome=None,
reference_vcf_key="reference",
only_passing=True,
allow_extended_nucleotides=False,
include_info=True,
chunk_size=10 ** 5,
max_variants=None,
sort_key=variant_ascending_position_sort_key,
distinct=True):
... | Load reference name and Variant objects from the given VCF filename.
Currently only local files are supported by this function (no http). If you
call this on an HTTP URL, it will fall back to `load_vcf`.
Parameters
----------
path : str
Path to VCF (*.vcf) or compressed VCF (*.vcf.gz).
... |
381,087 | def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock:
packed_block = self.pack_block(self.block, *args, **kwargs)
final_block = self.finalize_block(packed_block)
self.validate_block(final_block)
return final_block | Mine the current block. Proxies to self.pack_block method. |
381,088 | def fetch(self, resource_class):
if issubclass(resource_class, Entry):
params = None
content_type = getattr(resource_class, , None)
if content_type is not None:
params = {: resource_class.__content_type__}
return RequestArray(self.dispatch... | Construct a :class:`.Request` for the given resource type.
Provided an :class:`.Entry` subclass, the Content Type ID will be inferred and requested explicitly.
Examples::
client.fetch(Asset)
client.fetch(Entry)
client.fetch(ContentType)
client.fetch(Cus... |
381,089 | def real_time_scheduling(self, availability, oauth, event, target_calendars=()):
args = {
: oauth,
: event,
: target_calendars
}
if availability:
options = {}
options[] = self.map_availability_participants(availability.get(, N... | Generates an real time scheduling link to start the OAuth process with
an event to be automatically upserted
:param dict availability: - A dict describing the availability details for the event:
:participants - A dict stating who is required for the availability
... |
381,090 | def end_span(self, *args, **kwargs):
cur_span = self.current_span()
if cur_span is None and self._spans_list:
cur_span = self._spans_list[-1]
if cur_span is None:
logging.warning()
return
cur_span.finish()
self.span_context.span_id =... | End a span. Update the span_id in SpanContext to the current span's
parent span id; Update the current span. |
381,091 | def handle(self, *args, **kwargs):
frequency = kwargs[]
frequencies = settings.STATISTIC_FREQUENCY_ALL if frequency == else (frequency.split() if in frequency else [frequency])
if kwargs[]:
maintenance.list_statistics()
| Command handler for the "metrics" command. |
381,092 | def isclose(a, b, rtol=1e-5, atol=1e-8):
return abs(a - b) < (atol + rtol * abs(b)) | This is essentially np.isclose, but slightly faster. |
381,093 | def GetArchiveInfo(self):
self.searchable = extra.is_searchable(self.file)
self.lcid = None
result, ui = chmlib.chm_resolve_object(self.file, )
if (result != chmlib.CHM_RESOLVE_SUCCESS):
sys.stderr.write()
return 0
size, text = chmlib.chm_retri... | Obtains information on CHM archive.
This function checks the /#SYSTEM file inside the CHM archive to
obtain the index, home page, topics, encoding and title. It is called
from LoadCHM. |
381,094 | def get_all_fields(obj):
fields = []
for f in obj._meta.fields:
fname = f.name
get_choice = "get_" + fname + "_display"
if hasattr(obj, get_choice):
value = getattr(obj, get_choice)()
else:
try:
value = getattr(obj, fname)
... | Returns a list of all field names on the instance. |
381,095 | def copy(self):
if self._page_control is not None and self._page_control.hasFocus():
self._page_control.copy()
elif self._control.hasFocus():
text = self._control.textCursor().selection().toPlainText()
if text:
lines = map(self._transform_prom... | Copy the currently selected text to the clipboard, removing prompts. |
381,096 | def _to_DOM(self):
root_node = ET.Element("no2index")
reference_time_node = ET.SubElement(root_node, "reference_time")
reference_time_node.text = str(self._reference_time)
reception_time_node = ET.SubElement(root_node, "reception_time")
reception_time_node.text = str(sel... | Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object |
381,097 | def WaitProcessing(obj, eng, callbacks, exc_info):
e = exc_info[1]
obj.set_action(e.action, e.message)
obj.save(status=eng.object_status.WAITING,
callback_pos=eng.state.callback_pos,
id_workflow=eng.uuid)
eng.save(WorkflowStatus.HALTED)
... | Take actions when WaitProcessing is raised.
..note::
We're essentially doing HaltProcessing, plus `obj.set_action` and
object status `WAITING` instead of `HALTED`.
This is not present in TransitionActions so that's why it is not
calling super in this case. |
381,098 | def check_spot_requests(self, requests, tags=None):
instances = [None] * len(requests)
ec2_requests = self.retry_on_ec2_error(self.ec2.get_all_spot_instance_requests, request_ids=requests)
for req in ec2_requests:
if req.instance_id:
instance = self.retry_on... | Check status of one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list
:param tags:
:type tags: dict
:return: List of boto.ec2.instance.Instance's created, order corresponding to requests param (None if request
... |
381,099 | def mkdir(name, path):
with Session() as session:
try:
session.VFolder(name).mkdir(path)
print_done()
except Exception as e:
print_error(e)
sys.exit(1) | Create an empty directory in the virtual folder.
\b
NAME: Name of a virtual folder.
PATH: The name or path of directory. Parent directories are created automatically
if they do not exist. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.