code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
content = list_build_configurations_for_set_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | def list_build_configurations_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q="") | List all build configurations in a given BuildConfigurationSet. | 3.145813 | 3.430418 | 0.917035 |
content = add_build_configuration_to_set_raw(set_id, set_name, config_id, config_name)
if content:
return utils.format_json(content) | def add_build_configuration_to_set(
set_id=None, set_name=None, config_id=None, config_name=None) | Add a build configuration to an existing BuildConfigurationSet | 3.490652 | 3.821853 | 0.91334 |
content = list_build_records_for_set_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | def list_build_records_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q="") | List all build records for a BuildConfigurationSet | 3.014556 | 3.228024 | 0.93387 |
content = list_build_set_records_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q="") | List all build set records for a BuildConfigurationSet | 3.17712 | 3.498695 | 0.908087 |
stopping = []
reactor.addSystemEventTrigger('before', 'shutdown', stopping.append, True)
finished = main(reactor, *argv)
finished.addErrback(err, "main function encountered error")
def cbFinish(ignored):
if not stopping:
reactor.callWhenRunning(reactor.stop)
finished.add... | def react(reactor, main, argv) | Call C{main} and run the reactor until the L{Deferred} it returns fires.
@param reactor: An unstarted L{IReactorCore} provider which will be run and
later stopped.
@param main: A callable which returns a L{Deferred}. It should take as
many arguments as there are elements in the list C{argv}.
... | 3.920034 | 4.692469 | 0.835388 |
cls._static_registry.register(ModelClass, form_field, widget, title, prefix) | def register_model(cls, ModelClass, form_field=None, widget=None, title=None, prefix=None) | Register a model to use in the URL field.
This function needs to be called once for every model
that should be selectable in the URL field.
:param ModelClass: The model to register.
:param form_field: The form field class used to render the field. This can be a lambda for lazy evaluati... | 5.085656 | 7.199959 | 0.706345 |
# Allow the queryset or list to consist of multiple models.
# This supports querysets from django-polymorphic too.
queryset = list(objects)
any_url_values = []
for obj in queryset:
model = obj.__class__
for field in _any_url_fields_by_model[model... | def resolve_objects(cls, objects, skip_cached_urls=False) | Make sure all AnyUrlValue objects from a set of objects is resolved in bulk.
This avoids making a query per item.
:param objects: A list or queryset of models.
:param skip_cached_urls: Whether to avoid prefetching data that has it's URL cached. | 4.55043 | 3.854055 | 1.180686 |
import ambry.run
return ambry.run.load(path=path, root=root, db=db) | def config(path=None, root=None, db=None) | Return the default run_config object for this installation. | 5.140038 | 3.786824 | 1.357348 |
import ambry.library as _l
rc = config(path=path, root=root, db=db )
return _l.new_library(rc) | def get_library(path=None, root=None, db=None) | Return the default library for this installation. | 11.413099 | 11.216841 | 1.017497 |
parser = argparse.ArgumentParser(
prog='ambry',
description='Ambry {}. Management interface for ambry, libraries '
'and repositories. '.format(ambry._meta.__version__))
return parser | def doc_parser() | Utility function to allow getting the arguments for a single command, for Sphinx documentation | 12.472539 | 12.248968 | 1.018252 |
from ambry.run import find_config_file
from ambry.dbexceptions import ConfigurationError
from ambry.util import yaml
try:
plugins_dir = find_config_file('cli.yaml')
except ConfigurationError:
return []
with open(plugins_dir) as f:
cli_modules = yaml.load(f)
re... | def get_extra_commands() | Use the configuration to discover additional CLI packages to load | 4.455258 | 3.970181 | 1.12218 |
songs = self._api.weapi_songs_url([int(self.identifier)])
if songs and songs[0]['url']:
self.url = songs[0]['url']
else:
self.url = '' | def _refresh_url(self) | 刷新获取 url,失败的时候返回空而不是 None | 6.297209 | 5.401014 | 1.165931 |
local_path = self._find_in_local()
if local_path:
return local_path
if not self._url:
self._refresh_url()
elif time.time() > self._expired_at:
logger.info('song({}) url is expired, refresh...'.format(self))
self._refresh_url()
... | def url(self) | We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Currently, we assume that the
expiration time is 20 mi... | 5.053052 | 3.880078 | 1.302307 |
builder = CloudLoggingHandlerBuilder(
progname, fmt=fmt, datefmt=datefmt, project_id=project_id,
credentials=credentials, debug_thread_worker=debug_thread_worker)
return builder.get_handler() | def get_handler(progname, fmt=None, datefmt=None, project_id=None,
credentials=None, debug_thread_worker=False, **_) | Helper function to create a Stackdriver handler.
See `ulogger.stackdriver.CloudLoggingHandlerBuilder` for arguments
and supported keyword arguments.
Returns:
(obj): Instance of `google.cloud.logging.handlers.
CloudLoggingHandler` | 2.277979 | 2.251967 | 1.011551 |
endpoint_url = self.METADATA_ENDPOINT.format(
data_type=data_type, key=key)
try:
rsp = requests.get(
endpoint_url,
headers={'Metadata-Flavor': 'Google'},
timeout=timeout)
rsp.raise_for_status()
except re... | def _get_metadata(self, data_type, key, timeout=5) | Get host instance metadata (only works on GCP hosts).
More details about instance metadata:
https://cloud.google.com/compute/docs/storing-retrieving-metadata
Args:
data_type (str): Type of metadata to fetch. Eg. project,
instance
key (str): Key of metada... | 2.613198 | 2.453671 | 1.065015 |
return gcl_resource.Resource('gce_instance', {
'project_id': self.project_id,
'instance_id': self.instance_id,
'zone': self.zone
}) | def _create_gcl_resource(self) | Create a configured Resource object.
The logging.resource.Resource object enables GCL to filter and
bucket incoming logs according to which resource (host) they're
coming from.
Returns:
(obj): Instance of `google.cloud.logging.resource.Resource` | 3.801988 | 3.961541 | 0.959724 |
if not self.fmt:
self.fmt = ('%(asctime)s.%(msecs)03d {host} {progname} '
'(%(process)d): %(message)s').format(
host=self.hostname, progname=self.progname)
if not self.datefmt:
self.datefmt = '%Y-%m-%dT%H:%M:%S'
ret... | def get_formatter(self) | Create a fully configured `logging.Formatter`
Example of formatted log message:
2017-08-27T20:19:24.424 cpm-example-gew1 progname (23123): hello
Returns:
(obj): Instance of `logging.Formatter` | 2.291778 | 2.069993 | 1.107142 |
bthread_logger = logging.getLogger(
'google.cloud.logging.handlers.transports.background_thread')
if self.debug_thread_worker:
bthread_logger.setLevel(logging.DEBUG)
else:
bthread_logger.setLevel(logging.INFO) | def _set_worker_thread_level(self) | Sets logging level of the background logging thread to DEBUG or INFO | 4.15406 | 3.397101 | 1.222825 |
gcl_client = gcl_logging.Client(
project=self.project_id, credentials=self.credentials)
handler = gcl_handlers.CloudLoggingHandler(
gcl_client,
resource=self.resource,
labels={
'resource_id': self.instance_id,
'res... | def get_handler(self) | Create a fully configured CloudLoggingHandler.
Returns:
(obj): Instance of `google.cloud.logging.handlers.
CloudLoggingHandler` | 3.739451 | 3.487208 | 1.072334 |
self.backend.dataset_index.index_one(dataset, force=force) | def index_dataset(self, dataset, force=False) | Adds given dataset to the index. | 9.092665 | 7.352995 | 1.236593 |
self.backend.partition_index.index_one(partition, force=force) | def index_partition(self, partition, force=False) | Adds given partition to the index. | 9.65041 | 8.014736 | 1.204083 |
from ambry.orm.dataset import Dataset
dataset = bundle if isinstance(bundle, Dataset) else bundle.dataset
self.index_dataset(dataset, force)
for partition in dataset.partitions:
self.index_partition(partition, force) | def index_bundle(self, bundle, force=False) | Indexes a bundle/dataset and all of its partitions
:param bundle: A bundle or dataset object
:param force: If true, index the document even if it already exists
:return: | 4.372884 | 3.611354 | 1.210871 |
dataset_n = 0
partition_n = 0
def tick(d, p):
if tick_f:
tick_f('datasets: {} partitions: {}'.format(d, p))
for dataset in self.library.datasets:
if self.backend.dataset_index.index_one(dataset):
# dataset added to inde... | def index_library_datasets(self, tick_f=None) | Indexes all datasets of the library.
Args:
tick_f (callable, optional): callable of one argument. Gets string with index state. | 3.54686 | 3.592497 | 0.987297 |
return self.backend.dataset_index.search(search_phrase, limit=limit) | def search_datasets(self, search_phrase, limit=None) | Search for datasets. | 6.4045 | 6.884157 | 0.930324 |
from ambry.identity import ObjectNumber
from ambry.orm.exc import NotFoundError
from ambry.library.search_backends.base import SearchTermParser
results = []
stp = SearchTermParser()
# Because of the split between searching for partitions and bundles, some term... | def search(self, search_phrase, limit=None) | Search for datasets, and expand to database records | 6.849697 | 6.563638 | 1.043582 |
from itertools import chain
return chain(self.backend.dataset_index.list_documents(limit=limit),
self.backend.partition_index.list_documents(limit=limit),
self.backend.identifier_index.list_documents(limit=limit)) | def list_documents(self, limit=None) | Return a list of the documents
:param limit:
:return: | 4.35125 | 4.382152 | 0.992948 |
return '{} OR {}'.format(
self.backend.dataset_index.get_parsed_query()[0],
self.backend.partition_index.get_parsed_query()[0]) | def get_parsed_query(self) | Returns string with last query parsed. Assuming called after search_datasets. | 8.118127 | 6.098853 | 1.331091 |
data = list_build_configuration_set_records_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_build_configuration_set_records(page_size=200, page_index=0, sort="", q="") | List all build configuration set records. | 3.086322 | 3.28525 | 0.939448 |
data = list_records_for_build_config_set_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_records_for_build_config_set(id, page_size=200, page_index=0, sort="", q="") | Get a list of BuildRecords for the given BuildConfigSetRecord | 2.794669 | 3.122119 | 0.895119 |
old_user = self._user
self.auth(user)
try:
yield
finally:
self.auth(old_user) | def auth_as(self, user) | auth as a user temporarily | 3.794425 | 3.147072 | 1.2057 |
# Map common values into the accounts records
all_accounts = self.accounts
kmap = Account.prop_map()
for account_id, values in accounts_data.items():
if not isinstance(values, dict):
continue
d = {}
a = self.library.find... | def sync_accounts(self, accounts_data, clear = False, password=None, cb = None) | Load all of the accounts from the account section of the config
into the database.
:param accounts_data:
:param password:
:return: | 4.766036 | 4.623971 | 1.030724 |
if isinstance(v, int):
return v
if isinstance(v, float):
return int(v)
v = str(v).replace(',', '')
if not v:
return None
return int(v) | def robust_int(v) | Parse an int robustly, ignoring commas and other cruft. | 2.680959 | 2.284899 | 1.173338 |
return type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_code, 'vt_args': vt_args}) | def subclass(cls, vt_code, vt_args) | Return a dynamic subclass that has the extra parameters built in
:param vt_code: The full VT code, privided to resolve_type
:param vt_args: The portion of the VT code to the right of the part that matched a ValueType
:return: | 3.342146 | 4.709754 | 0.709622 |
'''
Given a template name and template vars.
Searches a template file based on engine set, and renders it
with corresponding engine.
Returns a string.
'''
logger.debug('Rendering template "%s"', template_name)
vars = self.globs.copy()
vars.update(... | def render(self, template_name, **kw) | Given a template name and template vars.
Searches a template file based on engine set, and renders it
with corresponding engine.
Returns a string. | 6.70316 | 2.649824 | 2.529662 |
'''Given a template name and template data.
Renders a template and returns as string'''
return self.template.render(template_name,
**self._vars(__data, **kw)) | def render(self, template_name, __data=None, **kw) | Given a template name and template data.
Renders a template and returns as string | 8.519993 | 4.253495 | 2.003057 |
'''Given a template name and template data.
Renders a template and returns `webob.Response` object'''
resp = self.render(template_name, __data)
return Response(resp,
content_type=content_type) | def render_to_response(self, template_name, __data,
content_type="text/html") | Given a template name and template data.
Renders a template and returns `webob.Response` object | 6.188707 | 2.902687 | 2.132061 |
ret = []
for line in it:
if is_delimiter(line):
if ret:
yield ret # OR ''.join(ret)
ret = []
else:
ret.append(line.rstrip()) # OR ret.append(line)
if ret:
yield ret | def per_section(it, is_delimiter=lambda x: x.isspace()) | From http://stackoverflow.com/a/25226944/610569 | 3.06986 | 2.820325 | 1.088477 |
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | def per_chunk(iterable, n=1, fillvalue=None) | From http://stackoverflow.com/a/8991553/610569
>>> list(per_chunk('abcdefghi', n=2))
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('i', None)]
>>> list(per_chunk('abcdefghi', n=3))
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')] | 2.446437 | 5.72541 | 0.427295 |
start, stop = 0, n
seq = list(sequence)
while stop <= len(seq):
yield tuple(seq[start:stop])
start += 1
stop += 1 | def per_window(sequence, n=1) | From http://stackoverflow.com/q/42220614/610569
>>> list(per_window([1,2,3,4], n=2))
[(1, 2), (2, 3), (3, 4)]
>>> list(per_window([1,2,3,4], n=3))
[(1, 2, 3), (2, 3, 4)] | 2.731431 | 4.142368 | 0.659389 |
start, stop = 0, n
seq = list(sequence)
while stop <= len(seq):
subseq = seq[start:stop]
if target in subseq:
yield tuple(seq[start:stop])
start += 1
stop += 1
# Fast forwarding the start.
# Find the next window which contains the target.
... | def skipping_window(sequence, target, n=3) | Return a sliding window with a constraint to check that
target is inside the window.
From http://stackoverflow.com/q/43626525/610569
>>> list(skipping_window([1,2,3,4,5], 2, 3))
[(1, 2, 3), (2, 3, 4)] | 4.002711 | 4.30304 | 0.930205 |
one_three, two_four = zigzag(sequence)
one, three = zigzag(one_three)
two, four = zigzag(two_four)
return one + list(reversed(two)) + three + list(reversed(four)) | def camel_shuffle(sequence) | Inspired by https://stackoverflow.com/q/42549212/610569
>>> list(range(12)) # Linear.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> camel_shuffle(list(range(12))) # M-shape.
[0, 4, 8, 9, 5, 1, 2, 6, 10, 11, 7, 3]
>>> camel_shuffle(list(reversed(range(12)))) #W-shape.
[11,... | 3.174835 | 4.427344 | 0.717097 |
'''Current page.'''
page = self.request.GET.get(self.page_param)
if not page:
return 1
try:
page = int(page)
except ValueError:
self.invalid_page()
return 1
if page<1:
self.invalid_page()
return 1
... | def page(self) | Current page. | 2.906766 | 2.905648 | 1.000385 |
'''Current or base URL. Can be redefined via keyword argument on
initialization.
Returns `iktomi.web.URL object.
`'''
return URL.from_url(self.request.url, show_host=self.show_host) | def url(self) | Current or base URL. Can be redefined via keyword argument on
initialization.
Returns `iktomi.web.URL object.
` | 20.267912 | 3.272915 | 6.192618 |
'''
Returns URL for page, page is included as query parameter.
Can be redefined by keyword argument
'''
if page is not None and page != 1:
return self.url.qs_set(**{self.page_param: page})
elif page is not None:
return self.url.qs_delete('page') | def page_url(self, page) | Returns URL for page, page is included as query parameter.
Can be redefined by keyword argument | 7.369672 | 3.447357 | 2.137775 |
'''Number of pages.'''
if not self.limit or self.count<self.limit:
return 1
if self.count % self.limit <= self.orphans:
return self.count // self.limit
return int(math.ceil(float(self.count)/self.limit)) | def pages_count(self) | Number of pages. | 4.541036 | 4.504175 | 1.008184 |
'''Slice the sequence of all items to obtain them for current page.'''
if self.limit:
if self.page>self.pages_count:
return []
if self.page == self.pages_count:
return items[self.limit*(self.page-1):]
return items[self.limit*(self.page-... | def slice(self, items) | Slice the sequence of all items to obtain them for current page. | 3.96296 | 2.748867 | 1.441671 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_build_configurations_with_http_info(id, **kwargs)
else:
(data) = self.get_build_configurations_with_http_info(id, **kwargs)
return data | def get_build_configurations(self, id, **kwargs) | Gets all BuildConfigurations associated with the specified Project Id
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.452095 | 1.673229 | 0.86784 |
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs if p.key not in ('data')}
d['secret'] = 'not available'
if self.secret_password:
try:
d['secret'] = self.decrypt_secret()
except AccountDecryptionError:
pass
... | def dict(self) | A dict that holds key/values for all of the properties in the
object.
:return: | 4.264773 | 4.405027 | 0.96816 |
data = list_build_records_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_build_records(page_size=200, page_index=0, sort="", q="") | List all BuildRecords | 3.433053 | 3.69813 | 0.928322 |
data = list_records_for_build_configuration_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_records_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q="") | List all BuildRecords for a given BuildConfiguration | 2.855368 | 3.032521 | 0.941582 |
data = list_records_for_project_raw(id, name, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_records_for_project(id=None, name=None, page_size=200, page_index=0, sort="", q="") | List all BuildRecords for a given Project | 2.935538 | 3.086039 | 0.951232 |
data = list_built_artifacts_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_built_artifacts(id, page_size=200, page_index=0, sort="", q="") | List Artifacts associated with a BuildRecord | 3.312429 | 3.379753 | 0.98008 |
data = list_dependency_artifacts_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_dependency_artifacts(id, page_size=200, page_index=0, sort="", q="") | List dependency artifacts associated with a BuildRecord | 3.326779 | 3.586972 | 0.927462 |
logger.info('StatusReporter started.')
# if configured not to report status then return immediately
if self.config['status_update_interval'] == 0:
logger.info('StatusReporter disabled by configuration.')
return
self.in_future.report_status() | def on_start(self) | Runs when the actor is started and schedules a status update | 9.748529 | 8.458591 | 1.1525 |
# calculate sleep interval based on current status and configured interval
_m = {'playing': 1, 'paused': 2, 'stopped': 5}[current_status['state']]
interval = (self.config['status_update_interval'] * _m) / 1000.0
# sleep for computed interval and kickoff another webhook
t... | def report_again(self, current_status) | Computes a sleep interval, sleeps for the specified amount of time
then kicks off another status report. | 8.346314 | 6.37694 | 1.308828 |
current_status = {
'current_track': self.core.playback.current_track.get(),
'state': self.core.playback.state.get(),
'time_position': self.core.playback.time_position.get(),
}
send_webhook(self.config, {'status_report': current_status})
self.r... | def report_status(self) | Get status of player from mopidy core and send webhook. | 4.235491 | 3.103469 | 1.36476 |
return 'anyurlfield.{0}.{1}.{2}.{3}'.format(model._meta.app_label, model.__name__, pk, language_code or get_language()) | def get_urlfield_cache_key(model, pk, language_code=None) | The low-level function to get the cache key for a model. | 3.828558 | 3.651146 | 1.048591 |
if not instance.pk or instance._state.adding:
return []
keys = []
for language in _get_available_languages(instance):
keys.append(get_urlfield_cache_key(instance.__class__, instance.pk, language))
return keys | def get_object_cache_keys(instance) | Return the cache keys associated with an object. | 4.004282 | 3.830479 | 1.045374 |
n = self.accumulator
self.accumulator = 0
stream = self.stream
stream.append(n)
self.sum += n
streamlen = len(stream)
if streamlen > self.period:
self.sum -= stream.popleft()
streamlen -= 1
if streamlen == 0:
... | def flush(self) | Add accumulator to the moving average queue and reset it. For
example, called by the StatsCollector once per second to calculate
per-second average. | 3.4452 | 3.252418 | 1.059273 |
path = '/v8/fcg-bin/fcg_v8_singer_track_cp.fcg'
url = api_base_url + path
params = {
'singerid': artist_id,
'songstatus': 1,
'order': 'listen',
'begin': 0,
'num': 50,
'from': 'h5',
'platform': 'h5page',
... | def artist_detail(self, artist_id) | 获取歌手详情 | 3.296658 | 2.961796 | 1.113061 |
try:
response = requests.post(
config['webhook_url'],
data=json.dumps(payload, cls=ModelJSONEncoder),
headers={config['api_key_header_name']: config['api_key']},
)
except Exception as e:
logger.warning('Unable to send webhook: ({1}) {2}'.format(
... | def send_webhook(config, payload) | Sends a HTTP request to the configured server.
All exceptions are suppressed but emit a warning message in the log. | 2.391004 | 2.415201 | 0.989981 |
connection = self._backend._get_connection()
self._backend.clean(connection) | def clean(self) | Remove all of the tables and data from the warehouse | 11.164177 | 9.441255 | 1.182489 |
connection = self._backend._get_connection()
return list(self._backend.list(connection)) | def list(self) | List the tables in the database | 9.636986 | 9.053688 | 1.064427 |
try:
obj_number = ObjectNumber.parse(ref)
if isinstance(obj_number, TableNumber):
table = self._library.table(ref)
connection = self._backend._get_connection()
return self._backend.install_table(connection, table, logger=logger)
... | def install(self, ref, table_name=None, index_columns=None,logger=None) | Finds partition by reference and installs it to warehouse db.
Args:
ref (str): id, vid (versioned id), name or vname (versioned name) of the partition. | 3.80619 | 3.841286 | 0.990863 |
from ambry.library import Library
assert isinstance(self._library, Library)
logger.debug('Materializing warehouse partition.\n partition: {}'.format(ref))
partition = self._library.partition(ref)
connection = self._backend._get_connection()
return self._bac... | def materialize(self, ref, table_name=None, index_columns=None, logger=None) | Creates materialized table for given partition reference.
Args:
ref (str): id, vid, name or vname of the partition.
Returns:
str: name of the partition table in the database. | 5.717237 | 5.581348 | 1.024347 |
from ambry.orm.exc import NotFoundError
logger.debug('Creating index for partition.\n ref: {}, columns: {}'.format(ref, columns))
connection = self._backend._get_connection()
try:
table_or_partition = self._library.partition(ref)
except NotFoundError:
... | def index(self, ref, columns) | Create an index on the columns.
Args:
ref (str): id, vid, name or versioned name of the partition.
columns (list of str): names of the columns needed indexes. | 5.843784 | 5.668101 | 1.030995 |
import sqlparse
statements = sqlparse.parse(sqlparse.format(asql, strip_comments=True))
parsed_statements = []
for statement in statements:
statement_str = statement.to_unicode().strip()
for preprocessor in self._backend.sql_processors():
... | def parse_sql(self, asql) | Executes all sql statements from asql.
Args:
library (library.Library):
asql (str): ambry sql query - see https://github.com/CivicKnowledge/ambry/issues/140 for details. | 3.894351 | 3.861034 | 1.008629 |
import sqlparse
from ambry.mprlib.exceptions import BadSQLError
from ambry.bundle.asql_parser import process_sql
from ambry.orm.exc import NotFoundError
if not logger:
logger = self._library.logger
rec = process_sql(asql, self._library)
for... | def query(self, asql, logger=None) | Execute an ASQL file and return the result of the first SELECT statement.
:param asql:
:param logger:
:return: | 3.979092 | 3.948066 | 1.007859 |
import pandas as pd
from ambry.mprlib.exceptions import BadSQLError
try:
def yielder(cursor):
for i, row in enumerate(cursor):
if i == 0:
yield [ e[0] for e in cursor.getdescription()]
yield r... | def dataframe(self,asql, logger = None) | Like query(), but returns a Pandas dataframe | 4.153571 | 4.101025 | 1.012813 |
import geopandas
from shapely.wkt import loads
from fiona.crs import from_epsg
if crs is None:
try:
crs = from_epsg(epsg)
except TypeError:
raise TypeError('Must set either crs or epsg for output.')
df = self.data... | def geoframe(self, sql, simplify=None, crs=None, epsg=4326) | Return geopandas dataframe
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param crs: Coordinate reference system information
:param epsg: Specifiy the CRS as an EPGS number.
:return: A Geopandas GeoDataFrame | 2.425488 | 2.495431 | 0.971972 |
from shapely.wkt import loads
if simplify:
return [loads(row.geometry).simplify(simplify) for row in self]
else:
return [loads(row.geometry) for row in self] | def shapes(self, simplify=None) | Return geodata as a list of Shapely shapes
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:return: A list of Shapely objects | 3.141454 | 3.083637 | 1.01875 |
params = self.get_url_params()
return params[index] if index < len(params) else default | def get_url_param(self, index, default=None) | Return url parameter with given index.
Args:
- index: starts from zero, and come after controller and
action names in url. | 3.073406 | 4.312931 | 0.712603 |
form_field = self.get_form_field()
widget = form_field.widget
if isinstance(widget, type):
widget = widget()
# Widget instantiation needs to happen manually.
# Auto skip if choices is not an existing attribute.
form_field_choices = getattr(form_field... | def get_widget(self) | Create the widget for the URL type. | 4.377243 | 4.203009 | 1.041454 |
if any(urltype.model == ModelClass for urltype in self._url_types):
raise ValueError("Model is already registered: '{0}'".format(ModelClass))
opts = ModelClass._meta
opts = opts.concrete_model._meta
if not prefix:
# Store something descriptive, easier t... | def register(self, ModelClass, form_field=None, widget=None, title=None, prefix=None, has_id_value=True) | Register a custom model with the ``AnyUrlField``. | 3.667351 | 3.581478 | 1.023977 |
for urltype in self._url_types:
if urltype.model is ModelClass:
return urltype
return None | def get_for_model(self, ModelClass) | Return the URL type for a given model class | 5.993092 | 3.444905 | 1.739697 |
# Any web domain will be handled by the standard URLField.
if self.is_external_url_prefix(prefix):
prefix = 'http'
for i, urltype in enumerate(self._url_types):
if urltype.prefix == prefix:
return i
return None | def index(self, prefix) | Return the model index for a prefix. | 8.915027 | 7.60217 | 1.172695 |
logger.debug("@@ request from Tropo - raw data: %s" % request.body)
try:
post = json.loads(request.body)
except ValueError:
logger.exception("EXCEPTION decoding post data in incoming request")
return HttpResponseBadRequest()
except Exception:
logger.exception("@@res... | def message_received(request, backend_name) | Handle HTTP requests from Tropo. | 5.356634 | 5.19797 | 1.030524 |
content = list_running_builds_raw(page_size, page_index, sort)
if content:
return utils.format_json_list(content) | def list_running_builds(page_size=200, page_index=0, sort="") | List all RunningBuilds | 4.003402 | 4.306703 | 0.929575 |
if session_factory is not None:
# use custom class to create session
sess_factory, sess_args, sess_kwargs = session_factory
s = sess_factory(*sess_args, **sess_kwargs)
else:
# use default session and arguments if not using a custom session
... | def create_session(self, session_id, register=True, session_factory=None) | Creates new session object and returns it.
@param session_id: Session id. If not provided, will generate a
new session id.
@param register: Should be the session registered in a storage.
Websockets don't need it.
@param session_factory: Use ... | 4.271534 | 4.060407 | 1.051997 |
json_msg = None
count = 0
for c in clients:
sess = c.session
if not sess.is_closed:
if sess.send_expects_json:
if json_msg is None:
json_msg = proto.json_encode(msg)
sess.send_jsoni... | def broadcast(self, clients, msg) | Optimized C{broadcast} implementation. Depending on type of the
session, will json-encode message once and will call either
C{send_message} or C{send_jsonifed}.
@param clients: Clients iterable
@param msg: Message to send | 4.742321 | 4.688 | 1.011587 |
'Numerical values limit'
message = N_('value should be between %(min)d and %(max)d') % \
dict(min=min_value, max=max_value)
@validator(message)
def wrapper(conv, value):
if value is None:
# it meens that this value is not required
return True
... | def between(min_value, max_value) | Numerical values limit | 5.353239 | 4.668941 | 1.146564 |
'''
Accepts a value from the form, calls :meth:`to_python` method,
checks `required` condition, applies filters and validators,
catches ValidationError.
:param value: a value to be accepted
:param silent=False: write errors to `form.errors` or not
'''
try... | def accept(self, value, silent=False) | Accepts a value from the form, calls :meth:`to_python` method,
checks `required` condition, applies filters and validators,
catches ValidationError.
:param value: a value to be accepted
:param silent=False: write errors to `form.errors` or not | 7.065432 | 3.788133 | 1.865149 |
'''
Additional clean action to preprocess value before :meth:`to_python`
method.
Subclasses may define own clean_value method to allow additional clean
actions like html cleanup, etc.
'''
# We have to clean before checking min/max length. It's done in
# s... | def clean_value(self, value) | Additional clean action to preprocess value before :meth:`to_python`
method.
Subclasses may define own clean_value method to allow additional clean
actions like html cleanup, etc. | 8.026939 | 3.498264 | 2.294549 |
'''
Yields `(raw_value, label)` pairs for all acceptable choices.
'''
conv = self.conv
for python_value, label in self.choices:
yield conv.from_python(python_value), label | def options(self) | Yields `(raw_value, label)` pairs for all acceptable choices. | 9.977271 | 4.007653 | 2.489554 |
if not isinstance(tzinfo, datetime.tzinfo):
try:
tzinfo = pytz.timezone(tzinfo)
assert tzinfo.zone in pytz.all_timezones
except AttributeError:
raise pytz.UnknownTimeZoneError("Unknown timezone! %s" % tzinfo)
return tzinfo | def _tzinfome(tzinfo) | Gets a tzinfo object from a string.
Args:
tzinfo: A string (or string like) object, or a datetime.tzinfo object.
Returns:
An datetime.tzinfo object.
Raises:
UnknownTimeZoneError: If the timezone given can't be decoded. | 2.763806 | 3.426872 | 0.80651 |
if not isinstance(dt, datetime_tz):
if not dt.tzinfo:
return datetime_tz(dt, tzinfo=localtz())
dt = datetime_tz(dt)
if force_to_local:
return dt.astimezone(localtz())
return dt | def localize(dt, force_to_local=True) | Localize a datetime to the local timezone.
If dt is naive, returns the same datetime with the local timezone, otherwise
uses astimezone to convert.
Args:
dt: datetime object.
force_to_local: Force all results to be in local time.
Returns:
A datetime_tz object. | 2.957502 | 2.924236 | 1.011376 |
if not dt.tzinfo:
return dt
if hasattr(dt, "asdatetime"):
return dt.asdatetime()
return dt.replace(tzinfo=None) | def get_naive(dt) | Gets a naive datetime from a datetime.
datetime_tz objects can't just have tzinfo replaced with None, you need to
call asdatetime.
Args:
dt: datetime object.
Returns:
datetime object without any timezone information. | 4.282936 | 3.360702 | 1.274417 |
if sys.platform == "win32":
tz = _detect_timezone_windows()
if tz is not None:
return tz
# First we try the TZ variable
tz = _detect_timezone_environ()
if tz is not None:
return tz
# Second we try /etc/timezone and use the value in that
tz = _detect_timezone_etc_timezone()
if tz is ... | def detect_timezone() | Try and detect the timezone that Python is currently running in.
We have a bunch of different methods for trying to figure this out (listed in
order they are attempted).
* In windows, use win32timezone.TimeZoneInfo.local()
* Try TZ environment variable.
* Try and find /etc/timezone file (with timezone ... | 4.451632 | 4.031261 | 1.104278 |
tzdir = os.environ.get("TZDIR", "/usr/share/zoneinfo/posix")
localtzdata = {}
for dirpath, _, filenames in os.walk(tzdir):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
name = os.path.relpath(filepath, tzdir)
f = open(filepath, "rb")
tzinfo = pytz.tzfile.bu... | def _load_local_tzinfo() | Load zoneinfo from local disk. | 2.441928 | 2.345924 | 1.040924 |
matches = []
if os.path.exists("/etc/localtime"):
f = open("/etc/localtime", "rb")
localtime = pytz.tzfile.build_tzinfo("/etc/localtime", f)
f.close()
# We want to match against the local database because /etc/localtime will
# be copied from that. Once we have found a name for /etc/localtime... | def _detect_timezone_etc_localtime() | Detect timezone based on /etc/localtime file. | 4.320346 | 4.237794 | 1.01948 |
method = getattr(datetime.datetime, name)
# Have to give the second argument as method has no __module__ option.
@functools.wraps(method, ("__name__", "__doc__"), ())
def wrapper(self, *args, **kw):
r = method(self, *args, **kw)
if isinstance(r, datetime.datetime) and not isinstance(r, type(self)):... | def _wrap_method(name) | Wrap a method.
Patch a method which might return a datetime.datetime to return a
datetime_tz.datetime_tz instead.
Args:
name: The name of the method to patch | 4.384856 | 4.49864 | 0.974707 |
args = list(self.timetuple()[0:6])+[self.microsecond]
if not naive:
args.append(self.tzinfo)
return datetime.datetime(*args) | def asdatetime(self, naive=True) | Return this datetime_tz as a datetime object.
Args:
naive: Return *without* any tz info.
Returns:
This datetime_tz as a datetime object. | 3.926512 | 4.715891 | 0.832613 |
return datetime.date(self.year, self.month, self.day) | def asdate(self) | Return this datetime_tz as a date object.
Returns:
This datetime_tz as a date object. | 3.689134 | 4.46817 | 0.825648 |
# Assert we are not a naive datetime object
assert self.tzinfo is not None
tzinfo = _tzinfome(tzinfo)
d = self.asdatetime(naive=False).astimezone(tzinfo)
return type(self)(d) | def astimezone(self, tzinfo) | Returns a version of this timestamp converted to the given timezone.
Args:
tzinfo: Either a datetime.tzinfo object or a string (which will be looked
up in pytz.
Returns:
A datetime_tz object in the given timezone. | 6.745908 | 7.212688 | 0.935283 |
if "tzinfo" in kw:
if kw["tzinfo"] is None:
raise TypeError("Can not remove the timezone use asdatetime()")
else:
tzinfo = kw["tzinfo"]
del kw["tzinfo"]
else:
tzinfo = None
is_dst = None
if "is_dst" in kw:
is_dst = kw["is_dst"]
del kw["is_dst"]... | def replace(self, **kw) | Return datetime with new specified fields given as arguments.
For example, dt.replace(days=4) would return a new datetime_tz object with
exactly the same as dt but with the days attribute equal to 4.
Any attribute can be replaced, but tzinfo can not be set to None.
Args:
Any datetime_tz attribu... | 3.675047 | 3.527057 | 1.041958 |
obj = datetime.datetime.utcfromtimestamp(timestamp)
obj = pytz.utc.localize(obj)
return cls(obj) | def utcfromtimestamp(cls, timestamp) | Returns a datetime object of a given timestamp (in UTC). | 2.91982 | 2.83813 | 1.028783 |
d = cls.utcfromtimestamp(timestamp)
return d.astimezone(localtz()) | def fromtimestamp(cls, timestamp) | Returns a datetime object of a given timestamp (in local tz). | 7.941899 | 5.959184 | 1.332716 |
obj = datetime.datetime.utcnow()
obj = cls(obj, tzinfo=pytz.utc)
return obj | def utcnow(cls) | Return a new datetime representing UTC day and time. | 4.458402 | 3.810856 | 1.169921 |
obj = cls.utcnow()
if tzinfo is None:
tzinfo = localtz()
return obj.astimezone(tzinfo) | def now(cls, tzinfo=None) | [tz] -> new datetime with tz's local day and time. | 4.264606 | 3.573416 | 1.193426 |
if tzinfo is None:
tzinfo = localtz()
return cls(datetime.datetime.combine(date, time), tzinfo) | def combine(cls, date, time, tzinfo=None) | date, time, [tz] -> datetime with same date and time fields. | 3.943134 | 4.040178 | 0.97598 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.