code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
datasets = []
query = text()
for result in self.execute(query):
res = DatasetSearchResult()
res.vid = result[0]
res.b_score = 1
datasets.append(res)
return datasets | def all(self) | Returns list with all indexed datasets. | 9.768991 | 8.130801 | 1.20148 |
query = text()
self.execute(query, **document) | def _index_document(self, document, force=False) | Adds dataset document to the index. | 28.931469 | 24.988947 | 1.157771 |
expanded_terms = self._expand_terms(terms)
if expanded_terms['doc']:
# create query with real score.
query_parts = ["SELECT vid, ts_rank_cd(setweight(doc,'C'), to_tsquery(:doc)) as score"]
if expanded_terms['doc'] and expanded_terms['keywords']:
que... | def _make_query_from_terms(self, terms, limit=None) | Creates a query for dataset from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (TextClause, dict): First element is FTS query, second is parameters
of the query. Element of the execution of the query is pair: (vid, score). | 3.64575 | 3.378261 | 1.079179 |
assert vid is not None
query = text()
self.execute(query, vid=vid) | def _delete(self, vid=None) | Deletes given dataset from index.
Args:
vid (str): dataset vid. | 11.004171 | 13.87409 | 0.793145 |
expanded_terms = self._expand_terms(terms)
terms_used = 0
if expanded_terms['doc']:
# create query with real score.
query_parts = ["SELECT vid, dataset_vid, ts_rank_cd(setweight(doc,'C'), to_tsquery(:doc)) as score"]
if expanded_terms['doc'] and expanded... | def _make_query_from_terms(self, terms, limit=None) | Creates a query for partition from decomposed search terms.
Args:
terms (dict or unicode or string):
Returns:
tuple of (TextClause, dict): First element is FTS query, second is
parameters of the query. Element of the execution of the query is
tuple of th... | 2.862773 | 2.668637 | 1.072747 |
query, query_params = self._make_query_from_terms(search_phrase, limit=limit)
self._parsed_query = (str(query), query_params)
if query is not None:
self.backend.library.database.set_connection_search_path()
results = self.execute(query, **query_params)
... | def search(self, search_phrase, limit=None) | Finds partitions by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to generate. None means without limit.
Generates:
PartitionSearchResult instances. | 6.585925 | 6.461201 | 1.019304 |
doc = super(self.__class__, self)._as_document(partition)
# pass time_coverage to the _index_document.
doc['time_coverage'] = partition.time_coverage
return doc | def _as_document(self, partition) | Converts partition to document indexed by to FTS index.
Args:
partition (orm.Partition): partition to convert.
Returns:
dict with structure matches to BasePartitionIndex._schema. | 7.989047 | 9.937642 | 0.803918 |
time_coverage = document.pop('time_coverage', [])
from_year = None
to_year = None
if time_coverage:
from_year = int(time_coverage[0]) if time_coverage and time_coverage[0] else None
to_year = int(time_coverage[-1]) if time_coverage and time_coverage[-1] ... | def _index_document(self, document, force=False) | Adds parition document to the index. | 2.978815 | 2.947002 | 1.010795 |
query = text()
result = self.execute(query, vid=partition.vid)
return bool(result.fetchall()) | def is_indexed(self, partition) | Returns True if partition is already indexed. Otherwise returns False. | 15.117795 | 13.277578 | 1.138596 |
partitions = []
query = text()
for result in self.execute(query):
dataset_vid, vid = result
partitions.append(PartitionSearchResult(dataset_vid=dataset_vid, vid=vid, score=1))
return partitions | def all(self) | Returns list with vids of all indexed partitions. | 10.031627 | 8.225407 | 1.21959 |
query_parts = [
'SELECT identifier, type, name, similarity(name, :word) AS sml',
'FROM identifier_index',
'WHERE name % :word',
'ORDER BY sml DESC, name']
query_params = {
'word': search_phrase}
if limit:
query_p... | def search(self, search_phrase, limit=None) | Finds identifiers by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to return. None means without limit.
Returns:
list of IdentifierSearchResult instances. | 4.179571 | 4.04925 | 1.032184 |
query = text()
self.execute(query, **identifier) | def _index_document(self, identifier, force=False) | Adds identifier document to the index. | 35.94738 | 32.376186 | 1.110303 |
query = text()
self.execute(query, identifier=identifier) | def _delete(self, identifier=None) | Deletes given identifier from index.
Args:
identifier (str): identifier of the document to delete. | 18.592497 | 42.057793 | 0.44207 |
query = text()
result = self.execute(query, identifier=identifier['identifier'])
return bool(result.fetchall()) | def is_indexed(self, identifier) | Returns True if identifier is already indexed. Otherwise returns False. | 13.047358 | 12.337873 | 1.057505 |
identifiers = []
query = text()
for result in self.execute(query):
vid, type_, name = result
res = IdentifierSearchResult(
score=1, vid=vid, type=type_, name=name)
identifiers.append(res)
return identifiers | def all(self) | Returns list with all indexed identifiers. | 9.365488 | 8.278893 | 1.131249 |
'''Pare text to have maximum size and add etc to the end if it's
changed'''
size = int(size)
text = text.strip()
if len(text)>size:
# strip the last word or not
to_be_stripped = not whitespace_re.findall(text[size-1:size+2])
text = text[:size]
if to_be_stripped:
... | def pare(text, size, etc='...') | Pare text to have maximum size and add etc to the end if it's
changed | 5.115064 | 3.934426 | 1.300079 |
data = get_environment_raw(id, name)
if data:
return utils.format_json(data) | def get_environment(id=None, name=None) | Get a specific Environment by name or ID | 5.908405 | 6.290029 | 0.939329 |
response = utils.checked_api_call(pnc_api.environments, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return response.content | def list_environments_raw(page_size=200, page_index=0, sort="", q="") | List all Environments | 3.758985 | 3.887881 | 0.966847 |
from ambry.valuetype.core import ROLE
for c in self.columns:
if c.role == ROLE.DIMENSION:
yield c | def dimensions(self) | Iterate over the dimension columns, regardless of parent/child status | 19.320341 | 12.058631 | 1.6022 |
from ambry.valuetype.core import ROLE
for c in self.columns:
if not c.parent and c.role == ROLE.DIMENSION:
yield c | def primary_dimensions(self) | Iterate over the primary dimension columns, columns which do not have a parent | 20.40971 | 11.962662 | 1.706118 |
from ambry.valuetype.core import ROLE
for c in self.columns:
if not c.parent and c.role == ROLE.MEASURE:
yield c | def primary_measures(self) | Iterate over the primary columns, columns which do not have a parent
Also sets the property partition_stats to the stats collection for the partition and column. | 19.170597 | 13.569092 | 1.412814 |
from ..identity import ColumnNumber
try:
c = self.column(name)
extant = True
if not update_existing:
return c
except NotFoundError:
sequence_id = len(self.columns) + 1
assert sequence_id
c = Co... | def add_column(self, name, update_existing=False, **kwargs) | Add a column to the table, or update an existing one.
:param name: Name of the new or existing column.
:param update_existing: If True, alter existing column values. Defaults to False
:param kwargs: Other arguments for the the Column() constructor
:return: a Column object | 4.175548 | 4.172235 | 1.000794 |
if len(self.columns) == 0:
return True
if len(self.columns) == 1 and self.columns[0].name == 'id':
return True
return False | def is_empty(self) | Return True if the table has no columns or the only column is the id | 3.136472 | 2.016841 | 1.555141 |
sd = dict(stats)
for c in self.columns:
if c not in sd:
continue
stat = sd[c]
if stat.size and stat.size > c.size:
c.size = stat.size
c.lom = stat.lom | def update_from_stats(self, stats) | Update columns based on partition statistics | 5.972425 | 4.955487 | 1.205215 |
from ..identity import ObjectNumber
if sequence_id:
self.sequence_id = sequence_id
assert self.d_vid
if self.id is None or force:
dataset_id = ObjectNumber.parse(self.d_vid).rev(None)
self.d_id = str(dataset_id)
self.id = str(Ta... | def update_id(self, sequence_id=None, force=True) | Alter the sequence id, and all of the names and ids derived from it. This
often needs to be don after an IntegrityError in a multiprocessing run | 4.095874 | 4.087389 | 1.002076 |
tr = []
for c in self.columns:
tr.append(c.expanded_transform)
return six.moves.zip_longest(*tr) | def transforms(self) | Return an array of arrays of column transforms.
#The return value is an list of list, with each list being a segment of column transformations, and
#each segment having one entry per column. | 8.40375 | 5.803867 | 1.447957 |
if target.sequence_id is None:
from ambry.orm.exc import DatabaseError
raise DatabaseError('Must have sequence id before insertion')
Table.before_update(mapper, conn, target) | def before_insert(mapper, conn, target) | event.listen method for Sqlalchemy to set the seqience_id for this
object and create an ObjectNumber value for the id | 6.835058 | 6.566806 | 1.04085 |
target.name = Table.mangle_name(target.name)
if isinstance(target, Column):
raise TypeError('Got a column instead of a table')
target.update_id(target.sequence_id, False) | def before_update(mapper, conn, target) | Set the Table ID based on the dataset number and the sequence number
for the table. | 10.82201 | 9.754028 | 1.109491 |
assert filetype in ['jsonzip', 'jsondir', 'wikidump']
# Iterating through paragraphes from the Anntoated Wikipedia zipfile.
if filetype == 'jsonzip':
with ZipFile(filename, 'r') as zip_in:
# Iterate through the individual files.
for infile in zip_in.namelist():
... | def iter_paragraph(filename, filetype) | A helper function to iterate through the diff types of Wikipedia data inputs.
:param arguments: The docopt arguments
:type arguments: dict
:return: A generator yielding a pargraph of text for each iteration. | 2.575166 | 2.600415 | 0.99029 |
return ch.join([substring for substring in s.strip().split(ch) if substring]) | def deduplicate(s, ch) | From http://stackoverflow.com/q/42216559/610569
s = 'this is an irritating string with random spacing .'
deduplicate(s)
'this is an irritating string with random spacing .' | 7.534415 | 9.009295 | 0.836294 |
count = [0] * (len(brackets) // 2) # count open/close brackets
saved_chars = []
for character in s:
for i, b in enumerate(brackets):
if character == b: # found bracket
kind, is_close = divmod(i, 2)
count[kind] += (-1)**is_close # `+1`: open, `-1`: clo... | def remove_text_inside_brackets(s, brackets="()[]") | From http://stackoverflow.com/a/14603508/610569 | 3.182985 | 3.111744 | 1.022894 |
if color in palette and color != 'default':
s = palette[color] + s
# Highlight / Background color.
if highlight and highlight in highlighter:
s = highlighter[highlight] + s
# Custom string format.
for name, value in kwargs.items():
if name in formatter and value == True:... | def color_print(s, color=None, highlight=None, end='\n', file=sys.stdout,
**kwargs) | From http://stackoverflow.com/a/287944/610569
See also https://gist.github.com/Sheljohn/68ca3be74139f66dbc6127784f638920 | 4.677884 | 4.864487 | 0.96164 |
errors = []
tasks_seen = TaskCache()
while True:
for session in self.values():
errs = session.wait_for_tasks(raise_if_error=False)
errors.extend(errs)
# look for tasks created after the wait (in callbacks of
# tasks fro... | def wait_for_tasks(self, raise_if_error=True) | Wait for the running tasks lauched from the sessions.
Note that it also wait for tasks that are started from other tasks
callbacks, like on_finished.
:param raise_if_error: if True, raise all possible encountered
errors using :class:`TaskErrors`. Else the errors are returned
... | 5.401849 | 4.794255 | 1.126734 |
if self.__timed_out:
return TimeoutError(self.session, self, "timeout")
if self.__exit_code is not None and \
self.__expected_exit_code is not None and \
self.__exit_code != self.__expected_exit_code:
return ExitCodeError(self.session, sel... | def error(self) | Return an instance of Exception if any, else None.
Actually check for a :class:`TimeoutError` or a
:class:`ExitCodeError`. | 4.080193 | 3.155407 | 1.29308 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_new_with_http_info(**kwargs)
else:
(data) = self.create_new_with_http_info(**kwargs)
return data | def create_new(self, **kwargs) | Creates a new License
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):
>>> pprint(response)
>>>
... | 1.551528 | 1.75709 | 0.88301 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_with_http_info(id, **kwargs)
else:
(data) = self.delete_with_http_info(id, **kwargs)
return data | def delete(self, id, **kwargs) | Deletes an existing License
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):
>>> pprint(response)
... | 1.522795 | 1.713519 | 0.888694 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_all_with_http_info(**kwargs)
else:
(data) = self.get_all_with_http_info(**kwargs)
return data | def get_all(self, **kwargs) | Gets all Licenses
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):
>>> pprint(response)
>>>
... | 1.574658 | 1.783825 | 0.882742 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_specific_with_http_info(id, **kwargs)
else:
(data) = self.get_specific_with_http_info(id, **kwargs)
return data | def get_specific(self, id, **kwargs) | Get specific License
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):
>>> pprint(response)
>>>
... | 1.477557 | 1.640322 | 0.900772 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_with_http_info(id, **kwargs)
else:
(data) = self.update_with_http_info(id, **kwargs)
return data | def update(self, id, **kwargs) | Updates an existing License
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):
>>> pprint(response)
... | 1.535145 | 1.717414 | 0.89387 |
d = {}
for p in self.__mapper__.attrs:
if p.key in ['vid','vname','fqname', 'version', 'cache_key']:
continue
if p.key == 'revision':
d[p.key] = self.revision + 1
else:
d[p.key] = getattr(self, p.key)
n... | def incver(self) | Increment all of the version numbers | 5.60544 | 5.647941 | 0.992475 |
from . import next_sequence_id
from sqlalchemy.orm import object_session
# NOTE: This next_sequence_id uses a different algorithm than dataset.next_sequence_id
# FIXME replace this one with dataset.next_sequence_id
return next_sequence_id(object_session(self), self._se... | def next_sequence_id(self, table_class, force_query=False) | Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix
for the child object. On the first call, will load the max sequence number
from the database, but subsequence calls will run in process, so this isn't suitable for
multi-process operatio... | 6.13061 | 5.618844 | 1.09108 |
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import FlushError
# If a sequence ID was specified, the caller is certain
# that there is no potential for conflicts,
# so there is no need to commit here.
if not sequence_id:
commit ... | def new_unique_object(self, table_class, sequence_id=None, force_query=False, **kwargs) | Use next_sequence_id to create a new child of the dataset, with a unique id | 4.447711 | 4.291622 | 1.03637 |
'''Add a table to the schema, or update it it already exists.
If updating, will only update data.
'''
from . import Table
from .exc import NotFoundError
try:
table = self.table(name)
extant = True
except NotFoundError:
extant... | def new_table(self, name, add_id=True, **kwargs) | Add a table to the schema, or update it it already exists.
If updating, will only update data. | 4.604182 | 3.753663 | 1.226584 |
from . import Partition
# Create the basic partition record, with a sequence ID.
if isinstance(table, string_types):
table = self.table(table)
if 'sequence_id' in kwargs:
sequence_id = kwargs['sequence_id']
del kwargs['sequence_id']
... | def new_partition(self, table, **kwargs) | Creates new partition and returns it.
Args:
table (orm.Table):
Returns:
orm.Partition | 4.251143 | 4.762899 | 0.892554 |
from .exc import NotFoundError
from six import text_type
if ref:
for p in self.partitions: # This is slow for large datasets, like Census years.
if (text_type(ref) == text_type(p.name) or text_type(ref) == text_type(p.id) or
text... | def partition(self, ref=None, **kwargs) | Returns partition by ref. | 5.794775 | 5.564082 | 1.041461 |
from sqlalchemy.orm.exc import NoResultFound
from ambry.orm.exc import NotFoundError
try:
f = object_session(self)\
.query(File)\
.filter(File.d_vid == self.vid)\
.filter(File.major_type == File.MAJOR_TYPE.BUILDSOURCE)\
... | def bsfile(self, path) | Return a Build Source file ref, creating a new one if the one requested does not exist | 4.610997 | 4.269891 | 1.079886 |
d = self.dict
row = [None] * len(fields)
for i, f in enumerate(fields):
if f in d:
row[i] = d[f]
return row | def row(self, fields) | Return a row for fields, for CSV files, pretty printing, etc, give a set of fields to return | 3.169824 | 3.028204 | 1.046767 |
from ambry.metadata.schema import Top # cross-module import
top = Top()
top.build_from_db(self.dataset)
return top | def metadata(self) | Access process configuarion values as attributes. | 16.979496 | 15.20792 | 1.11649 |
from ambry.orm import Config as SAConfig
from sqlalchemy import or_
rows = []
configs = self.dataset.session\
.query(SAConfig)\
.filter(or_(SAConfig.group == 'config', SAConfig.group == 'process'),
SAConfig.d_vid == self.dataset.vid)\... | def rows(self) | Return configuration in a form that can be used to reconstitute a
Metadata object. Returns all of the rows for a dataset.
This is distinct from get_config_value, which returns the value
for the library. | 3.693791 | 3.448053 | 1.071269 |
path = instance_to_path_map[config_instance]
# find group
group = prop_tree
for elem in path[:-1]:
group = getattr(group, elem)
assert group._key == config_instance.parent.key
setattr(group, config_instance.key, config_instance.value)
#
# bind config to the term
#
... | def _set_value(instance_to_path_map, path_to_instance_map, prop_tree, config_instance) | Finds appropriate term in the prop_tree and sets its value from config_instance.
Args:
configs_map (dict): key is id of the config, value is Config instance (AKA cache of the configs)
prop_tree (PropertyDictTree): poperty tree to populate.
config_instance (Config): | 5.310326 | 5.551337 | 0.956585 |
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance, False
else:
instance = model(**kwargs)
if 'dataset' in kwargs:
instance.update_sequence_id(session, kwargs['dataset'])
session.add(instance)
session.commit()
... | def get_or_create(session, model, **kwargs) | Get or create sqlalchemy instance.
Args:
session (Sqlalchemy session):
model (sqlalchemy model):
kwargs (dict): kwargs to lookup or create instance.
Returns:
Tuple: first element is found or created instance, second is boolean - True if instance created,
False if in... | 2.479661 | 3.064755 | 0.80909 |
path = group_or_term._get_path()
cached = group_or_term._top._cached_configs.get(path)
if cached:
config = cached
created = False
else:
# does not exist or not yet cached
config, created = get_or_create(session, Config, **kwargs)
return config, created | def _get_config_instance(group_or_term, session, **kwargs) | Finds appropriate config instance and returns it.
Args:
group_or_term (Group or Term):
session (Sqlalchemy session):
kwargs (dict): kwargs to pass to get_or_create.
Returns:
tuple of (Config, bool): | 4.528485 | 4.501577 | 1.005977 |
self._members = {
name: attr for name, attr in iteritems(type(self).__dict__) if isinstance(attr, Group)}
for name, m in iteritems(self._members):
m.init_descriptor(name, self) | def register_members(self) | Collect the names of the class member and convert them to object
members.
Unlike Terms, the Group class members are converted into object
members, so the configuration data | 6.464176 | 5.379141 | 1.201712 |
self._errors[(group, term, sub_term)] = value | def add_error(self, group, term, sub_term, value) | For records that are not defined as terms, either add it to the
errors list. | 6.787745 | 5.775132 | 1.17534 |
if isinstance(st, string_types):
from jinja2 import Template
try:
for i in range(5): # Only do 5 recursive substitutions.
st = Template(st).render(**(self._top.dict))
if '{{' not in st:
break
... | def _jinja_sub(self, st) | Create a Jina template engine, then perform substitutions on a string | 5.311552 | 5.379894 | 0.987297 |
if isinstance(st, binary_type):
return _ScalarTermS(st, self._jinja_sub)
elif isinstance(st, text_type):
return _ScalarTermU(st, self._jinja_sub)
elif st is None:
return _ScalarTermU(u(''), self._jinja_sub)
else:
return st | def scalar_term(self, st) | Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions | 4.138225 | 2.745346 | 1.50736 |
dataset = self._top._config.dataset
session = object_session(self._top._config)
logger.debug(
'Updating group config. dataset: {}, type: {}, key: {}'.format(dataset.vid, self._top._type, self._key))
self._config, created = _get_config_instance(
self, ses... | def update_config(self) | Updates or creates config of that group. Requires tree bound to db. | 4.988428 | 4.563473 | 1.093121 |
o = copy.copy(self)
o.init_instance(parent)
return o | def get_group_instance(self, parent) | Create an instance object | 7.589188 | 6.910546 | 1.098204 |
dataset = self._top._config.dataset
session = object_session(self._top._config)
logger.debug(
'Updating VarDictGroup config. dataset: {}, type: {}, key: {}, value: {}'.format(
dataset, self._top._type, key, value))
if not self._parent._config:
... | def update_config(self, key, value) | Creates or updates db config of the VarDictGroup. Requires bound to db tree. | 4.55145 | 3.82224 | 1.190781 |
dataset = self._top._config.dataset
session = object_session(self._top._config)
#logger.debug('Updating term config. dataset: {}, type: {}, key: {}, value: {}'.format(
# dataset, self._top._type, self._key, self.get()))
if not self._parent._config:
s... | def update_config(self) | Creates or updates db config of the term. Requires bound to db tree. | 5.473342 | 4.96146 | 1.103172 |
s = MLStripper()
s.feed(self.html)
return s.get_data() | def text(self) | Interpret the scalar as Markdown, strip the HTML and return text | 7.216216 | 6.04329 | 1.194087 |
queue = Queue()
stdout_reader, stderr_reader = \
self._create_readers(queue, *args, **kwargs)
self.thread = threading.Thread(target=self._read,
args=(stdout_reader,
stderr_reader,
... | def start(self, *args, **kwargs) | Start to read the stream(s). | 3.0533 | 2.824954 | 1.080832 |
'''Takes dict of attributes and returns their HTML representation'''
items = []
for key, value in data.items():
items.append('{}={}'.format(key, quoteattr(value)))
return ' '.join(items) | def quoteattrs(data) | Takes dict of attributes and returns their HTML representation | 3.697691 | 2.449947 | 1.509295 |
'''Quotes text to be used as JavaScript string in HTML templates. The
result doesn't contain surrounding quotes.'''
if isinstance(text, six.binary_type):
text = text.decode('utf-8') # for Jinja2 Markup
text = text.replace('\\', '\\\\');
text = text.replace('\n', '\\n');
text = text.repla... | def quote_js(text) | Quotes text to be used as JavaScript string in HTML templates. The
result doesn't contain surrounding quotes. | 4.278027 | 3.045958 | 1.404493 |
if ramp == 1: # basecase
yield int(err)
while True:
yield 0
# np.arange(n).sum() == err
# --> solve for n
# err = (n - 1) * (n // 2) == .5 * n**2 - .5 * n
# 0 = n**2 - n --> solve for n
n = np.abs(np.roots([.5, -.5, 0]).max())
niter = int(ramp // (2 * n)) ... | def create_ramp_plan(err, ramp) | Formulate and execute on a plan to slowly add heat or cooling to the system
`err` initial error (PV - SP)
`ramp` the size of the ramp
A ramp plan might yield MVs in this order at every timestep:
[5, 0, 4, 0, 3, 0, 2, 0, 1]
where err == 5 + 4 + 3 + 2 + 1 | 6.738423 | 6.552794 | 1.028328 |
if stop_condition:
return_code = stop_condition(list(errdata))
if return_code != -1:
log.info(
'Stop condition triggered! Relay is terminating.',
extra=dict(return_code=return_code))
sys.exit(return_code) | def evaluate_stop_condition(errdata, stop_condition) | Call the user-defined function: stop_condition(errdata)
If the function returns -1, do nothing. Otherwise, sys.exit. | 5.330786 | 4.451604 | 1.197498 |
# First, compile into an AST and handle syntax errors.
try:
tree = compile(codeString, filename, "exec", ast.PyCF_ONLY_AST)
except SyntaxError, value:
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
# If there's an encoding problem w... | def check(codeString, filename) | Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@return: The number of warnings emitted.
@rtype:... | 3.421373 | 3.351953 | 1.02071 |
try:
return check(file(filename, 'U').read() + '\n', filename)
except IOError, msg:
sys.stderr.write("%s: %s\n" % (filename, msg.args[1]))
return 1 | def checkPath(filename) | Check the given path, printing out any warnings detected.
@return: the number of warnings printed | 3.524508 | 3.665071 | 0.961648 |
'''
Current field's converted value from form's python_data.
'''
# XXX cached_property is used only for set initial state
# this property should be set every time field data
# has been changed, for instance, in accept method
python_data = self.parent.pytho... | def clean_value(self) | Current field's converted value from form's python_data. | 11.083846 | 6.175742 | 1.794739 |
'''Extracts raw value from form's raw data and passes it to converter'''
value = self.raw_value
if not self._check_value_type(value):
# XXX should this be silent or TypeError?
value = [] if self.multiple else self._null_value
self.clean_value = self.conv.accept(va... | def accept(self) | Extracts raw value from form's raw data and passes it to converter | 10.124924 | 6.159906 | 1.643682 |
'''Representation of aggregate value as dictionary.'''
try:
value = self.clean_value
except LookupError:
# XXX is this necessary?
value = self.get_initial()
return self.from_python(value) | def python_data(self) | Representation of aggregate value as dictionary. | 13.527568 | 8.568911 | 1.57868 |
'''
Accepts all children fields, collects resulting values into dict and
passes that dict to converter.
Returns result of converter as separate value in parent `python_data`
'''
result = dict(self.python_data)
for field in self.fields:
if field.writab... | def accept(self) | Accepts all children fields, collects resulting values into dict and
passes that dict to converter.
Returns result of converter as separate value in parent `python_data` | 8.198297 | 3.403866 | 2.408525 |
'''
Acts as `Field.accepts` but returns result of every child field
as value in parent `python_data`.
'''
result = FieldSet.accept(self)
self.clean_value = result[self.name]
return self.clean_value | def accept(self) | Acts as `Field.accepts` but returns result of every child field
as value in parent `python_data`. | 17.530422 | 3.626623 | 4.833814 |
conn.sendall(b'OK pubsub 1.0\n')
while True:
try:
s = conn.recv(1024).decode('utf-8').strip()
if not s:
conn.close()
break
except ConnectionResetError:
logger.debug('Client close the connection.')
break
... | def handle(conn, addr, gateway, *args, **kwargs) | NOTE: use tcp instead of udp because some operations need ack | 2.723379 | 2.699829 | 1.008723 |
if sys.version_info.major == 3 and sys.version_info.minor >= 5:
pattern = '/'.join([dir_path, '**', extension])
for filename in glob.iglob(pattern, recursive=True):
yield filename
else:
for root, dirnames, filenames in os.walk(dir_path):
for filename in fnmat... | def find_files(dir_path, extension="*") | From https://stackoverflow.com/a/2186565/610569 | 1.981246 | 1.88096 | 1.053316 |
if info is not None:
info.validate_pair(pair)
if connection is None:
connection = common.BTCEConnection()
response = connection.makeJSONRequest("/api/3/ticker/%s" % pair)
if type(response) is not dict:
raise TypeError("The response is a %r, not a dict." % type(response))... | def getTicker(pair, connection=None, info=None) | Retrieve the ticker for the given pair. Returns a Ticker instance. | 4.49307 | 4.358538 | 1.030866 |
if info is not None:
info.validate_pair(pair)
if connection is None:
connection = common.BTCEConnection()
response = connection.makeJSONRequest("/api/3/depth/%s" % pair)
if type(response) is not dict:
raise TypeError("The response is not a dict.")
depth = response.ge... | def getDepth(pair, connection=None, info=None) | Retrieve the depth for the given pair. Returns a tuple (asks, bids);
each of these is a list of (price, volume) tuples. | 2.590516 | 2.371663 | 1.092278 |
if info is not None:
info.validate_pair(pair)
if connection is None:
connection = common.BTCEConnection()
response = connection.makeJSONRequest("/api/3/trades/%s" % pair)
if type(response) is not dict:
raise TypeError("The response is not a dict.")
history = response... | def getTradeHistory(pair, connection=None, info=None, count=None) | Retrieve the trade history for the given pair. Returns a list of
Trade instances. If count is not None, it should be an integer, and
specifies the number of items from the trade history that will be
processed and returned. | 3.202352 | 3.152095 | 1.015944 |
import ambry.bundle.default_files as df
import os
path = os.path.join(os.path.dirname(df.__file__), self.file_name)
if six.PY2:
with open(path, 'rb') as f:
return f.read()
else:
# py3
with open(path, 'rt', encoding='... | def default(self) | Return default contents | 3.798953 | 3.452745 | 1.10027 |
from fs.errors import ResourceNotFoundError
try:
self._fs.remove(self.file_name)
except ResourceNotFoundError:
pass | def remove(self) | Removes file from filesystem. | 6.409598 | 5.136974 | 1.247738 |
# NOTE: These are ordered so the FILE_TO_RECORD has preference over RECORD_TO_FILE
# if there is a conflict.
if self.exists() and bool(self.size()) and not self.record.size:
# The fs exists, but the record is empty
return self.SYNC_DIR.FILE_TO_RECORD
i... | def sync_dir(self) | Report on which direction a synchronization should be done.
:return: | 4.491015 | 4.34078 | 1.03461 |
try:
if force:
sd = force
else:
sd = self.sync_dir()
if sd == self.SYNC_DIR.FILE_TO_RECORD:
if force and not self.exists():
return None
self.fs_to_record()
elif sd ==... | def sync(self, force=None) | Synchronize between the file in the file system and the field record | 5.112527 | 4.691684 | 1.0897 |
import unicodecsv as csv
fn_path = self.file_name
fr = self.record
fr.path = fn_path
rows = []
# NOTE. There were two cases here, for PY2 and PY3. Py two had
# encoding='utf-8' in the reader. I've combined them b/c that's the default for
# unic... | def fh_to_record(self, f) | Load a file in the filesystem into the file record | 5.2321 | 5.038931 | 1.038335 |
fr = self.record
fn_path = self.file_name
if fr.contents:
if six.PY2:
with self._fs.open(fn_path, 'wb') as f:
self.record_to_fh(f)
else:
# py3
with self._fs.open(fn_path, 'w', newline='') as f... | def record_to_fs(self) | Create a filesystem file from a File | 3.76279 | 3.697907 | 1.017546 |
fr = self.record
if fr.contents:
yaml.safe_dump(fr.unpacked_contents, f, default_flow_style=False, encoding='utf-8')
fr.source_hash = self.fs_hash
fr.modified = self.fs_modtime | def record_to_fh(self, f) | Write the record, in filesystem format, to a file handle or file object | 7.621802 | 7.050229 | 1.081072 |
fn_path = self.file_name
fr = self.record
fr.path = fn_path
fr.update_contents(f.read(), 'text/plain')
fr.source_hash = self.fs_hash
fr.synced_fs = self.fs_modtime
fr.modified = self.fs_modtime | def fh_to_record(self, f) | Load a file in the filesystem into the file record | 7.900108 | 6.853067 | 1.152784 |
from ..util import AttrDict
fr = self.record
contents = fr.unpacked_contents
if not contents:
return
ad = AttrDict(contents)
# Get time that filessystem was synchronized to the File record.
# Maybe use this to avoid overwriting configs t... | def record_to_objects(self) | Create config records to match the file metadata | 20.391165 | 18.819258 | 1.083527 |
o = self.get_object()
o.about = self._bundle.metadata.about
o.identity = self._dataset.identity.ident_dict
o.names = self._dataset.identity.names_dict
o.contacts = self._bundle.metadata.contacts
self.set_object(o) | def objects_to_record(self) | Write from object metadata to the record. Note that we don't write everything | 7.55265 | 6.674761 | 1.131524 |
fr = self.record
d = fr.unpacked_contents
d['identity'] = self._dataset.identity.ident_dict
d['names'] = self._dataset.identity.names_dict
fr.update_contents(msgpack.packb(d), 'application/msgpack') | def update_identity(self) | Update the identity and names to match the dataset id and version | 10.547409 | 7.689185 | 1.37172 |
from ..util import AttrDict
c = self.record.unpacked_contents
if not c:
c = yaml.safe_load(self.default)
return AttrDict(c) | def get_object(self) | Return contents in object form, an AttrDict | 14.135055 | 8.996407 | 1.571189 |
import json
import ambry.bundle.default_files as df
import os
path = os.path.join(os.path.dirname(df.__file__), 'notebook.ipynb')
if six.PY2:
with open(path, 'rb') as f:
content_str = f.read()
else:
# py3
wit... | def default(self) | Return default contents | 3.393957 | 3.342473 | 1.015403 |
from nbformat import read
from nbconvert.exporters import export_script
from cStringIO import StringIO
notebook = read(StringIO(self.record.unpacked_contents), 4)
script, resources = export_script(notebook)
env_dict = {}
exec (compile(script.replace(... | def execute(self) | Convert the notebook to a python script and execute it, returning the local context
as a dict | 6.056548 | 4.915196 | 1.232209 |
fr = self.record
if fr.contents:
with self._fs.open(self.file_name, 'w', encoding='utf-8') as f:
self.record_to_fh(f) | def record_to_fs(self) | Create a filesystem file from a File | 6.06579 | 6.024773 | 1.006808 |
from fs.errors import NoSysPathError
if module_path in sys.modules:
module = sys.modules[module_path]
else:
module = imp.new_module(module_path)
sys.modules[module_path] = module
bf = self.record
if not bf.contents:
retu... | def import_module(self, module_path = 'ambry.build', **kwargs) | Import the contents of the file into the ambry.build module
:param kwargs: items to add to the module globals
:return: | 4.519786 | 4.658249 | 0.970276 |
from fs.errors import NoSysPathError
try:
import ambry.build
module = sys.modules['ambry.build']
except ImportError:
module = imp.new_module('ambry.build')
sys.modules['ambry.build'] = module
bf = self.record
if not bf.h... | def import_bundle(self) | Add the filesystem to the Python sys path with an import hook, then import
to file as Python | 3.992495 | 4.055666 | 0.984424 |
try:
import ambry.build
module = sys.modules['ambry.build']
except ImportError:
module = imp.new_module('ambry.build')
sys.modules['ambry.build'] = module
bf = self.record
if not bf.has_contents:
return
try:... | def import_lib(self) | Import the lib.py file into the bundle module | 4.981259 | 4.664265 | 1.067962 |
from ambry.orm.exc import NotFoundError
fr = self.record
contents = fr.unpacked_contents
if not contents:
return
# Zip transposes an array when in the form of a list of lists, so this transposes so
# each row starts with the heading and the rest o... | def record_to_objects(self) | Create config records to match the file metadata | 4.966785 | 4.886434 | 1.016444 |
from ambry.orm import SourceTable
bsfile = self.record
failures = set()
# Clear out all of the columns from existing tables. We don't clear out the
# tables, since they may be referenced by sources
for row in bsfile.dict_row_reader:
st = self._dat... | def record_to_objects(self) | Write from the stored file data to the source records | 5.948154 | 5.756338 | 1.033323 |
from ambry.mprlib import execute_sql
execute_sql(self._bundle.library, self.record_content) | def execute(self) | Executes all sql statements from bundle.sql. | 47.834656 | 33.792824 | 1.415527 |
for r in self._dataset.files:
if file_const and r.minor_type != file_const:
continue
yield self.instance_from_name(r.path) | def list_records(self, file_const=None) | Iterate through the file records | 7.358802 | 7.364648 | 0.999206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.