code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_distributed_artifacts_with_http_info(id, **kwargs) else: (data) = self.get_distributed_artifacts_with_http_info(id, **kwargs) return data
def get_distributed_artifacts(self, id, **kwargs)
Get the artifacts distributed in this milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ppri...
1.455681
1.660789
0.8765
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_distributed_builds_with_http_info(id, **kwargs) else: (data) = self.get_distributed_builds_with_http_info(id, **kwargs) return data
def get_distributed_builds(self, id, **kwargs)
Gets the set of builds which produced artifacts distributed/shipped in a Product Milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callba...
1.424088
1.680325
0.847508
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_performed_builds_with_http_info(id, **kwargs) else: (data) = self.get_performed_builds_with_http_info(id, **kwargs) return data
def get_performed_builds(self, id, **kwargs)
Gets the set of builds performed during in a Product Milestone cycle This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response):...
1.422186
1.656868
0.858358
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.remove_distributed_artifact_with_http_info(id, artifact_id, **kwargs) else: (data) = self.remove_distributed_artifact_with_http_info(id, artifact_id, **kwargs) return data
def remove_distributed_artifact(self, id, artifact_id, **kwargs)
Removes an artifact from the specified product milestone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>>...
1.413205
1.564328
0.903394
if self._playlists is None: playlists_data = self._api.user_playlists(self.identifier) playlists = [] for playlist_data in playlists_data: playlist = _deserialize(playlist_data, PlaylistSchema) playlists.append(playlist) se...
def playlists(self)
获取用户创建的歌单 如果不是用户本人,则不能获取用户默认精选集
2.791321
2.834237
0.984858
if self._fav_songs is None: songs_data = self._api.user_favorite_songs(self.identifier) self._fav_songs = [] if not songs_data: return for song_data in songs_data: song = _deserialize(song_data, NestedSongSchema) ...
def fav_songs(self)
FIXME: 支持获取所有的收藏歌曲
3.267605
3.070848
1.064073
song_exts = ['mp3', 'ogg', 'wma', 'm4a'] exts = song_exts paths = paths or [Library.DEFAULT_MUSIC_FOLDER] depth = depth if depth <= 3 else 3 media_files = [] for directory in paths: logger.debug('正在扫描目录(%s)...', directory) media_files.exte...
def scan(self, paths=None, depth=2)
scan media files in all paths
4.107951
3.876004
1.059842
'''Calls each nested handler until one of them returns nonzero result. If any handler returns `None`, it is interpreted as "request does not match, the handler has nothing to do with it and `web.cases` should try to call the next handler".''' for handler in self.handlers: ...
def cases(self, env, data)
Calls each nested handler until one of them returns nonzero result. If any handler returns `None`, it is interpreted as "request does not match, the handler has nothing to do with it and `web.cases` should try to call the next handler".
8.274689
1.913214
4.325019
coming_comment = None win32_name = None territory = None parser = genshi.input.XMLParser(StringIO(windows_zones_xml)) map_zones = {} zone_comments = {} for kind, data, _ in parser: if kind == genshi.core.START and str(data[0]) == "mapZone": attrs = data[1] win32_name, territory, olson_...
def create_win32tz_map(windows_zones_xml)
Creates a map between Windows and Olson timezone names. Args: windows_zones_xml: The CLDR XML mapping. Yields: (win32_name, olson_name, comment)
2.889873
2.752656
1.049849
windows_zones_xml = download_cldr_win32tz_map_xml() source_hash = hashlib.md5(windows_zones_xml).hexdigest() if hasattr(windows_zones_xml, "decode"): windows_zones_xml = windows_zones_xml.decode("utf-8") map_zones = create_win32tz_map(windows_zones_xml) map_dir = os.path.dirname(os.path.abspath(__fil...
def update_stored_win32tz_map()
Downloads the cldr win32 timezone map and stores it in win32tz_map.py.
2.617029
2.539854
1.030386
mo = self._storage[page_idx - self._page_addr] #print filter(lambda x: x != None, self._storage) if mo is None and hasattr(self, "from_dbg"): byte_val = get_debugger().get_byte(page_idx) mo = SimMemoryObject(claripy.BVV(byte_val, 8), page_idx) self._s...
def load_mo(self, state, page_idx)
Loads a memory object from memory. :param page_idx: the index into the page :returns: a tuple of the object
5.12326
5.267731
0.972574
items = [] if start > self._page_addr + self._page_size or end < self._page_addr: l.warning("Calling load_slice on the wrong page.") return items for addr in range(max(start, self._page_addr), min( end, self._page_addr + self._page_size)): ...
def load_slice(self, state, start, end)
Return the memory objects overlapping with the provided slice. :param start: the start address :param end: the end address (non-inclusive) :returns: tuples of (starting_addr, memory_object)
4.231714
3.9101
1.082252
result = [] end = addr + num_bytes for page_addr in self._containing_pages(addr, end): try: #print "Getting page %x" % (page_addr // self._page_size) page = self._get_page(page_addr // self._page_size) #print "... got it" ...
def load_objects(self, addr, num_bytes, ret_on_segv=False)
Load memory objects from paged memory. :param addr: Address to start loading. :param num_bytes: Number of bytes to load. :param bool ret_on_segv: True if you want load_bytes to return directly when a SIGSEV is triggered, otherwise a SimSegfaultError will be rais...
4.472154
4.644174
0.96296
return set([self[i] for i in self.addrs_for_name(n)])
def memory_objects_for_name(self, n)
Returns a set of :class:`SimMemoryObjects` that contain expressions that contain a variable with the name of `n`. This is useful for replacing those values in one fell swoop with :func:`replace_memory_object()`, even if they have been partially overwritten.
7.409789
7.795815
0.950483
return set([self[i] for i in self.addrs_for_hash(n)])
def memory_objects_for_hash(self, n)
Returns a set of :class:`SimMemoryObjects` that contain expressions that contain a variable with the hash `h`.
8.249761
6.254521
1.319008
if self.state.solver.symbolic(addr): raise SimMemoryError( "page permissions cannot currently be looked up for symbolic addresses") if isinstance(addr, claripy.ast.bv.BV): addr = self.state.solver.eval(addr) page_num = addr // self._page_size ...
def permissions(self, addr, permissions=None)
Returns the permissions for a page at address `addr`. If optional argument permissions is given, set page permissions to that prior to returning permissions.
3.24733
3.002195
1.081652
def wrapper(f): return CallInterval(f, freq, **kwargs) return wrapper
def call_interval(freq, **kwargs)
Decorator for the CallInterval wrapper
6.644883
3.225604
2.060043
if self.start and self.start.state == 'done' and kwargs.get('log_action') != 'done': raise ProgressLoggingError("Can't add -- process section is done") self.augment_args(args, kwargs) kwargs['log_action'] = kwargs.get('log_action', 'add') rec = Process(**kwargs) ...
def add(self, *args, **kwargs)
Add a new record to the section
7.236055
6.666171
1.085489
self.augment_args(args, kwargs) kwargs['log_action'] = kwargs.get('log_action', 'update') if not self.rec: return self.add(**kwargs) else: for k, v in kwargs.items(): # Don't update object; use whatever was set in the original record ...
def update(self, *args, **kwargs)
Update the last section record
5.916124
5.224744
1.132328
if not self._ai_rec_id: self._ai_rec_id = self.add(*args, **kwargs) else: au_save = self._ai_rec_id self.update(*args, **kwargs) self._ai_rec_id = au_save return self._ai_rec_id
def add_update(self, *args, **kwargs)
A records is added, then on subsequent calls, updated
3.203268
3.053889
1.048914
kwargs['state'] = 'done' self.update(*args, **kwargs) self.rec = None
def update_done(self, *args, **kwargs)
Clear out the previous update
7.03011
6.18945
1.135822
kwargs['state'] = 'done' pr_id = self.add(*args, log_action='done', **kwargs) self._session.query(Process).filter(Process.group == self._group).update({Process.state: 'done'}) self.start.state = 'done' self._session.commit() return pr_id
def done(self, *args, **kwargs)
Mark the whole ProgressSection as done
6.151213
6.165591
0.997668
return ProgressSection(self, self._session, phase, stage, self._logger, **kwargs)
def start(self, phase, stage, **kwargs)
Start a new routine, stage or phase
13.986095
15.214364
0.919269
return (self._session.query(Process) .filter(Process.d_vid == self._d_vid)).all()
def records(self)
Return all start records for this the dataset, grouped by the start record
16.341488
13.375665
1.221733
return (self._session.query(Process) .filter(Process.d_vid == self._d_vid) .filter(Process.log_action == 'start') ).all()
def starts(self)
Return all start records for this the dataset, grouped by the start record
9.886422
8.249977
1.198358
return self._session.query(Process).filter(Process.d_vid == self._d_vid)
def query(self)
Return all start records for this the dataset, grouped by the start record
15.915401
13.063746
1.218288
return (self._session.query(Process) .filter(Process.d_vid == self._d_vid) .filter(Process.exception_class != None) .order_by(Process.modified)).all()
def exceptions(self)
Return all start records for this the dataset, grouped by the start record
8.221809
7.165403
1.147432
# Deleting seems to be really weird and unrelable. self._session \ .query(Process) \ .filter(Process.d_vid == self._d_vid) \ .delete(synchronize_session='fetch') for r in self.records: self._session.delete(r) self._session.commi...
def clean(self)
Delete all of the records
7.104455
6.639625
1.070009
from ambry.orm.config import BuildConfigGroupAccessor # It is a lightweight object, so no need to cache return BuildConfigGroupAccessor(self.dataset, 'buildstate', self._session)
def build(self)
Access build configuration values as attributes. See self.process for a usage example
22.112694
20.837408
1.061202
_ignore_log_keys = set(logging.makeLogRecord({}).__dict__) def _json_format(record): extras = ' '.join( "%s=%s" % (k, record.__dict__[k]) for k in set(record.__dict__).difference(_ignore_log_keys)) if extras: record.msg = "%s %s" % (record.msg, extras...
def configure_logging(add_handler, log=log)
Configure log records. If adding a handler, make the formatter print all passed in key:value data. ie log.extra('msg', extra=dict(a=1)) generates 'msg a=1' `add_handler` (True, False, None, or Handler instance) if True, add a logging.StreamHandler() instance if False, do not ...
2.402998
2.447893
0.98166
allowed_values = ["DOCKER_IMAGE", "VIRTUAL_MACHINE_RAW", "VIRTUAL_MACHINE_QCOW2", "LOCAL_WORKSPACE"] if system_image_type not in allowed_values: raise ValueError( "Invalid value for `system_image_type` ({0}), must be one of {1}" .format(system_image_t...
def system_image_type(self, system_image_type)
Sets the system_image_type of this BuildEnvironmentRest. :param system_image_type: The system_image_type of this BuildEnvironmentRest. :type: str
2.264638
2.255283
1.004148
qs = Page.objects.public() qs = qs.exclude(application_namespace=None) qs = qs.order_by('application_namespace') try: application_namespaces = list( qs.distinct('application_namespace').values_list( 'application_namespace', flat=True)) except NotImplementedE...
def get_public_cms_app_namespaces()
:return: a tuple() with all cms app namespaces
3.709872
3.641685
1.018724
pages = Page.objects.public() urls = [page.get_absolute_url(language=language_code) for page in pages] urls.sort() return tuple(urls)
def get_public_cms_page_urls(*, language_code)
:param language_code: e.g.: "en" or "de" :return: Tuple with all public urls in the given language
3.289788
3.14653
1.045529
from collections import defaultdict docs = defaultdict(list) for k, v in self.items(): if 'source' in v: docs[v.source].append(dict(v.items())) return docs
def group_by_source(self)
Return a dict of all of the docs, with the source associated with the doc as a key
4.437841
3.8885
1.141273
newpath = abspath(joinpath(self.path, normpath(path))) if not newpath.startswith(self.path): raise InsecurePath("%s is not a child of %s" % (newpath, self.path)) return self.clonePath(newpath)
def preauthChild(self, path)
Use me if `path' might have slashes in it, but you know they're safe. (NOT slashes at the beginning. It still needs to be a _child_).
3.671182
3.610118
1.016915
p = self.path for child in paths: jp = joinpath(p, child) if exists(jp): return self.clonePath(jp)
def childSearchPreauth(self, *paths)
Return my first existing child with a name in 'paths'. paths is expected to be a list of *pre-secured* path fragments; in most cases this will be specified by a system administrator and not an arbitrary user. If no appropriately-named children exist, this will return None.
5.947833
7.156656
0.831091
p = self.path for ext in exts: if not ext and self.exists(): return self if ext == '*': basedot = basename(p)+'.' for fn in listdir(dirname(p)): if fn.startswith(basedot): return ...
def siblingExtensionSearch(self, *exts)
Attempt to return a path with my name, given multiple possible extensions. Each extension in exts will be tested and the first path which exists will be returned. If no path exists, None will be returned. If '' is in exts, then if the file referred to by this path exists, 'self' will ...
4.124077
3.685236
1.119081
import glob path = self.path[-1] == '/' and self.path + pattern or slash.join([self.path, pattern]) return map(self.clonePath, glob.glob(path))
def globChildren(self, pattern)
Assuming I am representing a directory, return a list of FilePaths representing my children that match the given pattern.
6.623937
7.604391
0.871067
fdint = os.open(self.path, (os.O_EXCL | os.O_CREAT | os.O_RDWR)) # XXX TODO: 'name' attribute of returned files is not mutable or # settable via fdopen, so this file is slighly less functional than the # on...
def create(self)
Exclusively create a file, only if this file previously did not exist.
11.954234
10.550529
1.133046
sib = self.parent().child(_secureEnoughString() + self.basename()) sib.requireCreate() return sib
def temporarySibling(self)
Create a path naming a temporary sibling of this path in a secure fashion.
29.990519
14.871249
2.016678
parts = L.split() device = parts[2] if len(parts) == 7: factory = partitionstat else: factory = diskstat return device, factory(*map(int, parts[3:]))
def parseDiskStatLine(L)
Parse a single line from C{/proc/diskstats} into a two-tuple of the name of the device to which it corresponds (ie 'hda') and an instance of the appropriate record type (either L{partitionstat} or L{diskstat}).
5.279853
3.663176
1.441332
possibilities = [] cwd = os.getcwd() with file(procMounts, 'rb') as f: for L in f: parts = L.split() if cwd.startswith(parts[1]): possibilities.append((len(parts[1]), parts[0])) possibilities.sort() try: return possibilities[-1][-1] ex...
def discoverCurrentWorkingDevice(procMounts='/proc/self/mounts')
Return a short string naming the device which backs the current working directory, ie C{/dev/hda1}.
3.292739
3.187761
1.032932
def runner(): return BenchmarkProcess.spawn( executable=sys.executable, args=['-Wignore'] + args, path=path.path, env=os.environ) return runner
def makeBenchmarkRunner(path, args)
Make a function that will run two Python processes serially: first one which calls the setup function from the given file, then one which calls the execute function from the given file.
7.509778
8.764758
0.856815
os.write(BenchmarkProcess.BACKCHANNEL_OUT, BenchmarkProcess.START) response = util.untilConcludes(os.read, BenchmarkProcess.BACKCHANNEL_IN, 1) if response != BenchmarkProcess.START: raise RuntimeError( "Parent process responded with %r instead of START " % (response,))
def start()
Start recording stats. Call this from a benchmark script when your setup is done. Call this at most once. @raise RuntimeError: Raised if the parent process responds with anything other than an acknowledgement of this message.
8.56296
5.819013
1.471549
os.write(BenchmarkProcess.BACKCHANNEL_OUT, BenchmarkProcess.STOP) response = util.untilConcludes(os.read, BenchmarkProcess.BACKCHANNEL_IN, 1) if response != BenchmarkProcess.STOP: raise RuntimeError( "Parent process responded with %r instead of STOP" % (response,))
def stop()
Stop recording stats. Call this from a benchmark script when the code you want benchmarked has finished. Call this exactly the same number of times you call L{start} and only after calling it. @raise RuntimeError: Raised if the parent process responds with anything other than an acknowledgement of th...
7.296875
5.296005
1.377807
name = sys.argv[1] path = filepath.FilePath('.stat').temporarySibling() path.makedirs() func = makeBenchmarkRunner(path, sys.argv[1:]) try: bench(name, path, func) finally: path.remove()
def main()
Run me with the filename of a benchmark script as an argument. I will time it and append the results to a file named output in the current working directory.
11.819451
10.99365
1.075116
d = defer.Deferred() proto = cls(d, filepath.FilePath(path)) if spawnProcess is None: spawnProcess = reactor.spawnProcess spawnProcess( proto, executable, [executable] + args, path=path, env=env, ...
def spawn(cls, executable, args, path, env, spawnProcess=None)
Run an executable with some arguments in the given working directory with the given environment variables. Returns a Deferred which fires with a two-tuple of (exit status, output list) if the process terminates without timing out or being killed by a signal. Otherwise, the Deferred err...
3.624822
3.935025
0.921169
resp = requests.get(ORCID_PUBLIC_BASE_URL + unicode(orcid_id), headers=BASE_HEADERS) json_body = resp.json() return Author(json_body)
def get(orcid_id)
Get an author based on an ORCID identifier.
5.456378
4.930788
1.106594
value = context.get(contextFactory, _NOT_SPECIFIED) if value is not _NOT_SPECIFIED: return contextReceiver(value) else: return context.call({contextFactory: contextFactory()}, _contextualize, contextFactory, contextReceiver)
def _contextualize(contextFactory, contextReceiver)
Invoke a callable with an argument derived from the current execution context (L{twisted.python.context}), or automatically created if none is yet present in the current context. This function, with a better name and documentation, should probably be somewhere in L{twisted.python.context}. Calling con...
4.895685
6.02138
0.81305
if len(a) == 1: attributeNames = a[0].split() elif len(a) == 0: if not kw: raise TypeError("Attempted to define a record with no attributes.") attributeNames = kw.keys() attributeNames.sort() else: raise TypeError( "record must be called w...
def record(*a, **kw)
Are you tired of typing class declarations that look like this:: class StuffInfo: def __init__(self, a=None, b=None, c=None, d=None, e=None, f=None, g=None, h=None, i=None, j=None): self.a = a self.b = b self.c = c ...
4.459349
4.257309
1.047457
ID = id(stuff) if ID in self.active: return '%s(...)' % (stuff.__class__.__name__,) else: try: self.active[ID] = stuff return thunk(stuff) finally: del self.active[ID]
def recursiveRepr(self, stuff, thunk=repr)
Recursive repr().
3.021024
3.008134
1.004285
ms_sentence_map = dict() sentence_pattern = re.compile(r'\[(\d+(:\d+){0,2}(\.\d+)?)\]') lines = content.splitlines() for line in lines: m = sentence_pattern.search(line, 0) if m: time_str = m.group(1) mileseconds = 0 unit = 1000 t_seq ...
def parse(content)
Reference: https://github.com/osdlyrics/osdlyrics/blob/master/python/lrc.py >>> parse("[00:00.00] 作曲 : 周杰伦\\n[00:01.00] 作词 : 周杰伦\\n") {0.0: ' 作曲 : 周杰伦', 1000.0: ' 作词 : 周杰伦'}
3.125642
2.911688
1.073481
data = create_product_raw(name, abbreviation, **kwargs) if data: return utils.format_json(data)
def create_product(name, abbreviation, **kwargs)
Create a new Product
5.216238
4.952087
1.053341
content = update_product_raw(product_id, **kwargs) if content: return utils.format_json(content)
def update_product(product_id, **kwargs)
Update a Product with new information
5.565836
6.328635
0.879469
content = get_product_raw(id, name) if content: return utils.format_json(content)
def get_product(id=None, name=None)
Get a specific Product by name or ID
7.021668
7.218836
0.972687
content = list_versions_for_product_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content)
def list_versions_for_product(id=None, name=None, page_size=200, page_index=0, sort='', q='')
List all ProductVersions for a given Product
3.136856
3.524557
0.89
content = list_products_raw(page_size, page_index, sort, q) if content: return utils.format_json_list(content)
def list_products(page_size=200, page_index=0, sort="", q="")
List all Products
4.092548
4.33032
0.945091
submit_set = [] data_map = {} for address, o in self.gen: submit_set.append(address) data_map[address] = o if len(submit_set) >= self.submit_size: results = self._send(submit_set) submit_set = [] for...
def geocode(self)
A Generator that reads from the address generators and returns geocode results. The generator yields ( address, geocode_results, object)
2.723504
2.309762
1.179128
all_migrations = _get_all_migrations() logger.debug('Collected migrations: {}'.format(all_migrations)) for version, modname in all_migrations: if _is_missed(connection, version) and version <= SCHEMA_VERSION: logger.info('Missed migration: {} migration is missed. Migrating...'.form...
def migrate(connection, dsn)
Collects all migrations and applies missed. Args: connection (sqlalchemy connection):
5.207335
5.332089
0.976603
assert name, 'Name of the migration can not be empty.' from . import migrations # Find next number # package = migrations prefix = package.__name__ + '.' all_versions = [] for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix): version = int(modname....
def create_migration_template(name)
Creates migration file. Returns created file name. Args: name (str): name of the migration. Returns: str: name of the migration file.
3.216454
3.186412
1.009428
if connection.engine.name == 'sqlite': version = connection.execute('PRAGMA user_version').fetchone()[0] if version == 0: raise VersionIsNotStored return version elif connection.engine.name == 'postgresql': try: r = connection\ .execu...
def get_stored_version(connection)
Returns database version. Args: connection (sqlalchemy connection): Raises: Assuming user_version pragma (sqlite case) and user_version table (postgresql case) exist because they created with the database creation. Returns: int: version of the database.
2.947313
2.713926
1.085996
try: version = get_stored_version(connection) except VersionIsNotStored: logger.debug('Version not stored in the db: assuming new database creation.') version = SCHEMA_VERSION _update_version(connection, version) assert isinstance(version, int) if version > 10 and v...
def _validate_version(connection, dsn)
Performs on-the-fly schema updates based on the models version. Raises: DatabaseError: if user uses old sqlite database.
6.105245
6.008781
1.016054
stored_version = get_stored_version(connection) actual_version = SCHEMA_VERSION assert isinstance(stored_version, int) assert isinstance(actual_version, int) assert stored_version <= actual_version, \ 'Db version can not be greater than models version. Update your source code.' retu...
def _migration_required(connection)
Returns True if ambry models do not match to db tables. Otherwise returns False.
4.718086
3.927874
1.201181
if connection.engine.name == 'sqlite': connection.execute('PRAGMA user_version = {}'.format(version)) elif connection.engine.name == 'postgresql': connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_SCHEMA_NAME))) connection.execute(DDL('CREATE SCHEMA IF NOT E...
def _update_version(connection, version)
Updates version in the db to the given version. Args: connection (sqlalchemy connection): sqlalchemy session where to update version. version (int): version of the migration.
2.372481
2.350693
1.009269
from . import migrations package = migrations prefix = package.__name__ + '.' all_migrations = [] for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix): version = int(modname.split('.')[-1].split('_')[0]) all_migrations.append((version, modname)) a...
def _get_all_migrations()
Returns sorted list of all migrations. Returns: list of (int, str) tuples: first elem of the tuple is migration number, second if module name.
2.514506
2.528851
0.994327
if not self.exists(): self._create_path() self.create_tables() return True return False
def create(self)
Create the database from the base SQL.
8.658475
6.062016
1.428316
if self.driver == 'sqlite' and 'memory' not in self.dsn and self.dsn != 'sqlite://': dir_ = os.path.dirname(self.path) if dir_ and not os.path.exists(dir_): try: # Multiple process may try to make, so it could already # ...
def _create_path(self)
Create the path to hold the database, if one wwas specified.
4.961311
4.420154
1.12243
if self.driver == 'sqlite' and not os.path.exists(self.path): return False # init engine self.engine try: # Since we are using the connection, rather than the session, need to # explicitly set the search path. from sqlalchemy.e...
def exists(self)
Return True if the database exists, or for Sqlite, which will create the file on the first reference, the file has been initialized with the root config
5.063133
4.444679
1.139145
if not self._engine: if 'postgres' in self.driver: if 'connect_args' not in self.engine_kwargs: self.engine_kwargs['connect_args'] = { 'application_name': '{}:{}'.format(self._application_prefix, os.getpid()) ...
def engine(self)
return the SqlAlchemy engine for this database.
2.870678
2.817751
1.018784
if not self._connection: logger.debug('Opening connection to: {}'.format(self.dsn)) self._connection = self.engine.connect() logger.debug('Opened connection to: {}'.format(self.dsn)) # logger.debug("Opening connection to: {}".format(self.dsn)) return...
def connection(self)
Return an SqlAlchemy connection.
3.007328
2.62721
1.144685
from sqlalchemy.orm import sessionmaker from sqlalchemy.event import listen if not self.Session: self.Session = sessionmaker(bind=self.engine) if not self._session: self._session = self.Session() # set the search path if self._s...
def session(self)
Return a SqlAlchemy session.
3.347631
3.061436
1.093484
from sqlalchemy import MetaData metadata = MetaData(bind=self.engine, schema=self._schema) metadata.reflect(self.engine) return metadata
def metadata(self)
Return an SqlAlchemy MetaData object, bound to the engine.
5.00861
3.422692
1.463354
try: self.session.query(Dataset).filter_by(id=ROOT_CONFIG_NAME).one() self.close_session() except NoResultFound: o = Dataset( id=ROOT_CONFIG_NAME, vid=ROOT_CONFIG_NAME_V, name=ROOT_CONFIG_NAME, ...
def _add_config_root(self)
Adds the root dataset, which holds configuration values for the database.
3.968815
3.564465
1.113439
ds = Dataset(*args, **kwargs) try: self.session.add(ds) self.session.commit() ds._database = self return ds except IntegrityError as e: self.session.rollback() raise ConflictError( "Can't create da...
def new_dataset(self, *args, **kwargs)
Creates a new dataset :param args: Positional args passed to the Dataset constructor. :param kwargs: Keyword args passed to the Dataset constructor. :return: :class:`ambry.orm.Dataset` :raises: :class:`ambry.orm.ConflictError` if the a Dataset records already exists with the given vid
4.32906
4.161313
1.040311
ds = self.dataset(ROOT_CONFIG_NAME_V) ds._database = self return ds
def root_dataset(self)
Return the root dataset, which hold configuration values for the library
24.037916
19.127422
1.256725
return self.session.query(Dataset).filter(Dataset.vid != ROOT_CONFIG_NAME_V).one()
def package_dataset(self)
For sqlite bundle packages, return the first ( and only ) dataset
32.153706
21.253338
1.512878
ref = str(ref) try: ds = self.session.query(Dataset).filter(Dataset.vid == ref).one() except NoResultFound: ds = None if not ds: try: ds = self.session \ .query(Dataset) \ .filter(Data...
def dataset(self, ref, load_all=False, exception=True)
Return a dataset, given a vid or id :param ref: Vid or id for a dataset. If an id is provided, will it will return the one with the largest revision number :param load_all: Use a query that eagerly loads everything. :return: :class:`ambry.orm.Dataset`
2.107651
1.933486
1.090078
return self.session.query(Dataset).filter(Dataset.vid != ROOT_CONFIG_NAME_V).all()
def datasets(self)
Return all datasets :return:
25.467743
27.907412
0.91258
from ambry.orm import Code, Column, Table, Partition, ColumnStat, Process ssq = self.session.query ssq(Process).filter(Process.d_vid == ds.vid).delete() ssq(Code).filter(Code.d_vid == ds.vid).delete() ssq(ColumnStat).filter(ColumnStat.d_vid == ds.vid).delete() ...
def delete_tables_partitions(self, ds)
Fast delete of all of a datasets codes, columns, partitions and tables
2.987738
2.807677
1.064132
from ambry.orm import Partition ssq = self.session.query ssq(Process).filter(Process.d_vid == ds.vid).delete() ssq(Code).filter(Code.d_vid == ds.vid).delete() ssq(ColumnStat).filter(ColumnStat.d_vid == ds.vid).delete() ssq(Partition).filter(Partition.d_vid == d...
def delete_partitions(self, ds)
Fast delete of all of a datasets codes, columns, partitions and tables
3.713305
3.325244
1.116702
from ambry.orm import Table, Column, Partition, File, ColumnStat, Code, \ DataSource, SourceTable, SourceColumn tables = [Table, Column, Partition, File, ColumnStat, Code, SourceTable, SourceColumn, DataSource] return self._copy_dataset_copy(ds, tables, incver, cb, **kwarg...
def copy_dataset(self, ds, incver=False, cb=None, **kwargs)
Copy a dataset into the database. :param ds: The source dataset to copy :param cb: A progress callback, taking two parameters: cb(message, num_records) :return:
6.401648
7.292011
0.877899
from ambry.orm import File tables = [File] return self._copy_dataset_copy(ds, tables, incver, cb, **kwargs)
def copy_dataset_files(self, ds, incver=False, cb=None, **kwargs)
Copy only files and configs into the database. :param ds: The source dataset to copy :param cb: A progress callback, taking two parameters: cb(message, num_records) :return:
7.452972
7.836803
0.951022
from sqlalchemy import text # Name of sequence id column in the child c_seq_col = child_table_class.sequence_id.property.columns[0].name p_seq_col = getattr(parent_table_class, c_seq_col).property.columns[0].name p_vid_col = parent_table_class.vid.property.columns[0]...
def next_sequence_id(self, parent_table_class, parent_vid, child_table_class)
Get the next sequence id for child objects for a parent object that has a child sequence field
2.63322
2.661161
0.989501
orig_schemas = {} # These schema shenanigans are almost certainly wrong. # But they are expedient. For Postgres, it puts the library # tables in the Library schema. We need to change the schema for all tables in case # the table we are creating references another table...
def create_table(table, connection, schema=None)
Create a single table, primarily used din migrations
8.524288
8.522838
1.00017
result = None while 1: if deferred is None: deferred = defer.Deferred() try: result = g.next() except StopIteration: deferred.callback(result) return deferred except: deferred.errback() return deferred ...
def _deferGenerator(g, deferred=None)
See L{waitForDeferred}.
5.394283
5.350878
1.008112
'''Modifies decorated function to return its locals''' @functools.wraps(func) def wrap(*args, **kwargs): frames = [] def tracer(frame, event, arg): # pragma: no cover # coverage does not work in this function because the tracer # is deactivated here fram...
def return_locals(func)
Modifies decorated function to return its locals
2.827299
2.734594
1.033901
'''Creates dictionary to be passed as `binds` parameter to `sqlalchemy.orm.sessionmaker()` from dictionary mapping models module name to connection URI that should be used for these models. Models module must have `metadata` attribute. `package` when set must be a package or package name for all mod...
def multidb_binds(databases, package=None, engine_params=None)
Creates dictionary to be passed as `binds` parameter to `sqlalchemy.orm.sessionmaker()` from dictionary mapping models module name to connection URI that should be used for these models. Models module must have `metadata` attribute. `package` when set must be a package or package name for all models mod...
5.308594
3.000982
1.768952
class RequiredAttribute(attribute): def get(self): if requiredAttributeName not in self.__dict__: raise AttributeError( ('Required attribute %r has not been changed' ' from its default value on %r' % ( requ...
def requiredAttribute(requiredAttributeName)
Utility for defining attributes on base classes/mixins which require their values to be supplied by their derived classes. C{None} is a common, but almost never suitable default value for these kinds of attributes, as it may cause operations in the derived class to fail silently in peculiar ways. If a...
3.425411
3.018657
1.134747
response = utils.checked_api_call(pnc_api.builds_running, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q) if response: return response.content
def list_builds(page_size=200, page_index=0, sort="", q="")
List all builds :param page_size: number of builds returned per query :param sort: RSQL sorting query :param q: RSQL query :return:
4.44944
5.158021
0.862626
if not validate_input_parameters(product_name, product_version, product_milestone): sys.exit(1) product_version = pnc_api.product_versions.get_all(q="version=='"+ product_version + "';product.name=='"+product_name+"'") if not product_version.content: logging.error('Specified product ver...
def generate_repo_list(product_name=None, product_version=None, product_milestone=None)
Generates list of artifacts for offline repository.
2.395853
2.315507
1.034699
global user user = UserConfig() if username: user.username = username else: user.username = user.input_username() if password: user.password = password else: user.password = user.input_password() if (not ( user.username and user.password) ): log...
def login(username=None, password=None)
Log in to PNC using the supplied username and password. The keycloak token will be saved for all subsequent pnc-cli operations until login is called again :return:
4.305086
4.027657
1.068881
if self.cancelled: raise error.AlreadyCancelled elif self.called: raise error.AlreadyCalled else: self.canceller(self) self.cancelled = 1 if self.debug: self._str = str(self) del self.func, self.args...
def cancel(self)
Unschedule this call @raise AlreadyCancelled: Raised if this call has already been unscheduled. @raise AlreadyCalled: Raised if this call has already been made.
4.59609
4.533223
1.013868
if self.cancelled: raise error.AlreadyCancelled elif self.called: raise error.AlreadyCalled else: if self.seconds is None: new_time = base.seconds() + secondsFromNow else: new_time = self.seconds() + seconds...
def reset(self, secondsFromNow)
Reschedule this call for a different time @type secondsFromNow: C{float} @param secondsFromNow: The number of seconds from the time of the C{reset} call at which this call will be scheduled. @raise AlreadyCancelled: Raised if this call has been cancelled. @raise AlreadyCalled: ...
3.538977
3.404703
1.039438
if self.cancelled: raise error.AlreadyCancelled elif self.called: raise error.AlreadyCalled else: self.delayed_time += secondsLater if self.delayed_time < 0: self.activate_delay() self.resetter(self)
def delay(self, secondsLater)
Reschedule this call for a later time @type secondsLater: C{float} @param secondsLater: The number of seconds after the originally scheduled time for which to reschedule this call. @raise AlreadyCancelled: Raised if this call has been cancelled. @raise AlreadyCalled: Raised if ...
6.160697
5.695301
1.081716
startLogging(stdout) checker = InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("testuser", "examplepass") realm = AdditionRealm() factory = CredAMPServerFactory(Portal(realm, [checker])) reactor.listenTCP(7805, factory) reactor.run()
def main()
Start the AMP server and the reactor.
12.013756
8.649446
1.388962
self.use_title_tag = True self.title = instance.title
def set_meta(self, instance)
Set django-meta stuff from LandingPageModel instance.
12.554708
6.907373
1.817581
''' Returns permissions determined by object itself ''' if self.permissions is None: return field.parent.permissions return self.permissions
def check(self, field)
Returns permissions determined by object itself
17.195131
4.914365
3.498953
file_name = template_engine_name.lower() class_name = "{}View".format(template_engine_name.title()) try: view_module = import_module("rails.views.{}".format(file_name)) except ImportError: raise Exception("Template engine '{}' not found in 'rails.views'"....
def _load_view(self, template_engine_name, template_dir)
Load view by name and return an instance.
2.528098
2.406673
1.050453
'''Terminates process with PID `pid` and returns True if process finished during `timeout`. Current user must have permission to access process information.''' os.kill(pid, sig) start = time.time() while True: try: # This is requireed if it's our child to avoid zombie. Also ...
def terminate(pid, sig, timeout)
Terminates process with PID `pid` and returns True if process finished during `timeout`. Current user must have permission to access process information.
5.02393
3.617148
1.38892
if os.fork(): os._exit(os.EX_OK) except OSError as e: sys.exit('fork #1 failed: ({}) {}'.format(e.errno, e.strerror)) os.setsid() os.chdir(cwd) os.umask(umask) try: if os.fork(): os._exit(os.EX_OK) except OSError as e: sys.exit('fork #2 fai...
def doublefork(pidfile, logfile, cwd, umask): # pragma: nocover '''Daemonize current process. After first fork we return to the shell and removing our self from controling terminal via `setsid`. After second fork we are not session leader any more and cant get controlling terminal when opening files...
Daemonize current process. After first fork we return to the shell and removing our self from controling terminal via `setsid`. After second fork we are not session leader any more and cant get controlling terminal when opening files.
1.897339
1.917696
0.989385