code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
property_type = property_obj.get('type', 'object')
property_format = property_obj.get('format')
property_dict = {}
if property_type in ['object', 'array']:
schema_type = SchemaTypes.MAPPED if additional_prop else SchemaTypes.INLINE
schema_id = self._get_... | def get_type_properties(self, property_obj, name, additional_prop=False) | Get internal properties of property (extended in schema)
:param dict property_obj: raw property object
:param str name: name of property
:param bool additional_prop: recursion's param
:return: Type, format and internal properties of property
:rtype: tuple(str, str, dict) | 2.948789 | 2.92136 | 1.009389 |
schema_id = self._get_object_schema_id(schema_obj, schema_type)
if not self.storage.contains(schema_id):
schema = self.storage.create_schema(
schema_obj, self.name, schema_type, root=self.root)
assert schema.schema_id == schema_id
self._type = sc... | def set_type_by_schema(self, schema_obj, schema_type) | Set property type by schema object
Schema will create, if it doesn't exists in collection
:param dict schema_obj: raw schema object
:param str schema_type: | 3.881947 | 4.554766 | 0.852282 |
dataset = SimpleDataset(queryset, headers=None)
filename = '{0}.{1}'.format(
smart_str(modeladmin.model._meta.verbose_name_plural), file_type)
response_kwargs = {
'content_type': get_content_type(file_type)
}
response = HttpResponse(getattr(dataset, file_type), **response_kwa... | def tablib_export_action(modeladmin, request, queryset, file_type="xls") | Allow the user to download the current filtered list of items
:param file_type:
One of the formats supported by tablib (e.g. "xls", "csv", "html",
etc.) | 2.738382 | 2.967413 | 0.922818 |
if obj.get('definitions'):
self.schemas.clear()
all_of_stack = []
for name, definition in obj['definitions'].items():
if 'allOf' in definition:
all_of_stack.append((name, definition))
else:
self.... | def _fill_schemas_from_definitions(self, obj) | At first create schemas without 'AllOf'
:param obj:
:return: None | 2.620044 | 2.441767 | 1.073012 |
property_type, property_format, property_dict = \
super(Schema, self).get_type_properties(property_obj, name, additional_prop=additional_prop)
_schema = self.storage.get(property_type)
if _schema and ('additionalProperties' in property_obj):
_property_type, _prop... | def get_type_properties(self, property_obj, name, additional_prop=False) | Extend parents 'Get internal properties of property'-method | 3.483934 | 3.431503 | 1.015279 |
if model_name not in settings.TABLIB_MODELS:
raise Http404()
model = get_model(*model_name.split(".", 2))
if not model:
raise ImproperlyConfigured(
"Model {0} is in settings.TABLIB_MODELS but"
" could not be loaded".format(model_name))
qs = model._default_... | def generic_export(request, model_name=None) | Generic view configured through settings.TABLIB_MODELS
Usage:
1. Add the view to ``urlpatterns`` in ``urls.py``::
url(r'export/(?P<model_name>[^/]+)/$',
"django_tablib.views.generic_export"),
2. Create the ``settings.TABLIB_MODELS`` dictionary using model names
... | 3.314658 | 3.147646 | 1.053059 |
if len(collection) < 1:
return collection
if isinstance(collection, dict):
return sorted(collection.items(), key=lambda x: x[0])
if isinstance(list(collection)[0], Operation):
key = lambda x: x.operation_id
elif isinstance(list(collection)[0... | def sorted(collection) | sorting dict by key,
schema-collection by schema-name
operations by id | 3.033477 | 2.875745 | 1.054849 |
if not SchemaObjects.contains(_type):
return _type
schema = SchemaObjects.get(_type)
if schema.schema_type == SchemaTypes.DEFINITION and not kwargs.get('definition'):
return ''
head =
body = []
if schema.properties:
for p in s... | def get_regular_properties(self, _type, *args, **kwargs) | Make table with properties by schema_id
:param str _type:
:rtype: str | 3.964804 | 3.82424 | 1.036756 |
if not SchemaObjects.contains(_type):
return _type
schema = SchemaObjects.get(_type)
if schema.all_of:
models = ','.join(
(self.get_type_description(_type, *args, **kwargs) for _type in schema.all_of)
)
result = '{}'.format... | def get_type_description(self, _type, suffix='', *args, **kwargs) | Get description of type
:param suffix:
:param str _type:
:rtype: str | 3.673201 | 3.661108 | 1.003303 |
if not SchemaObjects.contains(_type):
return _type
schema = SchemaObjects.get(_type)
body = []
for sch in schema.nested_schemas: # complex types
nested_schema = SchemaObjects.get(sch)
if not (nested_schema or isinstance(nested_schema, SchemaM... | def get_additional_properties(self, _type, *args, **kwargs) | Make head and table with additional properties by schema_id
:param str _type:
:rtype: str | 4.11075 | 3.729138 | 1.102332 |
if not self.natural_text_field or self.attname not in instance.__dict__:
return
edtf = getattr(instance, self.attname)
# Update EDTF field based on latest natural text value, if any
natural_text = getattr(instance, self.natural_text_field)
if natural_text:
... | def pre_save(self, instance, add) | Updates the edtf value from the value of the display_field.
If there's a valid edtf, then set the date values. | 4.580451 | 4.438792 | 1.031914 |
if not delta:
return time_struct # No work to do
try:
dt_result = op(datetime(*time_struct[:6]), delta)
return dt_to_struct_time(dt_result)
except (OverflowError, ValueError):
# Year is not within supported 1 to 9999 AD range
pass
# Here we fake the year t... | def apply_delta(op, time_struct, delta) | Apply a `relativedelta` to a `struct_time` data structure.
`op` is an operator function, probably always `add` or `sub`tract to
correspond to `a_date + a_delta` and `a_date - a_delta`.
This function is required because we cannot use standard `datetime` module
objects for conversion when the date/time ... | 5.706615 | 5.498536 | 1.037843 |
return struct_time(
(
self._precise_year(lean),
self._precise_month(lean),
self._precise_day(lean),
) + tuple(TIME_EMPTY_TIME) + tuple(TIME_EMPTY_EXTRAS)
) | def _strict_date(self, lean) | Return a `time.struct_time` representation of the date. | 5.213581 | 4.30009 | 1.212435 |
result = relativedelta(0)
if self.year_ua:
result += appsettings.PADDING_YEAR_PRECISION * self.year_ua._get_multiplier()
if self.month_ua:
result += appsettings.PADDING_MONTH_PRECISION * self.month_ua._get_multiplier()
if self.day_ua:
result ... | def _get_fuzzy_padding(self, lean) | This is not a perfect interpretation as fuzziness is introduced for
redundant uncertainly modifiers e.g. (2006~)~ will get two sets of
fuzziness. | 1.752137 | 1.735625 | 1.009513 |
logger.info('Packaging lambda {}'.format(self.lambda_name))
zfh = io.BytesIO()
if os.path.exists(os.path.join(self.lambda_dir, '.env')):
logger.warn(
'A .env file exists in your Lambda directory - be '
'careful that it does not contain any se... | def package(self) | Packages lambda data for deployment into a zip | 3.885534 | 3.767762 | 1.031258 |
if not self.role:
logger.error('Missing AWS Role')
raise ArgumentsError('Role required')
logger.debug('Deploying lambda {}'.format(self.lambda_name))
zfh = self.package()
if self.lambda_name in self.get_function_names():
logger.info('Updati... | def deploy(self, *lambdas) | Deploys lambdas to AWS | 2.185838 | 2.150415 | 1.016473 |
for function in self.client.list_functions().get('Functions', []):
lines = json.dumps(function, indent=4, sort_keys=True).split('\n')
for line in lines:
logger.info(line) | def list(self) | Lists already deployed lambdas | 3.799135 | 2.951325 | 1.287264 |
if LooseVersion(django.get_version()) < LooseVersion('1.7.0'):
info = self.model._meta.app_label, self.model._meta.module_name
else:
info = self.model._meta.app_label, self.model._meta.model_name
return info | def get_info(self) | Helper method to get model info in a form of (app_label, model_name).
Avoid deprecation warnings and failures with different Django versions. | 2.237915 | 1.82214 | 1.22818 |
if month == 1 or month == 2:
yearp = year - 1
monthp = month + 12
else:
yearp = year
monthp = month
# this checks where we are in relation to October 15, 1582, the beginning
# of the Gregorian calendar.
if ((year < 1582) or
(year == 1582 and month < 10) ... | def date_to_jd(year,month,day) | Convert a date to Julian Day.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
year : int
Year as integer. Years preceding 1 A.D. should be 0 or negative.
The year before 1 A.D. is 0, 10 B.C.... | 1.706455 | 1.960315 | 0.8705 |
jd = jd + 0.5
F, I = math.modf(jd)
I = int(I)
A = math.trunc((I - 1867216.25)/36524.25)
if I > 2299160:
B = I + 1 + A - math.trunc(A / 4.)
else:
B = I
C = B + 1524
D = math.trunc((C - 122.1) / 365.25)
E = math.trunc(365.25 * D)
G = math.trunc((C - E) /... | def jd_to_date(jd) | Convert Julian Day to date.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
jd : float
Julian Day
Returns
-------
year : int
Year as integer. Years preceding 1 A.D. should be 0 ... | 1.40835 | 1.704872 | 0.826074 |
days = sec + (micro / 1.e6)
days = min + (days / 60.)
days = hour + (days / 60.)
return days / 24. | def hmsm_to_days(hour=0,min=0,sec=0,micro=0) | Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Second number. Defaults to 0.
micro : int, optional
... | 4.084527 | 6.931451 | 0.589274 |
hours = days * 24.
hours, hour = math.modf(hours)
mins = hours * 60.
mins, min = math.modf(mins)
secs = mins * 60.
secs, sec = math.modf(secs)
micro = round(secs * 1.e6)
return int(hour), int(min), int(sec), int(micro) | def days_to_hmsm(days) | Convert fractional days to hours, minutes, seconds, and microseconds.
Precision beyond microseconds is rounded to the nearest microsecond.
Parameters
----------
days : float
A fractional number of days. Must be less than 1.
Returns
-------
hour : int
Hour number.
min :... | 2.253041 | 2.838821 | 0.793654 |
days = date.day + hmsm_to_days(date.hour,date.minute,date.second,date.microsecond)
return date_to_jd(date.year,date.month,days) | def datetime_to_jd(date) | Convert a `datetime.datetime` object to Julian Day.
Parameters
----------
date : `datetime.datetime` instance
Returns
-------
jd : float
Julian day.
Examples
--------
>>> d = datetime.datetime(1985,2,17,6)
>>> d
datetime.datetime(1985, 2, 17, 6, 0)
>>> jdutil... | 3.761026 | 5.555002 | 0.677052 |
year, month, day = jd_to_date(jd)
frac_days,day = math.modf(day)
day = int(day)
hour,min,sec,micro = days_to_hmsm(frac_days)
return datetime(year,month,day,hour,min,sec,micro) | def jd_to_datetime(jd) | Convert a Julian Day to an `jdutil.datetime` object.
Parameters
----------
jd : float
Julian day.
Returns
-------
dt : `jdutil.datetime` object
`jdutil.datetime` equivalent of Julian day.
Examples
--------
>>> jd_to_datetime(2446113.75)
datetime(1985, 2, 17, 6,... | 3.379675 | 5.358748 | 0.630684 |
seconds_in_day = 24. * 3600.
days = td.days + (td.seconds + (td.microseconds * 10.e6)) / seconds_in_day
return days | def timedelta_to_days(td) | Convert a `datetime.timedelta` object to a total number of days.
Parameters
----------
td : `datetime.timedelta` instance
Returns
-------
days : float
Total number of days in the `datetime.timedelta` object.
Examples
--------
>>> td = datetime.timedelta(4.5)
>>> td
... | 3.559674 | 6.498072 | 0.547805 |
if schema_type == SchemaTypes.MAPPED:
schema = SchemaMapWrapper(obj, storage=cls, name=name, root=root)
else:
schema = Schema(obj, schema_type, storage=cls, name=name, root=root)
cls.add_schema(schema)
return schema | def create_schema(cls, obj, name, schema_type, root) | Create Schema object
:param dict obj: swagger schema object
:param str name: schema name
:param str schema_type: schema location.
Can be ``inline``, ``definition`` or ``mapped``
:param BaseSwaggerObject root: root doc
:return: new schema
:rtype: Schema | 3.450793 | 3.642632 | 0.947335 |
result = filter(lambda x: not x.is_inline_array, cls._schemas.values())
if schema_types:
result = filter(lambda x: x.schema_type in schema_types, result)
if sort:
result = sorted(result, key=attrgetter('name'))
return result | def get_schemas(cls, schema_types=None, sort=True) | Get schemas by type. If ``schema_type`` is None, return all schemas
:param schema_types: list of schema types
:type schema_types: list or None
:param bool sort: sort by name
:return: list of schemas
:rtype: list | 2.609718 | 2.887248 | 0.903877 |
tmp = schema.properties[:] # copy
prop = {}
to_dict = lambda e: prop.update({e.pop('name'): e})
[to_dict(i) for i in tmp] # map(to_dict, tmp)
for _prop in _schema.properties:
if prop.get(_prop['name']):
prop.pop(_prop['name'])
if pro... | def merge_schemas(cls, schema, _schema) | Return second Schema, which is extended by first Schema
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#composition-and-inheritance-polymorphism | 4.044907 | 3.75594 | 1.076936 |
if isinstance(dt, datetime):
return struct_time(
[dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second] +
TIME_EMPTY_EXTRAS
)
elif isinstance(dt, date):
return struct_time(
[dt.year, dt.month, dt.day] + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS
... | def dt_to_struct_time(dt) | Convert a `datetime.date` or `datetime.datetime` to a `struct_time`
representation *with zero values* for data fields that we cannot always
rely on for ancient or far-future dates: tm_wday, tm_yday, tm_isdst
NOTE: If it wasn't for the requirement that the extra fields are unset
we could use the `timetu... | 2.57418 | 2.503352 | 1.028293 |
if strip_time:
return struct_time(list(st[:3]) + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS)
else:
return struct_time(list(st[:6]) + TIME_EMPTY_EXTRAS) | def trim_struct_time(st, strip_time=False) | Return a `struct_time` based on the one provided but with the extra fields
`tm_wday`, `tm_yday`, and `tm_isdst` reset to default values.
If `strip_time` is set to true the time value are also set to zero:
`tm_hour`, `tm_min`, and `tm_sec`. | 4.81338 | 5.392931 | 0.892535 |
year, month, day = st[:3]
hours, minutes, seconds = st[3:6]
# Convert time of day to fraction of day
day += jdutil.hmsm_to_days(hours, minutes, seconds)
return jdutil.date_to_jd(year, month, day) | def struct_time_to_jd(st) | Return a float number representing the Julian Date for the given
`struct_time`.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are ignored. | 4.042081 | 4.552027 | 0.887974 |
year, month, day = jdutil.jd_to_date(jd)
# Convert time of day from fraction of day
day_fraction = day - int(day)
hour, minute, second, ms = jdutil.days_to_hmsm(day_fraction)
day = int(day)
# This conversion can return negative values for items we do not want to be
# negative: month, ... | def jd_to_struct_time(jd) | Return a `struct_time` converted from a Julian Date float number.
WARNING: Conversion to then from Julian Date value to `struct_time` can be
inaccurate and lose or gain time, especially for BC (negative) years.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are set to default
values, not real... | 4.918516 | 4.955553 | 0.992526 |
if second < 0:
minute += int(second / 60.0) # Adjust by whole minute in secs
minute -= 1 # Subtract 1 for negative second
second %= 60 # Convert negative second to positive remainder
if minute < 0:
hour += int(minute / 60.0) # Adjust by whole hour in minutes
hour... | def _roll_negative_time_fields(year, month, day, hour, minute, second) | Fix date/time fields which have nonsense negative values for any field
except for year by rolling the overall date/time value backwards, treating
negative values as relative offsets of the next higher unit.
For example minute=5, second=-63 becomes minute=3, second=57 (5 minutes
less 63 seconds)
Th... | 1.710664 | 1.751434 | 0.976722 |
if schema.schema_example:
return schema.schema_example
if ignored_schemas is None:
ignored_schemas = []
if paths is None:
paths = []
if name:
paths = list(map(lambda path: '.'.join((path, name)), paths))
if schema.ref_p... | def get_example_by_schema(cls, schema, ignored_schemas=None, paths=None, name='') | Get example by schema object
:param Schema schema: current schema
:param list ignored_schemas: list of previous schemas
for avoid circular references
:param list paths: list object paths (ex. #/definitions/Model.property)
If nested schemas exists, custom examples checks ... | 2.683538 | 2.6097 | 1.028293 |
path = "#/paths/'{0.path}'/{0.method}/parameters/{name}".format(
operation, name=operation.body.name or 'body')
return cls.get_example_by_schema(operation.body, paths=[path]) | def get_body_example(cls, operation) | Get example for body parameter example by operation
:param Operation operation: operation object | 7.266369 | 7.72945 | 0.940089 |
path = "#/paths/'{}'/{}/responses/{}".format(
operation.path, operation.method, response.name)
kwargs = dict(paths=[path])
if response.type in PRIMITIVE_TYPES:
result = cls.get_example_value_for_primitive_type(
response.type, response.properties,... | def get_response_example(cls, operation, response) | Get example for response object by operation object
:param Operation operation: operation object
:param Response response: response object | 4.48885 | 4.675478 | 0.960084 |
if header.is_array:
result = cls.get_example_for_array(header.item)
else:
example_method = getattr(cls, '{}_example'.format(header.type))
result = example_method(header.properties, header.type_format)
return {header.name: result} | def get_header_example(cls, header) | Get example for header object
:param Header header: Header object
:return: example
:rtype: dict | 4.560533 | 4.507987 | 1.011656 |
paths = kw.get('paths', [])
name = kw.get('name', '')
result = None
if name and paths:
paths = list(map(lambda path: '.'.join((path, name)), paths))
result, path = cls._get_custom_example(paths)
if result is not None and property_['type'] in P... | def get_property_example(cls, property_, nested=None, **kw) | Get example for property
:param dict property_:
:param set nested:
:return: example value | 3.143392 | 3.105476 | 1.012209 |
for d in DENSITY_TYPES:
if d == 'ldpi' and not self.ldpi:
continue # skip ldpi
if d == 'xxxhdpi' and not self.xxxhdpi:
continue # skip xxxhdpi
try:
path = os.path.join(self.out, 'res/drawable-%s' % d)
... | def mkres(self) | Create a directory tree for the resized assets | 3.810195 | 3.251362 | 1.171877 |
current_size = size
current_density = DENSITY_MAP[self.source_density]
target_density = DENSITY_MAP[target_density]
return int(current_size * (target_density / current_density)) | def get_size_for_density(self, size, target_density) | Return the new image size for the target density | 3.413138 | 2.905861 | 1.17457 |
# Get the original filename
_, filename = os.path.split(path)
# Generate the new filename
filename = self.get_safe_filename(filename)
filename = '%s%s' % (self.prefix if self.prefix else '', filename)
# Get the original image size
w, h = im.size
... | def resize_image(self, path, im) | Generate assets from the given image and path in case you've already
called Image.open | 3.137002 | 3.03893 | 1.032272 |
'''Returns the records serialized as Transit/json in utf8'''
with StringIO() as buf:
writer = Writer(buf, "json")
writer.write(records)
return buf.getvalue().encode('utf8') | def encode_transit(records) | Returns the records serialized as Transit/json in utf8 | 6.508848 | 3.533768 | 1.8419 |
if message['action'] == 'upsert':
message.setdefault('key_names', self.key_names)
message['client_id'] = self.client_id
message.setdefault('table_name', self.table_name)
self._add_message(message, callback_arg)
batch = self._take_batch(self.target_message... | def push(self, message, callback_arg=None) | message should be a dict recognized by the Stitch Import API.
See https://www.stitchdata.com/docs/integrations/import-api. | 4.675265 | 4.332475 | 1.079121 |
'''If we have enough data to build a batch, returns all the data in the
buffer and then clears the buffer.'''
if not self._buffer:
return []
enough_messages = len(self._buffer) >= min_records
enough_time = time.time() - self.time_last_batch_sent >= self.batch_delay_... | def _take_batch(self, min_records) | If we have enough data to build a batch, returns all the data in the
buffer and then clears the buffer. | 4.17122 | 2.773325 | 1.50405 |
result = self.parameters
if locations:
result = filter(lambda x: x.location_in in locations, result)
if excludes:
result = filter(lambda x: x.location_in not in excludes, result)
return list(result) | def get_parameters_by_location(self, locations=None, excludes=None) | Get parameters list by location
:param locations: list of locations
:type locations: list or None
:param excludes: list of excludes locations
:type excludes: list or None
:return: list of Parameter
:rtype: list | 2.325222 | 2.440092 | 0.952924 |
body = self.get_parameters_by_location(['body'])
return self.root.schemas.get(body[0].type) if body else None | def body(self) | Return body request parameter
:return: Body parameter
:rtype: Parameter or None | 13.986156 | 10.015071 | 1.396511 |
if not text:
return
t = text.lower()
# try parsing the whole thing
result = text_to_edtf_date(t)
if not result:
# split by list delims and move fwd with the first thing that returns a non-empty string.
# TODO: assemble multiple dates into a {} or [] structure.
... | def text_to_edtf(text) | Generate EDTF string equivalent of a given natural language date string. | 3.666814 | 3.655324 | 1.003143 |
if node.parent is None:
return node
root = node
while root.parent is not None:
root = root.parent
parent = node
while parent.parent is not root:
grandparent = parent.parent
parent.parent = root
parent = grandparent
return root | def find(node) | Find current canonical representative equivalent to node.
Adjust the parent pointer of each node along the way to the root
to point directly at the root for inverse-Ackerman-fast access. | 2.470224 | 2.508592 | 0.984705 |
a = find(a)
b = find(b)
if a is not b:
if a.rank < b.rank:
a.parent = b
elif b.rank < a.rank:
b.parent = a
else:
b.parent = a
a.rank += 1 | def union(a, b) | Assert equality of two nodes a and b so find(a) is find(b). | 1.967024 | 1.756495 | 1.119857 |
node = OrderedDict()
def N(x):
if x in node:
return node[x]
n = node[x] = Node(x)
return n
for x, y in equivalences:
union(N(x), N(y))
eqclass = OrderedDict()
for x, n in node.iteritems():
x_ = find(n).element
if x_ not in eqclass:
... | def classes(equivalences) | Compute mapping from element to list of equivalent elements.
`equivalences` is an iterable of (x, y) tuples representing
equivalences x ~ y.
Returns an OrderedDict mapping each x to the list of elements
equivalent to x. | 3.248194 | 3.245063 | 1.000965 |
table = np.loadtxt(dat_fname, skiprows=1, dtype='f4')
filter_kwargs = dict(
chunks=True,
compression='gzip',
compression_opts=3)
# Filter out pixels with all zeros
idx = ~np.all(table[:,2:32] < 1.e-5, axis=1)
with h5py.File(h5_fname, 'w') as f:
d = np.arange(0... | def ascii2h5(dat_fname, h5_fname) | Converts from the original ASCII format of the Chen+ (2014) 3D dust map to
the HDF5 format.
Args:
dat_fname (:obj:`str`): Filename of the original ASCII .dat file.
h5_fname (:obj:`str`): Output filename to write the resulting HDF5 file to. | 2.487902 | 2.604502 | 0.955231 |
dest_dir = fname_pattern = os.path.join(data_dir(), 'chen2014')
url = 'http://lamost973.pku.edu.cn/site/Photometric-Extinctions-and-Distances/table2.dat'
dat_fname = os.path.join(dest_dir, 'chen2014.dat')
h5_fname = os.path.join(dest_dir, 'chen2014.h5')
md5 = 'f8a2bc46d411c57ca4c76dc344e291f1'... | def fetch(clobber=False) | Downloads the Chen et al. (2014) dust map.
Args:
clobber (Optional[:obj:`bool`]): If ``True``, any existing file will be
overwritten, even if it appears to match. If ``False`` (the
default), :obj:`fetch()` will attempt to determine if the dataset
already exists. This det... | 5.064042 | 4.980799 | 1.016713 |
if len(msg) >= length:
return msg
return symbol * (length - len(msg)) + msg | def lpad(msg, symbol, length) | Left-pad a given string (msg) with a character (symbol) for a given number of bytes (length).
Return the padded string | 2.274624 | 2.983703 | 0.762349 |
if frm == to:
return lpad(string, get_code_string(frm)[0], minlen)
return encode(decode(string, frm), to, minlen) | def changebase(string, frm, to, minlen=0) | Change a string's characters from one base to another.
Return the re-encoded string | 7.201662 | 7.130604 | 1.009965 |
x = int(x)
if x < 253:
return from_int_to_byte(x)
elif x < 65536:
return from_int_to_byte(253) + encode(x, 256, 2)[::-1]
elif x < 4294967296:
return from_int_to_byte(254) + encode(x, 256, 4)[::-1]
else:
return from_int_to_byte(255) + encode(x, 256, 8)[::-1] | def num_to_var_int(x) | (bitcoin-specific): convert an integer into a variable-length integer | 1.815849 | 1.663345 | 1.091685 |
base, minlen = int(base), int(minlen)
code_string = get_code_string(base)
result = ""
while val > 0:
result = code_string[val % base] + result
val //= base
return code_string[0] * max(minlen - len(result), 0) + result | def encode(val, base, minlen=0) | Given an integer value (val) and a numeric base (base),
encode it into the string of symbols with the given base.
(with minimum length minlen)
Returns the (left-padded) re-encoded val as a string. | 2.713201 | 2.674068 | 1.014634 |
base = int(base)
code_string = get_code_string(base)
result = 0
if base == 16:
string = string.lower()
while len(string) > 0:
result *= base
result += code_string.find(string[0])
string = string[1:]
return result | def decode(string, base) | Given a string (string) and a numeric base (base),
decode the string into an integer.
Returns the integer | 2.591824 | 2.84847 | 0.9099 |
alpha = get_code_string(base)
if isinstance(obj, (str, unicode)):
for i in range(len(obj)):
if alpha.find(obj[i]) == -1:
return False
return True
elif isinstance(obj, (int, long, float)) or obj is None:
return True
elif isinstance(obj, list):
... | def json_is_base(obj, base) | Given a primitive compound Python object
(i.e. a dict, string, int, or list) and a numeric base,
verify whether or not the object and all relevant
sub-components have the given numeric base.
Return True if so.
Return False if not. | 2.260856 | 2.077053 | 1.088492 |
if isinstance(obj, (str, unicode)):
return changer(obj)
elif isinstance(obj, (int, long)) or obj is None:
return obj
elif isinstance(obj, list):
return [json_changebase(x, changer) for x in obj]
elif isinstance(obj, dict):
return dict((x, json_changebase(obj[x], ... | def json_changebase(obj, changer) | Given a primitive compound Python object (i.e. a dict,
string, int, or list) and a changer function that takes
a primitive Python object as an argument, apply the
changer function to the object and each sub-component.
Return the newly-reencoded object. | 1.999695 | 1.912425 | 1.045633 |
client = None
if client_type == 'local':
import crosscat.LocalEngine as LocalEngine
le = LocalEngine.LocalEngine(**kwargs)
client = CrossCatClient(le)
elif client_type == 'multiprocessing':
import crosscat.MultiprocessingEngine as MultiprocessingEngine
me = Mu... | def get_CrossCatClient(client_type, **kwargs) | Helper which instantiates the appropriate Engine and returns a Client | 2.429233 | 2.271534 | 1.069424 |
pix_idx = coord2healpix(coords, self._frame,
self._nside, nest=self._nest)
return self._pix_val[pix_idx] | def query(self, coords) | Args:
coords (`astropy.coordinates.SkyCoord`): The coordinates to query.
Returns:
A float array of the value of the map at the given coordinates. The
shape of the output is the same as the shape of the coordinates
stored by `coords`. | 8.637131 | 9.90314 | 0.872161 |
'''Generate token strings which, when joined together, form a valid
XPath serialization of the AST.'''
if hasattr(xp_ast, '_serialize'):
for tok in xp_ast._serialize():
yield tok
elif isinstance(xp_ast, string_types):
# strings in serialized xpath needed to be quoted
... | def _serialize(xp_ast) | Generate token strings which, when joined together, form a valid
XPath serialization of the AST. | 8.090514 | 5.49514 | 1.472304 |
clean()
local(
"LIBRARY_PATH={library_path} CPATH={include_path} {python} "
"setup.py build_ext --inplace".format(
library_path=LIBRARY_PATH,
include_path=INCLUDE_PATH,
python=python,
)) | def build(python=PYTHON) | Build the bigfloat library for in-place testing. | 3.865258 | 3.595463 | 1.075038 |
local(
"LIBRARY_PATH={library_path} CPATH={include_path} {python} "
"setup.py build".format(
library_path=LIBRARY_PATH,
include_path=INCLUDE_PATH,
python=python,
))
local("sudo {python} setup.py install".format(python=python)) | def install(python=PYTHON) | Install into site-packages | 3.366713 | 3.420602 | 0.984246 |
site_packages = local(
"{python} -c 'from distutils.sysconfig import "
"get_python_lib; print(get_python_lib())'".format(python=python),
capture=True,
)
with lcd(site_packages):
local("sudo rm mpfr.so")
local("sudo rm -fr bigfloat")
local("sudo rm bigfloa... | def uninstall(python=PYTHON) | Uninstall from site-packages | 4.236815 | 3.932303 | 1.077439 |
rc = False
start = datetime.datetime.now()
while True:
try:
# advance state
rc = indexer.StateEngine.build(blockchain_opts, last_block + 1, state_engine, expected_snapshots=expected_snapshots, tx_filter=tx_filter )
break
except Exception, e... | def sync_virtualchain(blockchain_opts, last_block, state_engine, expected_snapshots={}, tx_filter=None ) | Synchronize the virtual blockchain state up until a given block.
Obtain the operation sequence from the blockchain, up to and including last_block.
That is, go and fetch each block we haven't seen since the last call to this method,
extract the operations from them, and record in the given working_dir wher... | 4.736512 | 4.674829 | 1.013195 |
# warn about unsupported fields
for f in fields.keys():
if f not in indexer.RESERVED_KEYS:
log.warning("Unsupported virtualchain field '%s'" % f)
# propagate reserved fields
for f in fields.keys():
if f in indexer.RESERVED_KEYS:
op[f] = fields[f]
retur... | def virtualchain_set_opfields( op, **fields ) | Pass along virtualchain-reserved fields to a virtualchain operation.
This layer of indirection is meant to help with future compatibility,
so virtualchain implementations do not try to set operation fields
directly. | 4.666101 | 4.158301 | 1.122117 |
import tarfile
import sys
from glob import glob
from contextlib import closing
# The datatype that will be used to store extinction, A0
A0_dtype = 'float16'
def load_samp_file(f, fname):
# Parse filename
fname_chunks = os.path.split(fname)[1].split('_')
l = fl... | def ascii2h5(dirname, output_fname) | Converts from a directory of tarballed ASCII ".samp" files to a single
HDF5 file. Essentially, converts from the original release format to a
single HDF5 file. | 2.512408 | 2.467671 | 1.018129 |
doi = '10.7910/DVN/VBSI4A'
for component in ['dust', 'err']:
requirements = {'filename': 'PG_{}_4096_ngp.fits'.format(component)}
local_fname = os.path.join(
data_dir(),
'pg2010', 'PG_{}_4096_ngp.fits'.format(component))
print('Downloading P&G (2010) {} ... | def fetch() | Downloads the Peek & Graves (2010) dust map, placing it in
the data directory for :obj:`dustmap`. | 7.474117 | 6.161065 | 1.213121 |
return super(PG2010Query, self).query(coords, order=order) | def query(self, coords, order=1) | Returns the P&G (2010) correction to the SFD'98 E(B-V) at the specified
location(s) on the sky. If component is 'err', then return the
uncertainty in the correction.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
order (Optional[:obj:`int`]... | 8.664098 | 10.441543 | 0.829772 |
c_table = construction_table
for row, i in enumerate(c_table.index):
give_message = ("Not a valid construction table. "
"The index {i} uses an invalid reference").format
if row == 0:
pass
elif row == 1:
... | def _check_construction_table(construction_table) | Checks if a construction table uses valid references.
Raises an exception (UndefinedCoordinateSystem) otherwise. | 3.172984 | 2.679495 | 1.184172 |
c_table = construction_table
angles = self.get_angle_degrees(c_table.iloc[3:, :].values)
problem_index = np.nonzero((175 < angles) | (angles < 5))[0]
rename = dict(enumerate(c_table.index[3:]))
problem_index = [rename[i] for i in problem_index]
return problem_ind... | def check_dihedral(self, construction_table) | Checks, if the dihedral defining atom is colinear.
Checks for each index starting from the third row of the
``construction_table``, if the reference atoms are colinear.
Args:
construction_table (pd.DataFrame):
Returns:
list: A list of problematic indices. | 4.995908 | 4.818074 | 1.03691 |
if use_lookup is None:
use_lookup = settings['defaults']['use_lookup']
problem_index = self.check_dihedral(construction_table)
bond_dict = self._give_val_sorted_bond_dict(use_lookup=use_lookup)
c_table = construction_table.copy()
for i in problem_index:
... | def correct_dihedral(self, construction_table,
use_lookup=None) | Reindexe the dihedral defining atom if linear reference is used.
Uses :meth:`~Cartesian.check_dihedral` to obtain the problematic
indices.
Args:
construction_table (pd.DataFrame):
use_lookup (bool): Use a lookup variable for
:meth:`~chemcoord.Cartesian.g... | 3.15667 | 2.958529 | 1.066973 |
c_table = construction_table
abs_refs = constants.absolute_refs
A = np.empty((3, 3))
row = c_table.index.get_loc(i)
if row > 2:
message = 'The index {i} is not from the first three, rows'.format
raise ValueError(message(i=i))
for k in rang... | def _has_valid_abs_ref(self, i, construction_table) | Checks, if ``i`` uses valid absolute references.
Checks for each index from first to third row of the
``construction_table``, if the references are colinear.
This case has to be specially treated, because the references
are not only atoms (to fix internal degrees of freedom) but also po... | 3.81902 | 3.445601 | 1.108375 |
c_table = construction_table
problem_index = [i for i in c_table.index[:3]
if not self._has_valid_abs_ref(i, c_table)]
return problem_index | def check_absolute_refs(self, construction_table) | Checks first three rows of ``construction_table`` for linear references
Checks for each index from first to third row of the
``construction_table``, if the references are colinear.
This case has to be specially treated, because the references
are not only atoms (to fix internal degrees ... | 7.801718 | 6.564977 | 1.188385 |
c_table = construction_table.copy()
abs_refs = constants.absolute_refs
problem_index = self.check_absolute_refs(c_table)
for i in problem_index:
order_of_refs = iter(permutations(abs_refs.keys()))
finished = False
while not finished:
... | def correct_absolute_refs(self, construction_table) | Reindexe construction_table if linear reference in first three rows
present.
Uses :meth:`~Cartesian.check_absolute_refs` to obtain the problematic
indices.
Args:
construction_table (pd.DataFrame):
Returns:
pd.DataFrame: Appropiately renamed construction... | 4.932533 | 4.73063 | 1.04268 |
c_table = construction_table
default_cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral']
optional_cols = list(set(self.columns) - {'atom', 'x', 'y', 'z'})
zmat_frame = pd.DataFrame(columns=default_cols + optional_cols,
dtype='float', in... | def _build_zmat(self, construction_table) | Create the Zmatrix from a construction table.
Args:
Construction table (pd.DataFrame):
Returns:
Zmat: A new instance of :class:`Zmat`. | 3.287068 | 3.253033 | 1.010463 |
if use_lookup is None:
use_lookup = settings['defaults']['use_lookup']
self.get_bonds(use_lookup=use_lookup)
self._give_val_sorted_bond_dict(use_lookup=use_lookup)
use_lookup = True
# During function execution the connectivity situation won't change
... | def get_zmat(self, construction_table=None,
use_lookup=None) | Transform to internal coordinates.
Transforming to internal coordinates involves basically three
steps:
1. Define an order of how to build and define for each atom
the used reference atoms.
2. Check for problematic local linearity. In this algorithm an
angle with ``170... | 4.759963 | 3.588674 | 1.326385 |
r
if (construction_table.index != self.index).any():
message = "construction_table and self must use the same index"
raise ValueError(message)
c_table = construction_table.loc[:, ['b', 'a', 'd']]
c_table = c_table.replace(constants.int_label)
c_table = c_t... | def get_grad_zmat(self, construction_table, as_function=True) | r"""Return the gradient for the transformation to a Zmatrix.
If ``as_function`` is True, a function is returned that can be directly
applied onto instances of :class:`~Cartesian`, which contain the
applied distortions in cartesian space.
In this case the user does not have to worry abou... | 4.463429 | 4.074826 | 1.095367 |
atoms = self['atom']
data = constants.elements
if pd.api.types.is_list_like(new_cols):
new_cols = set(new_cols)
elif new_cols is None:
new_cols = set(data.columns)
else:
new_cols = [new_cols]
new_frame = data.loc[atoms, set(new... | def add_data(self, new_cols=None) | Adds a column with the requested data.
If you want to see for example the mass, the colormap used in
jmol and the block of the element, just use::
['mass', 'jmol_color', 'block']
The underlying ``pd.DataFrame`` can be accessed with
``constants.elements``.
To see al... | 3.141033 | 3.278287 | 0.958133 |
try:
mass = self.loc[:, 'mass'].sum()
except KeyError:
mass_molecule = self.add_data('mass')
mass = mass_molecule.loc[:, 'mass'].sum()
return mass | def get_total_mass(self) | Returns the total mass in g/mol.
Args:
None
Returns:
float: | 4.910397 | 5.936781 | 0.827114 |
same_atoms = True
for atom in set(self['atom']):
own_atom_number = len(self[self['atom'] == atom])
other_atom_number = len(other[other['atom'] == atom])
same_atoms = (own_atom_number == other_atom_number)
if not same_atoms:
break
... | def has_same_sumformula(self, other) | Determines if ``other`` has the same sumformula
Args:
other (molecule):
Returns:
bool: | 2.787069 | 2.990115 | 0.932094 |
atomic_number = constants.elements['atomic_number'].to_dict()
return sum([atomic_number[atom] for atom in self['atom']]) - charge | def get_electron_number(self, charge=0) | Return the number of electrons.
Args:
charge (int): Charge of the molecule.
Returns:
int: | 8.242235 | 12.528076 | 0.657901 |
api_instance.json_encoder = JSONEncodeManager()
dumps_settings = {} if extra_settings is None else extra_settings
dumps_settings['default'] = api_instance.json_encoder
dumps_settings.setdefault('ensure_ascii', False)
@api_instance.representation('application/json')
def output_json(data, c... | def enhance_json_encode(api_instance, extra_settings=None) | use `JSONEncodeManager` replace default `output_json` function of Flask-RESTful
for the advantage of use `JSONEncodeManager`, please see https://github.com/anjianshi/json_encode_manager | 2.517215 | 2.195506 | 1.146531 |
output_json = api_instance.representations['application/json']
@api_instance.representation('application/json')
def handle_jsonp(data, code, headers=None):
resp = output_json(data, code, headers)
if code == 200:
callback = request.args.get(callback_name_source, False) if n... | def support_jsonp(api_instance, callback_name_source='callback') | Let API instance can respond jsonp request automatically.
`callback_name_source` can be a string or a callback.
If it is a string, the system will find the argument that named by this string in `query string`.
If found, determine this request to be a jsonp request, and use the argument's value as ... | 2.96245 | 3.162348 | 0.936788 |
return self._frame.sort_values(by, axis=axis, ascending=ascending,
inplace=False, kind=kind,
na_position=na_position) | def sort_values(self, by, axis=0, ascending=True,
kind='quicksort', na_position='last') | Sort by the values along either axis
Wrapper around the :meth:`pandas.DataFrame.sort_values` method. | 2.669373 | 3.294152 | 0.810337 |
return self._frame.sort_index(axis=axis, level=level,
ascending=ascending, inplace=inplace,
kind=kind, na_position=na_position,
sort_remaining=sort_remaining, by=by) | def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
kind='quicksort', na_position='last',
sort_remaining=True, by=None) | Sort object by labels (along an axis)
Wrapper around the :meth:`pandas.DataFrame.sort_index` method. | 1.729769 | 2.008117 | 0.861388 |
out = self if inplace else self.copy()
out._frame.insert(loc, column, value,
allow_duplicates=allow_duplicates)
if not inplace:
return out | def insert(self, loc, column, value, allow_duplicates=False,
inplace=False) | Insert column into molecule at specified location.
Wrapper around the :meth:`pandas.DataFrame.insert` method. | 3.271585 | 3.308918 | 0.988717 |
script_hash = hashing.bin_sha256(script.decode('hex')).encode('hex')
scriptsig_script = '0020' + script_hash
addr = btc_make_p2sh_address(scriptsig_script)
return addr | def make_multisig_segwit_address_from_witness_script(script) | multisig witness script (p2sh-p2wsh) to address | 4.845067 | 4.763829 | 1.017053 |
pubs = []
privkeys = []
for pk in pks:
priv = None
if compressed in [True, False]:
priv = BitcoinPrivateKey(pk, compressed=compressed)
else:
priv = BitcoinPrivateKey(pk)
priv_hex = priv.to_hex()
pub_hex = priv.public_key().to_hex()
... | def make_multisig_info( m, pks, compressed=None ) | Make a multisig address and redeem script.
@m of the given @pks must sign.
Return {'address': p2sh address, 'redeem_script': redeem script, 'private_keys': private keys, 'segwit': False}
* privkeys will be hex-encoded
* redeem_script will be hex-encoded | 2.653636 | 2.230851 | 1.189518 |
pubs = []
privkeys = []
for pk in pks:
priv = BitcoinPrivateKey(pk, compressed=True)
priv_hex = priv.to_hex()
pub_hex = priv.public_key().to_hex()
privkeys.append(priv_hex)
pubs.append(keylib.key_formatting.compress(pub_hex))
script = None
if len(pubs)... | def make_multisig_segwit_info( m, pks ) | Make either a p2sh-p2wpkh or p2sh-p2wsh
redeem script and p2sh address.
Return {'address': p2sh address, 'redeem_script': **the witness script**, 'private_keys': privkeys, 'segwit': True}
* privkeys and redeem_script will be hex-encoded | 3.598365 | 3.34023 | 1.077281 |
if m <= 1 and n <= 1:
raise ValueError("Invalid multisig parameters")
pks = []
for i in xrange(0, n):
pk = BitcoinPrivateKey(compressed=True).to_wif()
pks.append(pk)
return make_multisig_info( m, pks ) | def make_multisig_wallet( m, n ) | Create a bundle of information
that can be used to generate an
m-of-n multisig scriptsig. | 3.977684 | 3.734946 | 1.064991 |
if privkey is None:
privkey = BitcoinPrivateKey(compressed=True).to_wif()
return make_multisig_segwit_info(1, [privkey]) | def make_segwit_info(privkey=None) | Create a bundle of information
that can be used to generate
a p2sh-p2wpkh transaction | 5.134583 | 5.128597 | 1.001167 |
pks = []
for i in xrange(0, n):
pk = BitcoinPrivateKey(compressed=True).to_wif()
pks.append(pk)
return make_multisig_segwit_info(m, pks) | def make_multisig_segwit_wallet( m, n ) | Create a bundle of information
that can be used to generate an
m-of-n multisig witness script. | 4.105888 | 4.364386 | 0.940771 |
script_parts = []
redeem_script_hex = str(redeem_script_hex)
try:
script_parts = btc_script_deserialize(redeem_script_hex)
except:
if os.environ.get("BLOCKSTACK_TEST") == "1":
traceback.print_exc()
log.error("Invalid redeem script %s" % redeem_script_hex)
... | def parse_multisig_redeemscript( redeem_script_hex ) | Given a redeem script (as hex), extract multisig information.
Return m, list of public keys on success
Return (None, None) | 2.678277 | 2.613754 | 1.024686 |
try:
script_parts = btc_script_deserialize(scriptsig_hex)
except:
if os.environ.get("BLOCKSTACK_TEST") == "1":
traceback.print_exc()
return None
# sanity check
return script_parts | def parse_multisig_scriptsig( scriptsig_hex ) | Given a scriptsig (as hex), extract the signatures.
Return list of signatures on success
Return None on error | 6.76406 | 7.093896 | 0.953504 |
settings = app.app.registry.settings
config = settings.get(CONFIG_RESOURCES, None)
if not config:
return
resources = [(k, [wrapper(r, GroupResource(k, v)) for r in v])
for k, v in config]
settings[CONFIG_RESOURCES] = resources | def resources_preparing_factory(app, wrapper) | Factory which wrap all resources in settings. | 6.346689 | 6.029095 | 1.052677 |
txobj = btc_tx_deserialize(tx_hex)
tx_num_bytes = len(tx_hex) / 2
num_virtual_bytes = None
if btc_tx_is_segwit(tx_hex):
# segwit--discount witness data
witness_len = 0
for inp in txobj['ins']:
witness_len += len(inp['witness_script']) / 2
# see https:... | def calculate_tx_fee( tx_hex, fee_per_byte ) | High-level API call (meant to be blockchain-agnostic)
What is the fee for the transaction? | 3.77705 | 3.774445 | 1.00069 |
if bitcoind_client is None:
bitcoind_client = get_bitcoind_client(bitcoind_opts=bitcoind_opts, config_path=config_path)
try:
# try to confirm in 2-3 blocks
try:
fee_info = bitcoind_client.estimatesmartfee(2)
if 'errors' in fee_info and len(fee_info['errors']... | def get_tx_fee_per_byte(bitcoind_opts=None, config_path=None, bitcoind_client=None) | Get the tx fee per byte from the underlying blockchain
Return the fee on success
Return None on error | 3.013513 | 2.961549 | 1.017546 |
tx_fee_per_byte = get_tx_fee_per_byte(config_path=config_path, bitcoind_opts=bitcoind_opts, bitcoind_client=bitcoind_client)
if tx_fee_per_byte is None:
return None
return calculate_tx_fee(tx_hex, tx_fee_per_byte) | def get_tx_fee(tx_hex, config_path=None, bitcoind_opts=None, bitcoind_client=None) | Get the tx fee for a tx
Return the fee on success
Return None on error | 1.842246 | 1.935736 | 0.951703 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.