_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q37400 | pretty_time | train | def pretty_time(s, granularity=3):
"""Pretty print time in seconds. COnverts the input time in seconds into a string with
interval names, such as days, hours and minutes
From:
http://stackoverflow.com/a/24542445/1144479
"""
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
... | python | {
"resource": ""
} |
q37401 | Proxy._create_class_proxy | train | def _create_class_proxy(cls, theclass):
"""creates a proxy for the given class"""
def make_method(name):
def method(self, *args, **kw):
return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw)
return method
namespace = {}
for name... | python | {
"resource": ""
} |
q37402 | Cli.description | train | def description(self, argv0='manage.py', command=None):
'''Description outputed to console'''
command = command or self.__class__.__name__.lower()
import inspect
_help = u''
_help += u'{}\n'.format(command)
if self.__doc__:
_help += self._fix_docstring(self.__... | python | {
"resource": ""
} |
q37403 | AdditionRealm.requestAvatar | train | def requestAvatar(self, avatarId, mind, *interfaces):
"""
Create Adder avatars for any IBoxReceiver request.
"""
if IBoxReceiver in interfaces:
return (IBoxReceiver, Adder(avatarId), lambda: None)
raise NotImplementedError() | python | {
"resource": ""
} |
q37404 | Application.handle_error | train | def handle_error(self, env):
'''
Unhandled exception handler.
You can put any logging, error warning, etc here.'''
logger.exception('Exception for %s %s :',
env.request.method, env.request.url) | python | {
"resource": ""
} |
q37405 | Exposer.get | train | def get(self, obj, key):
"""
Retrieve 'key' from an instance of a class which previously exposed it.
@param key: a hashable object, previously passed to L{Exposer.expose}.
@return: the object which was exposed with the given name on obj's key.
@raise MethodNotExposed: when the... | python | {
"resource": ""
} |
q37406 | repercent_broken_unicode | train | def repercent_broken_unicode(path):
"""
As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
we need to re-percent-encode any octet produced that is not part of a
strictly legal UTF-8 octet sequence.
"""
# originally from django.utils.encoding
while True:
try:
... | python | {
"resource": ""
} |
q37407 | uri_to_iri_parts | train | def uri_to_iri_parts(path, query, fragment):
r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI to convert.
"""... | python | {
"resource": ""
} |
q37408 | default_bundle_config | train | def default_bundle_config():
"""Return the default bundle config file as an AttrDict."""
import os
from ambry.util import AttrDict
config = AttrDict()
f = os.path.join(
os.path.dirname(
os.path.realpath(__file__)),
'bundle.yaml')
config.update_yaml(f)
return c... | python | {
"resource": ""
} |
q37409 | find_package_data | train | def find_package_data():
""" Returns package_data, because setuptools is too stupid to handle nested directories.
Returns:
dict: key is "ambry", value is list of paths.
"""
l = list()
for start in ('ambry/support', 'ambry/bundle/default_files'):
for root, dirs, files in os.walk(sta... | python | {
"resource": ""
} |
q37410 | File.update | train | def update(self, of):
"""Update a file from another file, for copying"""
# The other values should be set when the file object is created with dataset.bsfile()
for p in ('mime_type', 'preference', 'state', 'hash', 'modified', 'size', 'contents', 'source_hash', 'data'):
setattr(self,... | python | {
"resource": ""
} |
q37411 | File.dict_row_reader | train | def dict_row_reader(self):
""" Unpacks message pack rows into a stream of dicts. """
rows = self.unpacked_contents
if not rows:
return
header = rows.pop(0)
for row in rows:
yield dict(list(zip(header, row))) | python | {
"resource": ""
} |
q37412 | File.update_contents | train | def update_contents(self, contents, mime_type):
"""Update the contents and set the hash and modification time"""
import hashlib
import time
new_size = len(contents)
self.mime_type = mime_type
if mime_type == 'text/plain':
self.contents = contents.encode('ut... | python | {
"resource": ""
} |
q37413 | ApiClient.__deserialize_datetime | train | def __deserialize_datetime(self, string):
"""
Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
timestr = str(datetime.fromt... | python | {
"resource": ""
} |
q37414 | un | train | def un(source, wrapper=list, error_bad_lines=True):
"""Parse a text stream to TSV
If the source is a string, it is converted to a line-iterable stream. If
it is a file handle or other object, we assume that we can iterate over
the lines in it.
The result is a generator, and what it contains depend... | python | {
"resource": ""
} |
q37415 | to | train | def to(items, output=None):
"""Present a collection of items as TSV
The items in the collection can themselves be any iterable collection.
(Single field structures should be represented as one tuples.)
With no output parameter, a generator of strings is returned. If an output
parameter is passed, ... | python | {
"resource": ""
} |
q37416 | get_bundle_ref | train | def get_bundle_ref(args, l, use_history=False):
""" Use a variety of methods to determine which bundle to use
:param args:
:return:
"""
if not use_history:
if args.id:
return (args.id, '-i argument')
if hasattr(args, 'bundle_ref') and args.bundle_ref:
retu... | python | {
"resource": ""
} |
q37417 | bundle_variant | train | def bundle_variant(args, l, rc):
"""Create a new bundle as a variant of an existing bundle"""
from ambry.orm.exc import ConflictError
ob = l.bundle(args.ref)
d = dict(
dataset=args.dataset or ob.identity.dataset,
revision=args.revision,
source=args.source or ob.identity.source... | python | {
"resource": ""
} |
q37418 | bundle_new | train | def bundle_new(args, l, rc):
"""Create a new bundle"""
from ambry.orm.exc import ConflictError
d = dict(
dataset=args.dataset,
revision=args.revision,
source=args.source,
bspace=args.space,
subset=args.subset,
btime=args.time,
variation=args.variatio... | python | {
"resource": ""
} |
q37419 | InitialDataUpdater.handle_deletions | train | def handle_deletions(self):
"""
Manages handling deletions of objects that were previously managed by the initial data process but no longer
managed. It does so by mantaining a list of receipts for model objects that are registered for deletion on
each round of initial data processing. A... | python | {
"resource": ""
} |
q37420 | InitialDataUpdater.update_all_apps | train | def update_all_apps(self):
"""
Loops through all app names contained in settings.INSTALLED_APPS and calls `update_app`
on each one. Handles any object deletions that happened after all apps have been initialized.
"""
for app in apps.get_app_configs():
self.update_app(... | python | {
"resource": ""
} |
q37421 | BaseSearchBackend._and_join | train | def _and_join(self, terms):
""" Joins terms using AND operator.
Args:
terms (list): terms to join
Examples:
self._and_join(['term1']) -> 'term1'
self._and_join(['term1', 'term2']) -> 'term1 AND term2'
self._and_join(['term1', 'term2', 'term3']) -... | python | {
"resource": ""
} |
q37422 | BaseIndex.index_one | train | def index_one(self, instance, force=False):
""" Indexes exactly one object of the Ambry system.
Args:
instance (any): instance to index.
force (boolean): if True replace document in the index.
Returns:
boolean: True if document added to index, False if docum... | python | {
"resource": ""
} |
q37423 | BaseDatasetIndex._expand_terms | train | def _expand_terms(self, terms):
""" Expands terms of the dataset to the appropriate fields. It will parse the search phrase
and return only the search term components that are applicable to a Dataset query.
Args:
terms (dict or str):
Returns:
dict: keys are fie... | python | {
"resource": ""
} |
q37424 | BasePartitionIndex._as_document | train | def _as_document(self, partition):
""" Converts given partition to the document indexed by FTS backend.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema.
"""
schema = ' '.join(
... | python | {
"resource": ""
} |
q37425 | BasePartitionIndex._expand_terms | train | def _expand_terms(self, terms):
""" Expands partition terms to the appropriate fields.
Args:
terms (dict or str):
Returns:
dict: keys are field names, values are query strings
"""
ret = {
'keywords': list(),
'doc': list(),
... | python | {
"resource": ""
} |
q37426 | BasePartitionIndex._expand_place_ids | train | def _expand_place_ids(self, terms):
""" Lookups all of the place identifiers to get gvids
Args:
terms (str or unicode): terms to lookup
Returns:
str or list: given terms if no identifiers found, otherwise list of identifiers.
"""
place_vids = []
... | python | {
"resource": ""
} |
q37427 | BaseIdentifierIndex._as_document | train | def _as_document(self, identifier):
""" Converts given identifier to the document indexed by FTS backend.
Args:
identifier (dict): identifier to convert. Dict contains at
least 'identifier', 'type' and 'name' keys.
Returns:
dict with structure matches to... | python | {
"resource": ""
} |
q37428 | SearchTermParser._geograins | train | def _geograins(self):
"""Create a map geographic area terms to the geo grain GVid values """
from geoid.civick import GVid
geo_grains = {}
for sl, cls in GVid.sl_map.items():
if '_' not in cls.level:
geo_grains[self.stem(cls.level)] = str(cls.nullval().summ... | python | {
"resource": ""
} |
q37429 | SearchTermParser.parse | train | def parse(self, s, term_join=None):
""" Parses search term to
Args:
s (str): string with search term.
or_join (callable): function to join 'OR' terms.
Returns:
dict: all of the terms grouped by marker. Key is a marker, value is a term.
Example:
... | python | {
"resource": ""
} |
q37430 | Sqla.command_create_tables | train | def command_create_tables(self, meta_name=None, verbose=False):
'''
Create tables according sqlalchemy data model.
Is not a complex migration tool like alembic, just creates tables that
does not exist::
./manage.py sqla:create_tables [--verbose] [meta_name]
'''
... | python | {
"resource": ""
} |
q37431 | Sqla.command_gen | train | def command_gen(self, *names):
'''
Runs generator functions.
Run `docs` generator function::
./manage.py sqla:gen docs
Run `docs` generator function with `count=10`::
./manage.py sqla:gen docs:10
'''
if not names:
sys.exit('Please p... | python | {
"resource": ""
} |
q37432 | _get_table_names | train | def _get_table_names(statement):
""" Returns table names found in the query.
NOTE. This routine would use the sqlparse parse tree, but vnames don't parse very well.
Args:
statement (sqlparse.sql.Statement): parsed by sqlparse sql statement.
Returns:
list of str
"""
parts = st... | python | {
"resource": ""
} |
q37433 | DatabaseBackend.install | train | def install(self, connection, partition, table_name=None, index_columns=None, materialize=False,
logger=None):
""" Installs partition's mpr to the database to allow to execute sql queries over mpr.
Args:
connection:
partition (orm.Partition):
material... | python | {
"resource": ""
} |
q37434 | DatabaseBackend.install_table | train | def install_table(self, connection, table, logger = None):
""" Installs all partitons of the table and create view with union of all partitons.
Args:
connection: connection to database who stores mpr data.
table (orm.Table):
"""
# first install all partitions of ... | python | {
"resource": ""
} |
q37435 | DatabaseBackend.query | train | def query(self, connection, query, fetch=True):
""" Creates virtual tables for all partitions found in the query and executes query.
Args:
query (str): sql query
fetch (bool): fetch result from database if True, do not fetch overwise.
"""
self.install_module(co... | python | {
"resource": ""
} |
q37436 | build | train | def build(id=None, name=None, revision=None,
temporary_build=False, timestamp_alignment=False,
no_build_dependencies=False,
keep_pod_on_failure=False,
force_rebuild=False,
rebuild_mode=common.REBUILD_MODES_DEFAULT):
"""
Trigger a BuildConfiguration by name or ID... | python | {
"resource": ""
} |
q37437 | get_build_configuration | train | def get_build_configuration(id=None, name=None):
"""
Retrieve a specific BuildConfiguration
"""
data = get_build_configuration_raw(id, name)
if data:
return utils.format_json(data) | python | {
"resource": ""
} |
q37438 | update_build_configuration | train | def update_build_configuration(id, **kwargs):
"""
Update an existing BuildConfiguration with new information
:param id: ID of BuildConfiguration to update
:param name: Name of BuildConfiguration to update
:return:
"""
data = update_build_configuration_raw(id, **kwargs)
if data:
... | python | {
"resource": ""
} |
q37439 | list_build_configurations_for_product | train | def list_build_configurations_for_product(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given Product.
"""
data = list_build_configurations_for_product_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.... | python | {
"resource": ""
} |
q37440 | list_build_configurations_for_project | train | def list_build_configurations_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given Project.
"""
data = list_build_configurations_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.... | python | {
"resource": ""
} |
q37441 | list_build_configurations_for_product_version | train | def list_build_configurations_for_product_version(product_id, version_id, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given ProductVersion
"""
data = list_build_configurations_for_project_raw(product_id, version_id, page_size, page_index, sort, q)
... | python | {
"resource": ""
} |
q37442 | add_dependency | train | def add_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Add an existing BuildConfiguration as a dependency to another BuildConfiguration.
"""
data = add_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | python | {
"resource": ""
} |
q37443 | remove_dependency | train | def remove_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
"""
Remove a BuildConfiguration from the dependency list of another BuildConfiguration
"""
data = remove_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | python | {
"resource": ""
} |
q37444 | list_product_versions_for_build_configuration | train | def list_product_versions_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
"""
List all ProductVersions associated with a BuildConfiguration
"""
data = list_product_versions_for_build_configuration_raw(id, name, page_size, page_index, sort, q)
if data:
... | python | {
"resource": ""
} |
q37445 | add_product_version_to_build_configuration | train | def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None):
"""
Associate an existing ProductVersion with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_json_list(... | python | {
"resource": ""
} |
q37446 | remove_product_version_from_build_configuration | train | def remove_product_version_from_build_configuration(id=None, name=None, product_version_id=None):
"""
Remove a ProductVersion from association with a BuildConfiguration
"""
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_j... | python | {
"resource": ""
} |
q37447 | list_revisions_of_build_configuration | train | def list_revisions_of_build_configuration(id=None, name=None, page_size=200, page_index=0, sort=""):
"""
List audited revisions of a BuildConfiguration
"""
data = list_revisions_of_build_configuration_raw(id, name, page_size, page_index, sort)
if data:
return utils.format_json_list(data) | python | {
"resource": ""
} |
q37448 | get_revision_of_build_configuration | train | def get_revision_of_build_configuration(revision_id, id=None, name=None):
"""
Get a specific audited revision of a BuildConfiguration
"""
data = get_revision_of_build_configuration_raw(revision_id, id, name)
if data:
return utils.format_json_list(data) | python | {
"resource": ""
} |
q37449 | list_build_configurations | train | def list_build_configurations(page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations
"""
data = list_build_configurations_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | {
"resource": ""
} |
q37450 | tzabbr_register | train | def tzabbr_register(abbr, name, region, zone, dst):
"""Register a new timezone abbreviation in the global registry.
If another abbreviation with the same name has already been registered it new
abbreviation will only be registered in region specific dictionary.
"""
newabbr = tzabbr()
newabbr.abbr = abbr
... | python | {
"resource": ""
} |
q37451 | create_license | train | def create_license(**kwargs):
"""
Create a new License
"""
License = create_license_object(**kwargs)
response = utils.checked_api_call(pnc_api.licenses, 'create_new', body=License)
if response:
return utils.format_json(response.content) | python | {
"resource": ""
} |
q37452 | get_license | train | def get_license(id):
"""
Get a specific License by either ID or fullname
"""
response = utils.checked_api_call(
pnc_api.licenses, 'get_specific', id= id)
if response:
return utils.format_json(response.content) | python | {
"resource": ""
} |
q37453 | delete_license | train | def delete_license(license_id):
"""
Delete a License by ID
"""
response = utils.checked_api_call(pnc_api.licenses, 'delete', id=license_id)
if response:
return utils.format_json(response.content) | python | {
"resource": ""
} |
q37454 | update_license | train | def update_license(license_id, **kwargs):
"""
Replace the License with given ID with a new License
"""
updated_license = pnc_api.licenses.get_specific(id=license_id).content
for key, value in iteritems(kwargs):
if value:
setattr(updated_license, key, value)
response = utils... | python | {
"resource": ""
} |
q37455 | list_licenses | train | def list_licenses(page_size=200, page_index=0, sort="", q=""):
"""
List all Licenses
"""
response = utils.checked_api_call(pnc_api.licenses, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(response.content) | python | {
"resource": ""
} |
q37456 | Resizer.transform | train | def transform(self, img, transformation, params):
'''
Apply transformations to the image.
New transformations can be defined as methods::
def do__transformationname(self, img, transformation, params):
'returns new image with transformation applied'
.... | python | {
"resource": ""
} |
q37457 | ResizeMixed.get_resizer | train | def get_resizer(self, size, target_size):
'''Choose a resizer depending an image size'''
sw, sh = size
if sw >= sh * self.rate:
return self.hor_resize
else:
return self.vert_resize | python | {
"resource": ""
} |
q37458 | Playlist.next_song | train | def next_song(self):
"""next song for player, calculated based on playback_mode"""
# 如果没有正在播放的歌曲,找列表里面第一首能播放的
if self.current_song is None:
return self._get_good_song()
if self.playback_mode == PlaybackMode.random:
next_song = self._get_good_song(random_=True)
... | python | {
"resource": ""
} |
q37459 | Playlist.previous_song | train | def previous_song(self):
"""previous song for player to play
NOTE: not the last played song
"""
if self.current_song is None:
return self._get_good_song(base=-1, direction=-1)
if self.playback_mode == PlaybackMode.random:
previous_song = self._get_good_s... | python | {
"resource": ""
} |
q37460 | AbstractPlayer.state | train | def state(self, value):
"""set player state, emit state changed signal
outer object should not set state directly,
use ``pause`` / ``resume`` / ``stop`` / ``play`` method instead.
"""
self._state = value
self.state_changed.emit(value) | python | {
"resource": ""
} |
q37461 | alter_poms | train | def alter_poms(pom_dir, additional_params, repo_url=None, mvn_repo_local=None):
"""
Runs mvn clean command with provided additional parameters to perform pom updates by pom-manipulation-ext.
"""
work_dir = os.getcwd()
os.chdir(pom_dir)
try:
if repo_url:
settings_filename = c... | python | {
"resource": ""
} |
q37462 | pom_contains_modules | train | def pom_contains_modules():
"""
Reads pom.xml in current working directory and checks, if there is non-empty modules tag.
"""
pom_file = None
try:
pom_file = open("pom.xml")
pom = pom_file.read()
finally:
if pom_file:
pom_file.close()
artifact = MavenArti... | python | {
"resource": ""
} |
q37463 | create_mirror_settings | train | def create_mirror_settings(repo_url):
"""
Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all
repositories to look at.
:param repo_url: the repository URL to use
:returns: filepath to the created file
"""
cwd = os.getcwd()
... | python | {
"resource": ""
} |
q37464 | API.search | train | def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
resp ... | python | {
"resource": ""
} |
q37465 | _init_index | train | def _init_index(root_dir, schema, index_name):
""" Creates new index or opens existing.
Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.
Returns:
tuple ((... | python | {
"resource": ""
} |
q37466 | DatasetWhooshIndex.reset | train | def reset(self):
""" Resets index by removing index directory. """
if os.path.exists(self.index_dir):
rmtree(self.index_dir)
self.index = None | python | {
"resource": ""
} |
q37467 | DatasetWhooshIndex._get_generic_schema | train | def _get_generic_schema(self):
""" Returns whoosh's generic schema of the dataset. """
schema = Schema(
vid=ID(stored=True, unique=True), # Object id
title=NGRAMWORDS(),
keywords=KEYWORD, # Lists of coverage identifiers, ISO time values and GVIDs, source names, sour... | python | {
"resource": ""
} |
q37468 | IdentifierWhooshIndex.search | train | def search(self, search_phrase, limit=None):
""" Finds identifier by search phrase. """
self._parsed_query = search_phrase
schema = self._get_generic_schema()
parser = QueryParser('name', schema=schema)
query = parser.parse(search_phrase)
class PosSizeWeighting(scoring.W... | python | {
"resource": ""
} |
q37469 | IdentifierWhooshIndex._get_generic_schema | train | def _get_generic_schema(self):
""" Returns whoosh's generic schema. """
schema = Schema(
identifier=ID(stored=True), # Partition versioned id
type=ID(stored=True),
name=NGRAM(phrase=True, stored=True, minsize=2, maxsize=8))
return schema | python | {
"resource": ""
} |
q37470 | PartitionWhooshIndex.all | train | def all(self):
""" Returns list with all indexed partitions. """
partitions = []
for partition in self.index.searcher().documents():
partitions.append(
PartitionSearchResult(dataset_vid=partition['dataset_vid'], vid=partition['vid'], score=1))
return partition... | python | {
"resource": ""
} |
q37471 | PartitionWhooshIndex._make_query_from_terms | train | def _make_query_from_terms(self, terms):
""" returns a FTS query for partition created from decomposed search terms.
args:
terms (dict or str):
returns:
str containing fts query.
"""
expanded_terms = self._expand_terms(terms)
cterms = ''
... | python | {
"resource": ""
} |
q37472 | PartitionWhooshIndex._from_to_as_term | train | def _from_to_as_term(self, frm, to):
""" Turns from and to into the query format.
Args:
frm (str): from year
to (str): to year
Returns:
FTS query str with years range.
"""
# The wackiness with the conversion to int and str, and adding ' ', ... | python | {
"resource": ""
} |
q37473 | SimSymbolicDbgMemory.copy | train | def copy(self, _):
"""
Return a copy of the SimMemory.
"""
#l.debug("Copying %d bytes of memory with id %s." % (len(self.mem), self.id))
c = SimSymbolicDbgMemory(
mem=self.mem.branch(),
memory_id=self.id,
endness=self.endness,
abstr... | python | {
"resource": ""
} |
q37474 | AmbrySeries.column | train | def column(self):
"""Return the ambry column"""
from ambry.orm.exc import NotFoundError
if not hasattr(self, 'partition'):
return None
if not self.name:
return None
try:
try:
return self.partition.column(self.name)
... | python | {
"resource": ""
} |
q37475 | get_handler | train | def get_handler(progname, address=None, proto=None, facility=None,
fmt=None, datefmt=None, **_):
"""Helper function to create a Syslog handler.
See `ulogger.syslog.SyslogHandlerBuilder` for arguments and
supported keyword arguments.
Returns:
(obj): Instance of `logging.SysLogHa... | python | {
"resource": ""
} |
q37476 | TargetRepositoryRest.repository_type | train | def repository_type(self, repository_type):
"""
Sets the repository_type of this TargetRepositoryRest.
:param repository_type: The repository_type of this TargetRepositoryRest.
:type: str
"""
allowed_values = ["MAVEN", "NPM", "COCOA_POD", "GENERIC_PROXY"]
if repo... | python | {
"resource": ""
} |
q37477 | worker | train | def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None):
""" Custom worker for bundle operations
:param inqueue:
:param outqueue:
:param initializer:
:param initargs:
:param maxtasks:
:return:
"""
from ambry.library import new_library
from ambry.run import ge... | python | {
"resource": ""
} |
q37478 | init_library | train | def init_library(database_dsn, accounts_password, limited_run = False):
"""Child initializer, setup in Library.process_pool"""
import os
import signal
# Have the child processes ignore the keyboard interrupt, and other signals. Instead, the parent will
# catch these, and clean up the children.
... | python | {
"resource": ""
} |
q37479 | unify_mp | train | def unify_mp(b, partition_name):
"""Unify all of the segment partitions for a parent partition, then run stats on the MPR file"""
with b.progress.start('coalesce_mp',0,message="MP coalesce {}".format(partition_name)) as ps:
r = b.unify_partition(partition_name, None, ps)
return r | python | {
"resource": ""
} |
q37480 | LibraryFilesystem._compose | train | def _compose(self, name, args, mkdir=True):
"""Get a named filesystem entry, and extend it into a path with additional
path arguments"""
from os.path import normpath
from ambry.dbexceptions import ConfigurationError
root = p = self._config.filesystem[name].format(root=self._root... | python | {
"resource": ""
} |
q37481 | LibraryFilesystem.compose | train | def compose(self, name, *args):
"""Compose, but don't create base directory"""
return self._compose(name, args, mkdir=False) | python | {
"resource": ""
} |
q37482 | LibraryFilesystem.database_dsn | train | def database_dsn(self):
"""Substitute the root dir into the database DSN, for Sqlite"""
if not self._config.library.database:
return 'sqlite:///{root}/library.db'.format(root=self._root)
return self._config.library.database.format(root=self._root) | python | {
"resource": ""
} |
q37483 | make_table_map | train | def make_table_map(table, headers):
"""Create a function to map from rows with the structure of the headers to the structure of the table."""
header_parts = {}
for i, h in enumerate(headers):
header_parts[h] = 'row[{}]'.format(i)
body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(... | python | {
"resource": ""
} |
q37484 | augment_pipeline | train | def augment_pipeline(pl, head_pipe=None, tail_pipe=None):
"""
Augment the pipeline by adding a new pipe section to each stage that has one or more pipes. Can be used for debugging
:param pl:
:param DebugPipe:
:return:
"""
for k, v in iteritems(pl):
if v and len(v) > 0:
... | python | {
"resource": ""
} |
q37485 | ReplaceWithDestHeader.process_header | train | def process_header(self, headers):
"""Ignore the incomming header and replace it with the destination header"""
return [c.name for c in self.source.dest_table.columns][1:] | python | {
"resource": ""
} |
q37486 | WriteToPartition.rate | train | def rate(self):
"""Report the insertion rate in records per second"""
end = self._end_time if self._end_time else time.time()
return self._count / (end - self._start_time) | python | {
"resource": ""
} |
q37487 | Pipeline._subset | train | def _subset(self, subset):
"""Return a new pipeline with a subset of the sections"""
pl = Pipeline(bundle=self.bundle)
for group_name, pl_segment in iteritems(self):
if group_name not in subset:
continue
pl[group_name] = pl_segment
return pl | python | {
"resource": ""
} |
q37488 | Pipeline.configure | train | def configure(self, pipe_config):
"""Configure from a dict"""
# Create a context for evaluating the code for each pipeline. This removes the need
# to qualify the class names with the module
import ambry.etl
import sys
# ambry.build comes from ambry.bundle.files.PythonSo... | python | {
"resource": ""
} |
q37489 | Pipeline.replace | train | def replace(self, repl_class, replacement, target_segment_name=None):
"""Replace a pipe segment, specified by its class, with another segment"""
for segment_name, pipes in iteritems(self):
if target_segment_name and segment_name != target_segment_name:
raise Exception()
... | python | {
"resource": ""
} |
q37490 | PostgreSQLBackend.install | train | def install(self, connection, partition, table_name=None, columns=None, materialize=False,
logger=None):
""" Creates FDW or materialize view for given partition.
Args:
connection: connection to postgresql
partition (orm.Partition):
materialize (boolea... | python | {
"resource": ""
} |
q37491 | PostgreSQLBackend.close | train | def close(self):
""" Closes connection to database. """
if getattr(self, '_connection', None):
logger.debug('Closing postgresql connection.')
self._connection.close()
self._connection = None
if getattr(self, '_engine', None):
self._engine.dispose() | python | {
"resource": ""
} |
q37492 | PostgreSQLBackend._get_mpr_table | train | def _get_mpr_table(self, connection, partition):
""" Returns name of the postgres table who stores mpr data.
Args:
connection: connection to postgres db who stores mpr data.
partition (orm.Partition):
Returns:
str:
Raises:
MissingTableEr... | python | {
"resource": ""
} |
q37493 | PostgreSQLBackend._add_partition | train | def _add_partition(self, connection, partition):
""" Creates FDW for the partition.
Args:
connection:
partition (orm.Partition):
"""
logger.debug('Creating foreign table for partition.\n partition: {}'.format(partition.name))
with connection.cursor() ... | python | {
"resource": ""
} |
q37494 | PostgreSQLBackend._get_connection | train | def _get_connection(self):
""" Returns connection to the postgres database.
Returns:
connection to postgres database who stores mpr data.
"""
if not getattr(self, '_connection', None):
logger.debug(
'Creating new connection.\n dsn: {}'
... | python | {
"resource": ""
} |
q37495 | PostgreSQLBackend._execute | train | def _execute(self, connection, query, fetch=True):
""" Executes given query and returns result.
Args:
connection: connection to postgres database who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query result and return it. If Fals... | python | {
"resource": ""
} |
q37496 | CPI.get | train | def get(self, date=datetime.date.today(), country=None):
"""
Get the CPI value for a specific time. Defaults to today. This uses
the closest method internally but sets limit to one day.
"""
if not country:
country = self.country
if country == "all":
... | python | {
"resource": ""
} |
q37497 | Reverse.as_url | train | def as_url(self):
'''
Reverse object converted to `web.URL`.
If Reverse is bound to env:
* try to build relative URL,
* use current domain name, port and scheme as default
'''
if '' in self._scope:
return self._finalize().as_url
if no... | python | {
"resource": ""
} |
q37498 | URL.from_url | train | def from_url(cls, url, show_host=True):
'''Parse string and get URL instance'''
# url must be idna-encoded and url-quotted
if six.PY2:
if isinstance(url, six.text_type):
url = url.encode('utf-8')
parsed = urlparse(url)
netloc = parsed.netloc.d... | python | {
"resource": ""
} |
q37499 | URL.qs_set | train | def qs_set(self, *args, **kwargs):
'''Set values in QuerySet MultiDict'''
if args and kwargs:
raise TypeError('Use positional args or keyword args not both')
query = self.query.copy()
if args:
mdict = MultiDict(args[0])
for k in mdict.keys():
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.