_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q46200 | DependencyLink.dependent | train | def dependent(self):
"""
Accesses the dependent node
:getter: returns the Dependent node
:type: corenlp_xml.dependencies.DependencyNode
"""
if self._dependent is None:
dependents = self._element.xpath('dependent')
if len(dependents) > 0:
... | python | {
"resource": ""
} |
q46201 | ScssImportsParser.strip_quotes | train | def strip_quotes(self, content):
"""
Unquote given rule.
Args:
content (str): An import rule.
Raises:
InvalidImportRule: Raise exception if the rule is badly quoted
(not started or not ended quotes).
Returns:
string: The given ru... | python | {
"resource": ""
} |
q46202 | ScssImportsParser.flatten_rules | train | def flatten_rules(self, declarations):
"""
Flatten returned import rules from regex.
Because import rules can contains multiple items in the same rule
(called multiline import rule), the regex ``REGEX_IMPORT_RULE``
return a list of unquoted items for each rule.
Args:
... | python | {
"resource": ""
} |
q46203 | naccess_available | train | def naccess_available():
"""True if naccess is available on the path."""
available = False
try:
subprocess.check_output(['naccess'], stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
available = True
except FileNotFoundError:
print("naccess has not been found o... | python | {
"resource": ""
} |
q46204 | run_naccess | train | def run_naccess(pdb, mode, path=True, include_hetatms=False, outfile=None,
path_to_ex=None):
"""Uses naccess to run surface accessibility calculations.
Notes
-----
Requires the naccess program, with a path to its executable
provided in global_settings. For information on the Naccess... | python | {
"resource": ""
} |
q46205 | Driver.selenium | train | def selenium(self):
"""Get the instance of webdriver, it starts the browser if the
webdriver is not yet instantied
:return: a `selenium instance <http://selenium-python.readthedocs.org/
api.html#module-selenium.webdriver.remote.webdriver>`
"""
if not self._web_driver:
... | python | {
"resource": ""
} |
q46206 | paths_by_depth | train | def paths_by_depth(paths):
"""Sort list of paths by number of directories in it
.. todo::
check if a final '/' is consistently given or ommitted.
:param iterable paths: iterable containing paths (str)
:rtype: list
"""
return sorted(
paths,
key=lambda path: path... | python | {
"resource": ""
} |
q46207 | ScssFinder.get_relative_from_paths | train | def get_relative_from_paths(self, filepath, paths):
"""
Find the relative filepath from the most relevant multiple paths.
This is somewhat like a ``os.path.relpath(path[, start])`` but where
``start`` is a list. The most relevant item from ``paths`` will be used
to apply the rel... | python | {
"resource": ""
} |
q46208 | ScssFinder.is_allowed | train | def is_allowed(self, filepath, excludes=[]):
"""
Check from exclude patterns if a relative filepath is allowed
Args:
filepath (str): A relative file path. (exclude patterns are
allways based from the source directory).
Keyword Arguments:
excludes... | python | {
"resource": ""
} |
q46209 | ScssFinder.match_conditions | train | def match_conditions(self, filepath, sourcedir=None, nopartial=True,
exclude_patterns=[], excluded_libdirs=[]):
"""
Find if a filepath match all required conditions.
Available conditions are (in order):
* Is allowed file extension;
* Is a partial source... | python | {
"resource": ""
} |
q46210 | ScssFinder.change_extension | train | def change_extension(self, filepath, new_extension):
"""
Change final filename extension.
Args:
filepath (str): A file path (relative or absolute).
new_extension (str): New extension name (without leading dot) to
apply.
Returns:
str: ... | python | {
"resource": ""
} |
q46211 | ScssFinder.get_destination | train | def get_destination(self, filepath, targetdir=None):
"""
Return destination path from given source file path.
Destination is allways a file with extension ``.css``.
Args:
filepath (str): A file path. The path is allways relative to
sources directory. If not ... | python | {
"resource": ""
} |
q46212 | ScssFinder.compilable_sources | train | def compilable_sources(self, sourcedir, absolute=False, recursive=True,
excludes=[]):
"""
Find all scss sources that should be compiled, aka all sources that
are not "partials" Sass sources.
Args:
sourcedir (str): Directory path to scan.
... | python | {
"resource": ""
} |
q46213 | ScssFinder.mirror_sources | train | def mirror_sources(self, sourcedir, targetdir=None, recursive=True,
excludes=[]):
"""
Mirroring compilable sources filepaths to their targets.
Args:
sourcedir (str): Directory path to scan.
Keyword Arguments:
absolute (bool): Returned path... | python | {
"resource": ""
} |
q46214 | AddHandler.add_bundle | train | def add_bundle(self, data: dict) -> models.Bundle:
"""Build a new bundle version of files.
The format of the input dict is defined in the `schema` module.
"""
bundle_obj = self.bundle(data['name'])
if bundle_obj and self.version(bundle_obj.name, data['created']):
LOG... | python | {
"resource": ""
} |
q46215 | AddHandler._build_tags | train | def _build_tags(self, tag_names: List[str]) -> dict:
"""Build a list of tag objects."""
tags = {}
for tag_name in tag_names:
tag_obj = self.tag(tag_name)
if tag_obj is None:
LOG.debug(f"create new tag: {tag_name}")
tag_obj = self.new_tag(ta... | python | {
"resource": ""
} |
q46216 | Prospector.run | train | def run(self):
"""
Runs prospector in the input files and returns a json with the analysis
"""
arg_prospector = f'prospector --output-format json {self.repo.diff_files()}'
analysis = subprocess.run(arg_prospector, stdout=subprocess.PIPE, shell=True)
return json.loads(anal... | python | {
"resource": ""
} |
q46217 | DjangoCursorWrapper.execute | train | def execute(self, operation, parameters=()):
"""
Wraps execute method to record the query, execution duration and
stackframe.
"""
__traceback_hide__ = True # NOQ
# Time the exection of the query
start = time.time()
try:
return self.cursor.ex... | python | {
"resource": ""
} |
q46218 | main | train | def main():
"""Collect user args and call command funct.
Collect command line args and setup environment then call
function for command specified in args.
"""
parser = parser_setup()
options = parser.parse_args()
debug = bool(options.debug > 0)
debugall = bool(options.debug > 1)
... | python | {
"resource": ""
} |
q46219 | cmd_list | train | def cmd_list(options):
"""Gather data for instances matching args and call display func.
Args:
options (object): contains args and data from parser.
"""
(i_info, param_str) = gather_data(options)
if i_info:
awsc.get_all_aminames(i_info)
param_str = "Instance List - " + para... | python | {
"resource": ""
} |
q46220 | cmd_startstop | train | def cmd_startstop(options):
"""Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object)... | python | {
"resource": ""
} |
q46221 | cmd_ssh | train | def cmd_ssh(options):
"""Connect to the specified instance via ssh.
Finds instances that match the user specified args that are also
in the 'running' state. The target instance is determined, the
required connection information is retreived (IP, key and ssh
user-name), then an 'ssh' connection is ... | python | {
"resource": ""
} |
q46222 | cmd_ssh_user | train | def cmd_ssh_user(tar_aminame, inst_name):
"""Calculate instance login-username based on image-name.
Args:
tar_aminame (str): name of the image instance created with.
inst_name (str): name of the instance.
Returns:
username (str): name for ssh based on AMI-name.
"""
if tar_a... | python | {
"resource": ""
} |
q46223 | gather_data | train | def gather_data(options):
"""Get Data specific for command selected.
Create ec2 specific query and output title based on
options specified, retrieves the raw response data
from aws, then processes it into the i_info dict,
which is used throughout this module.
Args:
options (object): co... | python | {
"resource": ""
} |
q46224 | process_results | train | def process_results(qry_results):
"""Generate dictionary of results from query.
Decodes the large dict recturned from the AWS query.
Args:
qry_results (dict): results from awsc.get_inst_info
Returns:
i_info (dict): information on instances and details.
"""
i_info = {}
for ... | python | {
"resource": ""
} |
q46225 | qry_create | train | def qry_create(options):
"""Create query from the args specified and command chosen.
Creates a query string that incorporates the args in the options
object, and creates the title for the 'list' function.
Args:
options (object): contains args and data from parser
Returns:
qry_strin... | python | {
"resource": ""
} |
q46226 | qry_helper | train | def qry_helper(flag_id, qry_string, param_str, flag_filt=False, filt_st=""):
"""Dynamically add syntaxtical elements to query.
This functions adds syntactical elements to the query string, and
report title, based on the types and number of items added thus far.
Args:
flag_filt (bool): at least... | python | {
"resource": ""
} |
q46227 | list_instances | train | def list_instances(i_info, param_str, numbered=False):
"""Display a list of all instances and their details.
Iterates through all the instances in the dict, and displays
information for each instance.
Args:
i_info (dict): information on instances and details.
param_str (str): the title... | python | {
"resource": ""
} |
q46228 | list_tags | train | def list_tags(tags):
"""Print tags in dict so they allign with listing above."""
tags_sorted = sorted(list(tags.items()), key=operator.itemgetter(0))
tag_sec_spacer = ""
c = 1
ignored_keys = ["Name", "aws:ec2spot:fleet-request-id"]
pad_col = {1: 38, 2: 49}
for k, v in tags_sorted:
# ... | python | {
"resource": ""
} |
q46229 | determine_inst | train | def determine_inst(i_info, param_str, command):
"""Determine the instance-id of the target instance.
Inspect the number of instance-ids collected and take the
appropriate action: exit if no ids, return if single id,
and call user_picklist function if multiple ids exist.
Args:
i_info (dict)... | python | {
"resource": ""
} |
q46230 | user_picklist | train | def user_picklist(i_info, command):
"""Display list of instances matching args and ask user to select target.
Instance list displayed and user asked to enter the number corresponding
to the desired target instance, or '0' to abort.
Args:
i_info (dict): information on instances and details.
... | python | {
"resource": ""
} |
q46231 | user_entry | train | def user_entry(entry_int, num_inst, command):
"""Validate user entry and returns index and validity flag.
Processes the user entry and take the appropriate action: abort
if '0' entered, set validity flag and index is valid entry, else
return invalid index and the still unset validity flag.
Args:
... | python | {
"resource": ""
} |
q46232 | execute | train | def execute(args):
"""
Call vswhere with the given arguments and return an array of results.
`args` is a list of command line arguments to pass to vswhere.
If the argument list contains '-property', this returns an array with the
property value for each result. Otherwise, this returns an array of
... | python | {
"resource": ""
} |
q46233 | find | train | def find(find_all=False, latest=False, legacy=False, prerelease=False, products=None, prop=None, requires=None, requires_any=False, version=None):
"""
Call vswhere and return an array of the results.
If `find_all` is true, finds all instances even if they are incomplete and may not launch.
If `latest`... | python | {
"resource": ""
} |
q46234 | get_vswhere_path | train | def get_vswhere_path():
"""
Get the path to vshwere.exe.
If vswhere is not already installed as part of Visual Studio, and no
alternate path is given using `set_vswhere_path()`, the latest release will
be downloaded and stored alongside this script.
"""
if alternate_path and os.path.exists(... | python | {
"resource": ""
} |
q46235 | _download_vswhere | train | def _download_vswhere():
"""
Download vswhere to DOWNLOAD_PATH.
"""
print('downloading from', _get_latest_release_url())
try:
from urllib.request import urlopen
with urlopen(_get_latest_release_url()) as response, open(DOWNLOAD_PATH, 'wb') as outfile:
shutil.copyfileobj(r... | python | {
"resource": ""
} |
q46236 | LambdaFuncGenerator._get_source | train | def _get_source(self):
"""
Get the lambda function source template. Strip the leading docstring.
Note that it's a real module in this project so we can test it.
:return: function source code, with leading docstring stripped.
:rtype: str
"""
logger.debug('Getting ... | python | {
"resource": ""
} |
q46237 | LambdaFuncGenerator._docstring | train | def _docstring(self):
"""
Generate a docstring for the generated source file.
:return: new docstring
:rtype: str
"""
s = '"""' + "\n"
s += "webhook2lambda2sqs generated function source\n"
s += "this code was generated by webhook2lambda2sqs v%s\n" % VERSIO... | python | {
"resource": ""
} |
q46238 | LambdaFuncGenerator.generate | train | def generate(self):
"""
Generate Lambda function source; return it as a string.
:rtype: str
:returns: lambda function source
"""
s = self._docstring
s += self._get_source().replace(
'endpoints = {}',
'endpoints = ' + self._config_src
... | python | {
"resource": ""
} |
q46239 | kem | train | def kem(request):
"""
due to the base directory settings of django, the model_path needs to be different when
testing with this section.
"""
keyword = request.GET['keyword']
lang = request.GET['lang']
ontology = 'ontology' if 'ontology' in request.GET and bool(json.loads(request.GET['ontology'].lower())) else 'o... | python | {
"resource": ""
} |
q46240 | Metadata.normalize_date | train | def normalize_date(date):
'''normalize the specified date to milliseconds since the epoch
If it is a string, it is assumed to be some sort of datetime such as
"2015-12-27" or "2015-12-27T11:01:20.954". If date is a naive datetime,
it is assumed to be UTC.
If numeric arguments a... | python | {
"resource": ""
} |
q46241 | union_sql | train | def union_sql(view_name, *tables):
"""This function generates string containing SQL code, that creates
a big VIEW, that consists of many SELECTs.
>>> utils.union_sql('global', 'foo', 'bar', 'baz')
'CREATE VIEW global SELECT * FROM foo UNION SELECT * FROM bar UNION SELECT * FROM baz'
"""
if not... | python | {
"resource": ""
} |
q46242 | Transceiver.send_data | train | def send_data(self, data):
''' This function can be overwritten in derived class
Std. function is to broadcast all receiver data to all backends
'''
for frontend_data in data:
serialized_data = self.serialize_data(frontend_data)
if sys.version_info >= (3, 0):... | python | {
"resource": ""
} |
q46243 | QueryProcessor.pre_handler | train | def pre_handler(self, cmd):
"""Hook for logic before each handler starts."""
if self._finished:
return
if self.interesting_commit and cmd.name == 'commit':
if cmd.mark == self.interesting_commit:
print(cmd.to_string())
self._finished = True... | python | {
"resource": ""
} |
q46244 | QueryProcessor.feature_handler | train | def feature_handler(self, cmd):
"""Process a FeatureCommand."""
feature = cmd.feature_name
if feature not in commands.FEATURE_NAMES:
self.warning("feature %s is not supported - parsing may fail"
% (feature,)) | python | {
"resource": ""
} |
q46245 | Messages.commit_format | train | def commit_format(self):
"""
Formats the analysis into a simpler dictionary with the line, file and message values to
be commented on a commit.
Returns a list of dictionaries
"""
formatted_analyses = []
for analyze in self.analysis['messages']:
for... | python | {
"resource": ""
} |
q46246 | bundles | train | def bundles():
"""Display bundles."""
per_page = int(request.args.get('per_page', 30))
page = int(request.args.get('page', 1))
query = store.bundles()
query_page = query.paginate(page, per_page=per_page)
data = []
for bundle_obj in query_page.items:
bundle_data = bundle_obj.to_dict(... | python | {
"resource": ""
} |
q46247 | Decoder.int_to_rgba | train | def int_to_rgba(cls, rgba_int):
"""Converts a color Integer into r, g, b, a tuple."""
if rgba_int is None:
return None, None, None, None
alpha = rgba_int % 256
blue = rgba_int / 256 % 256
green = rgba_int / 256 / 256 % 256
red = rgba_int / 256 / 256 / 256 % 25... | python | {
"resource": ""
} |
q46248 | format_float | train | def format_float(x, max_width):
'''format_float will ensure that a number's decimal part is truncated to
fit within some bounds, unless the whole part is wider than max_width,
which is a problem you need to sort out yourself.
'''
# width of (whole part + 1 (to avoid zero)) + 1 because int floors, no... | python | {
"resource": ""
} |
q46249 | SassCompileHelper.write_content | train | def write_content(self, content, destination):
"""
Write given content to destination path.
It will create needed directory structure first if it contain some
directories that does not allready exists.
Args:
content (str): Content to write to target file.
... | python | {
"resource": ""
} |
q46250 | VIVOUtilsGraph.nt_yielder | train | def nt_yielder(self, graph, size):
"""
Yield n sized ntriples for a given graph.
Used in sending chunks of data to the VIVO
SPARQL API.
"""
for grp in self.make_batch(size, graph):
tmpg = Graph()
# Add statements as list to tmp graph
tm... | python | {
"resource": ""
} |
q46251 | VIVOUtilsGraph.bulk_update | train | def bulk_update(self, named_graph, graph, size, is_add=True):
"""
Bulk adds or deletes. Triples are chunked into n size groups before
sending to API. This prevents the API endpoint from timing out.
"""
context = URIRef(named_graph)
total = len(graph)
if total > 0:... | python | {
"resource": ""
} |
q46252 | VIVOUtilsGraph.bulk_add | train | def bulk_add(self, named_graph, add, size=DEFAULT_CHUNK_SIZE):
"""
Add batches of statements in n-sized chunks.
"""
return self.bulk_update(named_graph, add, size) | python | {
"resource": ""
} |
q46253 | VIVOUtilsGraph.bulk_remove | train | def bulk_remove(self, named_graph, add, size=DEFAULT_CHUNK_SIZE):
"""
Remove batches of statements in n-sized chunks.
"""
return self.bulk_update(named_graph, add, size, is_add=False) | python | {
"resource": ""
} |
q46254 | blend | train | def blend(c1, c2):
"""Alpha blends two colors, using the alpha given by c2"""
return [c1[i] * (0xFF - c2[3]) + c2[i] * c2[3] >> 8 for i in range(3)] | python | {
"resource": ""
} |
q46255 | gradient_list | train | def gradient_list(start, end, steps):
"""Compute gradient colors"""
delta = [end[i] - start[i] for i in range(4)]
return [bytearray(start[j] + (delta[j] * i) // steps for j in range(4))
for i in range(steps + 1)] | python | {
"resource": ""
} |
q46256 | rgb2rgba | train | def rgb2rgba(rgb):
"""Take a row of RGB bytes, and convert to a row of RGBA bytes."""
rgba = []
for i in range(0, len(rgb), 3):
rgba += rgb[i:i+3]
rgba.append(255)
return rgba | python | {
"resource": ""
} |
q46257 | ByteReader.read | train | def read(self, num_bytes):
"""Read `num_bytes` from the compressed data chunks.
Data is returned as `bytes` of length `num_bytes`
Will raise an EOFError if data is unavailable.
Note: Will always return `num_bytes` of data (unlike the file read method).
"""
while len(s... | python | {
"resource": ""
} |
q46258 | PNGCanvas._offset | train | def _offset(self, x, y):
"""Helper for internal data"""
x, y = force_int(x, y)
return y * self.width * 4 + x * 4 | python | {
"resource": ""
} |
q46259 | PNGCanvas.point | train | def point(self, x, y, color=None):
"""Set a pixel"""
if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1:
return
if color is None:
color = self.color
o = self._offset(x, y)
self.canvas[o:o + 3] = blend(self.canvas[o:o + 3], bytearray(color)) | python | {
"resource": ""
} |
q46260 | PNGCanvas.vertical_gradient | train | def vertical_gradient(self, x0, y0, x1, y1, start, end):
"""Draw a vertical gradient"""
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 ... | python | {
"resource": ""
} |
q46261 | PNGCanvas.filled_rectangle | train | def filled_rectangle(self, x0, y0, x1, y1):
"""Draw a filled rectangle"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
self.point(x, y, self.color) | python | {
"resource": ""
} |
q46262 | PNGCanvas.blend_rect | train | def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff):
"""Blend a rectangle onto the image"""
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
o = self._offset(x, y)
rgba = self.c... | python | {
"resource": ""
} |
q46263 | PNGCanvas.line | train | def line(self, x0, y0, x1, y1):
"""Draw a line using Xiaolin Wu's antialiasing technique"""
# clean params
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
if y0 > y1:
y0, y1, x0, x1 = y1, y0, x1, x0
dx = x1 - x0
if dx < 0:
sx = -1
else:... | python | {
"resource": ""
} |
q46264 | PNGCanvas.polyline | train | def polyline(self, arr):
"""Draw a set of lines"""
for i in range(0, len(arr) - 1):
self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]) | python | {
"resource": ""
} |
q46265 | PNGCanvas.dump | train | def dump(self):
"""Dump the image data"""
scan_lines = bytearray()
for y in range(self.height):
scan_lines.append(0) # filter type 0 (None)
scan_lines.extend(
self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
)
# image repre... | python | {
"resource": ""
} |
q46266 | PNGCanvas.pack_chunk | train | def pack_chunk(tag, data):
"""Pack a PNG chunk for serializing to disk"""
to_check = tag + data
return (struct.pack(b"!I", len(data)) + to_check +
struct.pack(b"!I", zlib.crc32(to_check) & 0xFFFFFFFF)) | python | {
"resource": ""
} |
q46267 | PNGCanvas.load | train | def load(self, f):
"""Load a PNG image"""
SUPPORTED_COLOR_TYPES = (COLOR_TYPE_TRUECOLOR, COLOR_TYPE_TRUECOLOR_WITH_ALPHA)
SAMPLES_PER_PIXEL = { COLOR_TYPE_TRUECOLOR: 3,
COLOR_TYPE_TRUECOLOR_WITH_ALPHA: 4 }
assert f.read(8) == SIGNATURE
chunks = ite... | python | {
"resource": ""
} |
q46268 | PNGCanvas.defilter | train | def defilter(cur, prev, filter_type, bpp=4):
"""Decode a chunk"""
if filter_type == 0: # No filter
return cur
elif filter_type == 1: # Sub
xp = 0
for xc in range(bpp, len(cur)):
cur[xc] = (cur[xc] + cur[xp]) % 256
xp += 1
... | python | {
"resource": ""
} |
q46269 | PNGCanvas.chunks | train | def chunks(f):
"""Split read PNG image data into chunks"""
while 1:
try:
length = struct.unpack(b"!I", f.read(4))[0]
tag = f.read(4)
data = f.read(length)
crc = struct.unpack(b"!I", f.read(4))[0]
except struct.error:... | python | {
"resource": ""
} |
q46270 | Sublemon.start | train | async def start(self) -> None:
"""Coroutine to run this server."""
if self._is_running:
raise SublemonRuntimeError(
'Attempted to start an already-running `Sublemon` instance')
self._poll_task = asyncio.ensure_future(self._poll())
self._is_running = True | python | {
"resource": ""
} |
q46271 | Sublemon.stop | train | async def stop(self) -> None:
"""Coroutine to stop execution of this server."""
if not self._is_running:
raise SublemonRuntimeError(
'Attempted to stop an already-stopped `Sublemon` instance')
await self.block()
self._poll_task.cancel()
self._is_runni... | python | {
"resource": ""
} |
q46272 | Sublemon._poll | train | async def _poll(self) -> None:
"""Coroutine to poll status of running subprocesses."""
while True:
await asyncio.sleep(self._poll_delta)
for subproc in list(self._running_set):
subproc._poll() | python | {
"resource": ""
} |
q46273 | Sublemon.iter_lines | train | async def iter_lines(
self,
*cmds: str,
stream: str='both') -> AsyncGenerator[str, None]:
"""Coroutine to spawn commands and yield text lines from stdout."""
sps = self.spawn(*cmds)
if stream == 'both':
agen = amerge(
amerge(*[sp.st... | python | {
"resource": ""
} |
q46274 | Sublemon.gather | train | async def gather(self, *cmds: str) -> Tuple[int]:
"""Coroutine to spawn subprocesses and block until completion.
Note:
The same `max_concurrency` restriction that applies to `spawn`
also applies here.
Returns:
The exit codes of the spawned subprocesses, in t... | python | {
"resource": ""
} |
q46275 | Sublemon.block | train | async def block(self) -> None:
"""Block until all running and pending subprocesses have finished."""
await asyncio.gather(
*itertools.chain(
(sp.wait_done() for sp in self._running_set),
(sp.wait_done() for sp in self._pending_set))) | python | {
"resource": ""
} |
q46276 | Sublemon.spawn | train | def spawn(self, *cmds: str) -> List[SublemonSubprocess]:
"""Coroutine to spawn shell commands.
If `max_concurrency` is reached during the attempt to spawn the
specified subprocesses, excess subprocesses will block while attempting
to acquire this server's semaphore.
"""
... | python | {
"resource": ""
} |
q46277 | SettingsBackendBase.parse_filepath | train | def parse_filepath(self, filepath=None):
"""
Parse given filepath to split possible path directory from filename.
* If path directory is empty, will use ``basedir`` attribute as base
filepath;
* If path directory is absolute, ignore ``basedir`` attribute;
* If path dir... | python | {
"resource": ""
} |
q46278 | SettingsBackendBase.check_filepath | train | def check_filepath(self, path, filename):
"""
Check and return the final filepath to settings
Args:
path (str): Directory path where to search for settings file.
filename (str): Filename to use to search for settings file.
Raises:
boussole.exceptions... | python | {
"resource": ""
} |
q46279 | SettingsBackendBase.open | train | def open(self, filepath):
"""
Open settings backend to return its content
Args:
filepath (str): Settings object, depends from backend
Returns:
string: File content.
"""
with io.open(filepath, 'r', encoding='utf-8') as fp:
content = f... | python | {
"resource": ""
} |
q46280 | SettingsBackendBase.load | train | def load(self, filepath=None):
"""
Load settings file from given path and optionnal filepath.
During path resolving, the ``projectdir`` is updated to the file path
directory.
Keyword Arguments:
filepath (str): Filepath to the settings file.
Returns:
... | python | {
"resource": ""
} |
q46281 | Withdraw.withdraw_bulk | train | async def withdraw_bulk(self, *args, **kwargs):
"""
Withdraw funds requests to user wallet
Accepts:
- coinid [string] (blockchain id (example: BTCTEST, LTCTEST))
- address [string] withdrawal address (in hex for tokens)
- amount [int] withdrawal amount multipl... | python | {
"resource": ""
} |
q46282 | Withdraw.withdraw_custom_token | train | async def withdraw_custom_token(self, *args, **kwargs):
"""
Withdraw custom token to user wallet
Accepts:
- address [hex string] (withdrawal address in hex form)
- amount [int] withdrawal amount multiplied by decimals_k (10**8)
- blockchain [string] token's ... | python | {
"resource": ""
} |
q46283 | Version.relative_root_dir | train | def relative_root_dir(self):
"""Build the relative root dir path for the bundle version."""
return Path(self.bundle.name) / str(self.created_at.date()) | python | {
"resource": ""
} |
q46284 | File.full_path | train | def full_path(self):
"""Return the full path to the file."""
if Path(self.path).is_absolute():
return self.path
else:
return str(self.app_root / self.path) | python | {
"resource": ""
} |
q46285 | multiline_repr | train | def multiline_repr(text, special_chars=('\n', '"')):
"""Get string representation for triple quoted context.
Make string representation as normal except do not transform
"special characters" into an escaped representation to support
use of the representation in a triple quoted multi-line string
con... | python | {
"resource": ""
} |
q46286 | Baseline._dedent | train | def _dedent(text):
"""Remove common indentation from each line in a text block.
When text block is a single line, return text block. Otherwise
determine common indentation from last line, strip common
indentation from each line, and return text block consisting of
inner lines (d... | python | {
"resource": ""
} |
q46287 | Baseline._atexit_callback | train | def _atexit_callback(cls):
"""Create Python script copies with updated baselines.
For any baseline that had a miscompare, make a copy of the
source file which contained the baseline and update the
baseline with the new string value.
:returns:
record of every Python ... | python | {
"resource": ""
} |
q46288 | bundle | train | def bundle(context, name):
"""Add a new bundle."""
if context.obj['db'].bundle(name):
click.echo(click.style('bundle name already exists', fg='yellow'))
context.abort()
new_bundle = context.obj['db'].new_bundle(name)
context.obj['db'].add_commit(new_bundle)
# add default version
... | python | {
"resource": ""
} |
q46289 | file_cmd | train | def file_cmd(context, tags, archive, bundle_name, path):
"""Add a file to a bundle."""
bundle_obj = context.obj['db'].bundle(bundle_name)
if bundle_obj is None:
click.echo(click.style(f"unknown bundle: {bundle_name}", fg='red'))
context.abort()
version_obj = bundle_obj.versions[0]
ne... | python | {
"resource": ""
} |
q46290 | tag | train | def tag(context: click.Context, file_id: int, tags: List[str]):
"""Add tags to an existing file."""
file_obj = context.obj['db'].file_(file_id)
if file_obj is None:
print(click.style('unable to find file', fg='red'))
context.abort()
for tag_name in tags:
tag_obj = context.obj['db... | python | {
"resource": ""
} |
q46291 | include_version | train | def include_version(global_root: str, version_obj: models.Version, hardlink:bool=True):
"""Include files in existing bundle version."""
global_root_dir = Path(global_root)
if version_obj.included_at:
raise VersionIncludedError(f"version included on {version_obj.included_at}")
# generate root di... | python | {
"resource": ""
} |
q46292 | checksum | train | def checksum(path):
"""Calculcate checksum for a file."""
hasher = hashlib.sha1()
with open(path, 'rb') as stream:
buf = stream.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = stream.read(BLOCKSIZE)
return hasher.hexdigest() | python | {
"resource": ""
} |
q46293 | FilteredGenericForeignKey.get_prep_lookup | train | def get_prep_lookup(self, lookup_name, rhs):
"""
Perform preliminary non-db specific lookup checks and conversions
"""
if lookup_name == 'exact':
if not isinstance(rhs, Model):
raise FilteredGenericForeignKeyFilteringException(
"For exact l... | python | {
"resource": ""
} |
q46294 | StorageTable.create_account | train | async def create_account(self, **params):
"""Describes, validates data.
"""
logging.debug("\n\n[+] -- Create account debugging. ")
model = {
"unique": ["email", "public_key"],
"required": ("public_key",),
"default": {"count":len(settings.AVAILABLE_COIN_ID),
"level":2,
"news_count":0,
"em... | python | {
"resource": ""
} |
q46295 | StorageTable.set_access_string | train | async def set_access_string(self, **params):
"""Writes content access string to database
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
cid = int(params.get("cid", "0"))
seller_access_string = params.get("seller_access_string")
seller_pubkey = params.get("seller_pubkey")... | python | {
"resource": ""
} |
q46296 | StorageTable.log_source | train | async def log_source(self, **params):
""" Logging users request sources
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return {"error":400, "reason":"Missed required fields"}
# Insert new source if does not exists the one
database = client[settings.D... | python | {
"resource": ""
} |
q46297 | StorageTable.log_transaction | train | async def log_transaction(self, **params):
"""Writing transaction to database
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return {"error":400, "reason":"Missed required fields"}
coinid = params.get("coinid")
if not coinid in ["QTUM", "PUT"]:
re... | python | {
"resource": ""
} |
q46298 | ContentHandler.get | train | async def get(self, cid, coinid):
"""Receives content by content id and coin id
Accepts:
Query string arguments:
- "cid" - int
- "coinid" - str
Returns:
return dict with following fields:
- "description" - str
- "read_access" - int
- "write_access" - int
- "content" - str
- "ci... | python | {
"resource": ""
} |
q46299 | DescriptionHandler.put | train | async def put(self, cid):
"""Update description for content
Accepts:
Query string args:
- "cid" - int
Request body parameters:
- message (signed dict):
- "description" - str
- "coinid" - str
Returns:
dict with following fields:
- "confirmed": None
- "txid" - str
- "descrip... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.