code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
class RingBuffer(_RingBufferBase):
__doc__ = _RingBufferBase.__doc__
_ffi = ffi
_lib = lib
return RingBuffer | def init(ffi, lib) | Return RingBuffer class using the given CFFI instance. | 4.616734 | 3.43231 | 1.345081 |
try:
data = self._ffi.from_buffer(data)
except TypeError:
pass # input is not a buffer
if size < 0:
size, rest = divmod(self._ffi.sizeof(data), self.elementsize)
if rest:
raise ValueError('data size must be multiple of ele... | def write(self, data, size=-1) | Write data to the ring buffer.
This advances the write index after writing;
calling :meth:`advance_write_index` is *not* necessary.
:param data: Data to write to the buffer.
:type data: CData pointer or buffer or bytes
:param size: The number of elements to be written.
... | 4.411844 | 4.470865 | 0.986799 |
if size < 0:
size = self.read_available
data = self._ffi.new('unsigned char[]', size * self.elementsize)
size = self.readinto(data)
return self._ffi.buffer(data, size * self.elementsize) | def read(self, size=-1) | Read data from the ring buffer into a new buffer.
This advances the read index after reading;
calling :meth:`advance_read_index` is *not* necessary.
:param size: The number of elements to be read.
If not specified, all available elements are read.
:type size: int, optional
... | 3.905493 | 4.336639 | 0.900581 |
try:
data = self._ffi.from_buffer(data)
except TypeError:
pass # input is not a buffer
size, rest = divmod(self._ffi.sizeof(data), self.elementsize)
if rest:
raise ValueError('data size must be multiple of elementsize')
return self._l... | def readinto(self, data) | Read data from the ring buffer into a user-provided buffer.
This advances the read index after reading;
calling :meth:`advance_read_index` is *not* necessary.
:param data: The memory where the data should be stored.
:type data: CData pointer or buffer
:returns: The number of e... | 4.749826 | 4.89472 | 0.970398 |
ptr1 = self._ffi.new('void**')
ptr2 = self._ffi.new('void**')
size1 = self._ffi.new('ring_buffer_size_t*')
size2 = self._ffi.new('ring_buffer_size_t*')
return (self._lib.PaUtil_GetRingBufferWriteRegions(
self._ptr, size, ptr1, size1, ptr2, size2),
... | def get_write_buffers(self, size) | Get buffer(s) to which we can write data.
When done writing, use :meth:`advance_write_index` to make the
written data available for reading.
:param size: The number of elements desired.
:type size: int
:returns:
* The room available to be written or the given *size... | 2.821871 | 2.886301 | 0.977677 |
ptr1 = self._ffi.new('void**')
ptr2 = self._ffi.new('void**')
size1 = self._ffi.new('ring_buffer_size_t*')
size2 = self._ffi.new('ring_buffer_size_t*')
return (self._lib.PaUtil_GetRingBufferReadRegions(
self._ptr, size, ptr1, size1, ptr2, size2),
... | def get_read_buffers(self, size) | Get buffer(s) from which we can read data.
When done reading, use :meth:`advance_read_index` to make the
memory available for writing again.
:param size: The number of elements desired.
:type size: int
:returns:
* The number of elements available for reading (which... | 2.824224 | 2.907624 | 0.971317 |
return [(host, len(li)) for (host, li) in self._cm.get_all().items()] | def open_connections(self) | return a list of connected hosts and the number of connections
to each. [('foo.com:80', 2), ('bar.org', 1)] | 16.100645 | 7.764111 | 2.073727 |
for h in self._cm.get_all(host):
self._cm.remove(h)
h.close() | def close_connection(self, host) | close connection(s) to <host>
host is the host:port spec, as in 'www.cnn.com:8080' as passed in.
no error occurs if there is no connection to that host. | 6.676861 | 7.864536 | 0.848983 |
for host, conns in self._cm.get_all().items():
for h in conns:
self._cm.remove(h)
h.close() | def close_all(self) | close all open connections | 6.685288 | 5.741787 | 1.164322 |
try:
self._start_transaction(h, req)
r = h.getresponse()
# note: just because we got something back doesn't mean it
# worked. We'll check the version below, too.
except (socket.error, httplib.HTTPException):
r = None
except:
... | def _reuse_connection(self, h, req, host) | start the transaction with a re-used connection
return a response object (r) upon success or None on failure.
This DOES not close or remove bad connections in cases where
it returns. However, if an unexpected exception occurs, it
will close and remove the connection before re-raising. | 6.412775 | 5.956836 | 1.07654 |
assert os.path.exists(sdmfile), 'sdmfile %s does not exist' % sdmfile
sdm = getsdm(sdmfile, bdfdir=bdfdir)
scan = sdm.scan(scannum)
assert scan.bdf.fname, 'bdfstr not defined for scan %d' % scannum
if readints == 0:
readints = scan.bdf.numIntegration - nskip
logger.info('Reading... | def read_bdf(sdmfile, scannum, nskip=0, readints=0, bdfdir='') | Uses sdmpy to read a given range of integrations from sdm of given scan.
readints=0 will read all of bdf (skipping nskip). | 5.264582 | 4.512484 | 1.166671 |
# define times to read
if segment != -1:
assert 'segmenttimes' in d, 'd must have segmenttimes defined'
t0 = d['segmenttimes'][segment][0]
t1 = d['segmenttimes'][segment][1]
datetime = qa.time(qa.quantity((t1+t0)/2, 'd'),
form=['ymdhms'], prec=9)... | def get_uvw_segment(d, segment=-1) | Calculates uvw for each baseline at mid time of a given segment.
d defines pipeline state. assumes segmenttimes defined by RT.set_pipeline. | 4.364814 | 4.144078 | 1.053265 |
sdm = getsdm(sdmname)
sourcedict = {}
for row in sdm['Field']:
src = str(row.fieldName)
sourcenum = int(row.sourceId)
direction = str(row.referenceDir)
(ra,dec) = [float(val) for val in direction.split(' ')[3:]] # skip first two values in string
sourcedict[so... | def read_sources(sdmname) | Use sdmpy to get all sources and ra,dec per scan as dict | 3.784451 | 3.528387 | 1.072573 |
sdm = getsdm(sdmfile, bdfdir=bdfdir)
scandict = {}
skippedscans = []
for scan in sdm.scans():
scannum = int(scan.idx)
scandict[scannum] = {}
intentstr = ' '.join(scan.intents)
src = scan.source
scandict[scannum]['source'] = src
scandict[scannum]['... | def read_scans(sdmfile, bdfdir='') | Use sdmpy to get all scans and info needed for rtpipe as dict | 3.39396 | 3.214272 | 1.055903 |
# fill ms file
if os.path.exists(msfile):
logger.debug('%s already set.' % msfile)
else:
logger.info('No %s found. Creating anew.' % msfile)
if inttime != '0':
logger.info('Filtering by int time.')
call(['asdm2MS', '--ocm', 'co',
... | def sdm2ms(sdmfile, msfile, scan, inttime='0') | Converts sdm to ms format for a single scan.
msfile defines the name template for the ms. Should end in .ms,
but "s<scan>" will be put in.
scan is string of (sdm counted) scan number.
inttime is string to feed to split command.
gives option of integrated data down in time. | 5.338151 | 5.422865 | 0.984378 |
try:
sdm = sdmpy.SDM(*args, **kwargs)
except XMLSyntaxError:
kwargs['use_xsd'] = False
sdm = sdmpy.SDM(*args, **kwargs)
return sdm | def getsdm(*args, **kwargs) | Wrap sdmpy.SDM to get around schema change error | 4.033817 | 2.567767 | 1.570944 |
self.logger.info("Dimmer %s start_change: %s", self.device_id, direction)
if direction == 'up':
level = '01'
elif direction == 'down':
level = '00'
else:
self.logger.error("Dimmer %s start_change: %s is invalid, use up or down",
... | def start_change(self, direction) | Start changing light level manually. Direction should be 'up' or 'down | 2.831628 | 2.703716 | 1.047309 |
self.logger.info("Dimmer %s stop_change", self.device_id)
self.hub.direct_command(self.device_id, '18', '00')
success = self.hub.check_success(self.device_id, '18', '00')
if success:
self.logger.info("Dimmer %s stop_change: Light stopped changing successfully",
... | def stop_change(self) | Stop changing light level manually | 3.462641 | 3.20049 | 1.081909 |
self.logger.info("Dimmer %s beep", self.device_id)
self.hub.direct_command(self.device_id, '30', '00')
success = self.hub.check_success(self.device_id, '30', '00')
return success | def beep(self) | Make dimmer beep. Not all devices support this | 5.618227 | 4.517782 | 1.243581 |
pk = None
if self._lazy_collection['pks']:
if len(self._lazy_collection['pks']) > 1:
raise ValueError('Too much pks !')
pk = list(self._lazy_collection['pks'])[0]
return pk | def _get_pk(self) | Return None if we don't have any filter on a pk, the pk if we have one,
or raise a ValueError if we have more than one.
For internal use only. | 3.982854 | 3.64512 | 1.092654 |
sort_options = {}
if self._sort is not None and not has_pk:
sort_options.update(self._sort)
if self._sort_limits is not None:
if 'start' in self._sort_limits and 'num' not in self._sort_limits:
self._sort_limits['num'] = -1
elif 'num' ... | def _prepare_sort_options(self, has_pk) | Prepare "sort" options to use when calling the collection, depending
on "_sort" and "_sort_limits" attributes | 1.995596 | 1.727737 | 1.155035 |
old_sort_limits_and_len_mode = None if self._sort_limits is None else self._sort_limits.copy(), self._len_mode
try: # try block to always reset the _sort_limits in the "finally" part
conn = self.cls.get_connection()
self._len = 0
# The collection fails (em... | def _collection(self) | Effectively retrieve data according to lazy_collection. | 5.530321 | 5.393572 | 1.025354 |
conn = self.cls.get_connection()
if sort_options is not None:
# a sort, or values, call the SORT command on the set
return conn.sort(final_set, **sort_options)
else:
# no sort, nor values, simply return the full set
return conn.smembers(f... | def _final_redis_call(self, final_set, sort_options) | The final redis call to obtain the values to return from the "final_set"
with some sort options. | 5.569245 | 5.492976 | 1.013885 |
# we want instances, so create an object for each pk, without
# checking for pk existence if asked
meth = self.cls.lazy_connect if self._instances_skip_exist_test else self.cls
return [meth(pk) for pk in pks] | def _to_instances(self, pks) | Returns a list of instances for each given pk, respecting the condition
about checking or not if a pk exists. | 19.944136 | 17.590183 | 1.133822 |
if self._instances:
results = self._to_instances(results)
else:
results = list(results)
# cache the len for future use
self._len = len(results)
return results | def _prepare_results(self, results) | Called in _collection to prepare results from redis before returning
them. | 5.990939 | 5.385355 | 1.11245 |
final_sets = set()
tmp_keys = set()
for set_ in sets:
if isinstance(set_, str):
final_sets.add(set_)
elif isinstance(set_, ParsedFilter):
for index_key, key_type, is_tmp in set_.index.get_filtered_keys(
... | def _prepare_sets(self, sets) | Return all sets in self._lazy_collection['sets'] to be ready to be used
to intersect them. Called by _get_final_set, to use in subclasses.
Must return a tuple with a set of redis set keys, and another with
new temporary keys to drop at the end of _get_final_set | 4.237914 | 3.852962 | 1.09991 |
conn = self.cls.get_connection()
all_sets = set()
tmp_keys = set()
if pk is not None and not sets and not (sort_options and sort_options.get('get')):
# no final set if only a pk without values to retrieve
return (None, False)
elif sets or pk:
... | def _get_final_set(self, sets, pk, sort_options) | Called by _collection to get the final set to work on. Return the name
of the set to use, and a list of keys to delete once the collection is
really called (in case of a computed set based on multiple ones) | 4.096328 | 3.78177 | 1.083177 |
self.cls.get_connection().sinterstore(final_set, list(sets))
return final_set | def _combine_sets(self, sets, final_set) | Given a list of set, combine them to create the final set that will be
used to make the final redis call. | 12.435447 | 7.520434 | 1.653554 |
if self.cls._field_is_pk(field_name):
return True
if field_name.endswith('__eq') and self.cls._field_is_pk(field_name[:-4]):
return True
return False | def _field_is_pk(self, field_name) | Check if the given name is the pk field, suffixed or not with "__eq" | 3.136449 | 2.274688 | 1.378848 |
for key, value in filters.items():
if self._field_is_pk(key):
pk = self.cls.get_field('pk').normalize(value)
self._lazy_collection['pks'].add(pk)
else:
# store the info to call the index later, in ``_prepare_sets``
... | def _add_filters(self, **filters) | Define self._lazy_collection according to filters. | 7.206399 | 6.202298 | 1.161892 |
self.reset_result_type()
self._instances = True
self._instances_skip_exist_test = skip_exist_test
return self | def instances(self, skip_exist_test=False) | Ask the collection to return a list of instances.
If skip_exist_test is set to True, the instances returned by the
collection won't have their primary key checked for existence. | 6.065338 | 6.175042 | 0.982234 |
fields = []
for field_name in self.cls._fields:
field = self.cls.get_field(field_name)
if not isinstance(field, MultiValuesField):
fields.append(field_name)
return fields | def _get_simple_fields(self) | Return a list of the names of all fields that handle simple values
(StringField or InstanceHashField), that redis can use to return values via
the sort command (so, exclude all fields based on MultiValuesField) | 3.703561 | 2.370904 | 1.562088 |
parameters = self._coerce_by_parameter(parameters)
self._sort = parameters
return self | def sort(self, **parameters) | Parameters:
`by`: pass either a field name or a wildcard string to sort on
prefix with `-` to make a desc sort.
`alpha`: set it to True to sort lexicographically instead of numerically. | 10.669002 | 11.45429 | 0.931442 |
loc, prop, d0 = pc.read_candidates(candsfile, snrmin=threshold, returnstate=True)
if 'snr2' in d0['features']:
snrcol = d0['features'].index('snr2')
elif 'snr1' in d0['features']:
snrcol = d0['features'].index('snr1')
dmindcol = d0['featureind'].index('dmind')
if len(loc):
... | def list_cands(candsfile, threshold=0.) | Prints candidate info in time order above some threshold | 5.204844 | 5.135461 | 1.01351 |
if candnum >= 0:
candlocs, candprops, d0 = pc.read_candidates(candsfile, snrmin=threshold, returnstate=True)
candloc = candlocs[candnum]
candprop = candprops[candnum]
logger.info('Refining cand {0} with features {1}'.format(candloc, candprop))
values = rt.pipeline_refi... | def refine_cand(candsfile, candloc=[], candnum=-1, threshold=0, scaledm=2.1, scalepix=2, scaleuv=1.0, chans=[], returndata=False) | Helper function to interact with merged cands file and refine analysis
candsfile is merged pkl file
candloc (scan, segment, candint, dmind, dtind, beamnum) is as above.
if no candloc, then it prints out cands above threshold. | 2.728822 | 2.815834 | 0.969099 |
# get snrs above threshold
locs, props, d = pc.read_candidates(candsfile, snrmin=threshold, returnstate=True)
if 'snr2' in d['features']:
snrcol = d['features'].index('snr2')
elif 'snr1' in d['features']:
snrcol = d['features'].index('snr1')
scancol = d['featureind'].index('sc... | def refine_cands(candsfile, threshold=0, scaledm=2.1, scalepix=2, scaleuv=1.0, chans=[], savepkl=True) | Runs refine_cand on all positive SNR candidates above threshold. Any detected at higher SNR are highlighted. | 2.864609 | 2.833714 | 1.010902 |
scan, segment, candint, dmind, dtind, beamnum = candloc
# set up state and find absolute integration of candidate
d0 = pickle.load(open(candsfile, 'r'))
filename = os.path.basename(d0['filename'])
readints0 = d0['readints']
nskip0 = (24*3600*(d0['segmenttimes'][segment, 0]
... | def convertloc(candsfile, candloc, memory_limit) | For given state and location that are too bulky, calculate new location given memory_limit. | 3.872399 | 3.799217 | 1.019262 |
import math
srcra = np.degrees(pt_ra + l1/math.cos(pt_dec))
srcdec = np.degrees(pt_dec + m1)
return deg2HMS(srcra, srcdec) | def source_location(pt_ra, pt_dec, l1, m1) | Takes phase center and src l,m in radians to get ra,dec of source.
Returns string ('hh mm ss', 'dd mm ss') | 3.91804 | 3.709558 | 1.056201 |
RA, DEC, rs, ds = '', '', '', ''
if dec:
if str(dec)[0] == '-':
ds, dec = '-', abs(dec)
deg = int(dec)
decM = abs(int((dec-deg)*60))
if round:
decS = int((abs((dec-deg)*60)-decM)*60)
else:
decS = (abs((dec-deg)*60)-decM)*60
... | def deg2HMS(ra='', dec='', round=False) | quick and dirty coord conversion. googled to find bdnyc.org. | 1.845405 | 1.871325 | 0.986149 |
for v in ('1.2', '1.1', '1.0'):
try:
tree.find('channel/{%s}wxr_version' % (WP_NS % v)).text
return v
except AttributeError:
pass
raise CommandError('Cannot resolve the wordpress namespace') | def guess_wxr_version(self, tree) | We will try to guess the wxr version used
to complete the wordpress xml namespace name. | 7.953933 | 5.326326 | 1.493325 |
self.write_out(self.style.STEP('- Importing authors\n'))
post_authors = set()
for item in tree.findall('channel/item'):
post_type = item.find('{%s}post_type' % WP_NS).text
if post_type == 'post':
post_authors.add(item.find(
'{... | def import_authors(self, tree) | Retrieve all the authors used in posts
and convert it to new or existing author and
return the conversion. | 3.158383 | 2.980426 | 1.059709 |
action_text = "The author '%s' needs to be migrated to an user:\n"\
"1. Use an existing user ?\n"\
"2. Create a new user ?\n"\
"Please select a choice: " % self.style.ITEM(author_name)
while 42:
selection = input(smar... | def migrate_author(self, author_name) | Handle actions for migrating the authors. | 2.856664 | 2.855012 | 1.000578 |
self.write_out(self.style.STEP('- Importing categories\n'))
categories = {}
for category_node in category_nodes:
title = category_node.find('{%s}cat_name' % WP_NS).text[:255]
slug = category_node.find(
'{%s}category_nicename' % WP_NS).text[:255]
... | def import_categories(self, category_nodes) | Import all the categories from 'wp:category' nodes,
because categories in 'item' nodes are not necessarily
all the categories and returning it in a dict for
database optimizations. | 2.932215 | 2.730922 | 1.073709 |
self.write_out(self.style.STEP('- Importing tags\n'))
for tag_node in tag_nodes:
tag_name = tag_node.find(
'{%s}tag_slug' % WP_NS).text[:50]
self.write_out('> %s... ' % tag_name)
Tag.objects.get_or_create(name=tag_name)
self.write_... | def import_tags(self, tag_nodes) | Import all the tags form 'wp:tag' nodes,
because tags in 'item' nodes are not necessarily
all the tags, then use only the nicename, because it's like
a slug and the true tag name may be not valid for url usage. | 4.2598 | 3.626024 | 1.174785 |
tags = []
for category in categories:
domain = category.attrib.get('domain', 'category')
if 'tag' in domain and category.attrib.get('nicename'):
tags.append(category.attrib.get('nicename'))
return tags | def get_entry_tags(self, categories) | Return a list of entry's tags,
by using the nicename for url compatibility. | 3.823487 | 3.08616 | 1.238914 |
categories = []
for category_node in category_nodes:
domain = category_node.attrib.get('domain')
if domain == 'category':
categories.append(self.categories[category_node.text])
return categories | def get_entry_categories(self, category_nodes) | Return a list of entry's categories
based on imported categories. | 2.952775 | 2.664127 | 1.108346 |
try:
creation_date = datetime.strptime(
item_node.find('{%s}post_date_gmt' % WP_NS).text,
'%Y-%m-%d %H:%M:%S')
except ValueError as error:
print 'Import entry error: {}'.format(error)
creation_date = datetime.now()
if... | def import_entry(self, title, content, item_node) | Importing an entry but some data are missing like
related entries, start_publication and end_publication.
start_publication and creation_date will use the same value,
wich is always in Wordpress $post->post_date. | 2.454098 | 2.404082 | 1.020804 |
self.write_out(self.style.STEP('- Importing entries\n'))
for item_node in items:
title = (item_node.find('title').text or '')[:255]
post_type = item_node.find('{%s}post_type' % WP_NS).text
content = item_node.find(
'{http://purl.org/rss/1.0/m... | def import_entries(self, items) | Loops over items and find entry to import,
an entry need to have 'post_type' set to 'post' and
have content. | 2.842235 | 2.67437 | 1.062768 |
for comment_node in comment_nodes:
is_pingback = comment_node.find(
'{%s}comment_type' % WP_NS).text == PINGBACK
is_trackback = comment_node.find(
'{%s}comment_type' % WP_NS).text == TRACKBACK
title = 'Comment #%s' % (comment_node.fin... | def import_comments(self, entry, comment_nodes) | Loops over comments nodes and import then
in django_comments. | 2.218961 | 2.15813 | 1.028187 |
'''
>>> dd = DiskDict(DATA_FILE)
>>> print(dd.get('deepcompute'))
1
'''
k = self._enckey(k)
v = self._f.get(k, None)
if v is None: return default
return pickle.loads(v) | def get(self, k, default=None) | >>> dd = DiskDict(DATA_FILE)
>>> print(dd.get('deepcompute'))
1 | 6.59647 | 3.108818 | 2.121858 |
'''
>>> dd = DiskDict(DATA_FILE)
>>> print(next(dd.items()))
('deepcompute', 1)
'''
for k, v in self._f:
yield self._deckey(k), pickle.loads(v) | def items(self) | >>> dd = DiskDict(DATA_FILE)
>>> print(next(dd.items()))
('deepcompute', 1) | 11.643531 | 3.544678 | 3.284792 |
_EPS = 1.254e-5
vector = self.get_parameter_vector()
value0 = self.get_value(*args, **kwargs)
grad = np.empty([len(vector)] + list(value0.shape), dtype=np.float64)
for i, v in enumerate(vector):
vector[i] = v + _EPS
self.set_parameter_vector(vecto... | def compute_gradient(self, *args, **kwargs) | Compute the "gradient" of the model for the current parameters
The default implementation computes the gradients numerically using
a first order forward scheme. For better performance, this method
should be overloaded by subclasses. The output of this function
should be an array where t... | 2.515795 | 2.565095 | 0.98078 |
'''Refetch instance data from the API.
'''
response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id))
attributes = response.json()
self.category = Category(attributes['category'])
self.url = attributes['url']
self.title = attributes['title']
if attrib... | def refresh(self) | Refetch instance data from the API. | 3.259567 | 3.146265 | 1.036012 |
'''
Fetch all guides.
:param iterable guideids: Only return Guides corresponding to these ids.
:param string filter: Only return guides of this type. Choices:
installation, repair, disassembly, teardown,
technique, maintenance.
... | def all(guideids=None, filter=None, order=None) | Fetch all guides.
:param iterable guideids: Only return Guides corresponding to these ids.
:param string filter: Only return guides of this type. Choices:
installation, repair, disassembly, teardown,
technique, maintenance.
:param string ... | 3.980551 | 2.203179 | 1.80673 |
if self.connected:
return
pk = self._pk
if self.exists(pk=pk):
self._connected = True
else:
self._pk = None
self._connected = False
raise DoesNotExist("No %s found with pk %s" % (self.__class__.__name__, pk)) | def connect(self) | Connect the instance to redis by checking the existence of its primary
key. Do nothing if already connected. | 4.370242 | 3.598869 | 1.214338 |
instance = cls()
instance._pk = instance.pk.normalize(pk)
instance._connected = False
return instance | def lazy_connect(cls, pk) | Create an object, setting its primary key without testing it. So the
instance is not connected | 8.284982 | 8.662557 | 0.956413 |
if not cls.has_field(field_name):
raise AttributeError('"%s" is not a field for the model "%s"' %
(field_name, cls.__name__))
field = getattr(cls, '_redis_attr_%s' % field_name)
return field | def get_class_field(cls, field_name) | Return the field object with the given name (for the class, the fields
are in the "_redis_attr_%s" form) | 4.008216 | 2.610851 | 1.535214 |
if not self.has_field(field_name):
raise AttributeError('"%s" is not a field for the model "%s"' %
(field_name, self.__class__.__name__))
field = getattr(self, field_name)
return field | def get_instance_field(self, field_name) | Return the field object with the given name (works for a bound instance) | 3.001195 | 2.869848 | 1.045768 |
if self._pk:
raise ImplementationError('Something wrong happened, the PK was already set !')
self._pk = value
self._connected = True
# Default must be set only at first initialization
self._set_defaults() | def _set_pk(self, value) | Use the given value as the instance's primary key, if it doesn't have
one yet (it must be used only for new instances). Then save default values. | 12.549543 | 9.920177 | 1.265052 |
for field_name in self._fields:
if field_name in self._init_fields:
continue
field = self.get_field(field_name)
if hasattr(field, "default"):
field.proxy_set(field.default) | def _set_defaults(self) | Set default values to fields. We assume that they are not yet populated
as this method is called just after creation of a new pk. | 4.028964 | 3.217151 | 1.252339 |
if not kwargs:
raise ValueError(u"`Exists` method requires at least one kwarg.")
# special case to check for a simple pk
if len(kwargs) == 1 and cls._field_is_pk(list(kwargs.keys())[0]):
return cls.get_field('pk').exists(list(kwargs.values())[0])
# get ... | def exists(cls, **kwargs) | A model with the values defined by kwargs exists in db?
`kwargs` are mandatory. | 6.585454 | 6.161566 | 1.068796 |
if len(args) == 1: # Guess it's a pk
pk = args[0]
elif kwargs:
# special case to check for a simple pk
if len(kwargs) == 1 and cls._field_is_pk(list(kwargs.keys())[0]):
pk = list(kwargs.values())[0]
else: # case with many filters... | def get(cls, *args, **kwargs) | Retrieve one instance from db according to given kwargs.
Optionnaly, one arg could be used to retrieve it from pk. | 3.853306 | 3.740091 | 1.030271 |
try:
inst = cls.get(**kwargs)
created = False
except DoesNotExist:
inst = cls(**kwargs)
created = True
except Exception:
raise
return inst, created | def get_or_connect(cls, **kwargs) | Try to retrieve an object in db, and create it if it does not exist. | 3.489985 | 2.896379 | 1.204947 |
if args and not any(arg in self._instancehash_fields for arg in args):
raise ValueError("Only InstanceHashField can be used here.")
return self._call_command('hmget', args) | def hmget(self, *args) | This command on the model allow getting many instancehash fields with only
one redis call. You must pass hash name to retrieve as arguments. | 11.316744 | 7.029631 | 1.609863 |
if kwargs and not any(kwarg in self._instancehash_fields for kwarg in iterkeys(kwargs)):
raise ValueError("Only InstanceHashField can be used here.")
indexed = []
# main try block to revert indexes if something fail
try:
# Set indexes for indexable fie... | def hmset(self, **kwargs) | This command on the model allow setting many instancehash fields with only
one redis call. You must pass kwargs with field names as keys, with
their value. | 7.46317 | 6.298343 | 1.184942 |
if args and not any(arg in self._instancehash_fields for arg in args):
raise ValueError("Only InstanceHashField can be used here.")
# Set indexes for indexable fields.
for field_name in args:
field = self.get_field(field_name)
if field.indexable:
... | def hdel(self, *args) | This command on the model allow deleting many instancehash fields with
only one redis call. You must pass hash names to retrieve as arguments | 7.251143 | 5.746013 | 1.261943 |
# Delete each field
for field_name in self._fields:
field = self.get_field(field_name)
if not isinstance(field, PKField):
# pk has no stored key
field.delete()
# Remove the pk from the model collection
self.connection.srem(... | def delete(self) | Delete the instance from redis storage. | 6.702046 | 6.32975 | 1.058817 |
if not hasattr(threadlocal, 'limpyd_locked_fields'):
threadlocal.limpyd_locked_fields = {}
if cls._name not in threadlocal.limpyd_locked_fields:
threadlocal.limpyd_locked_fields[cls._name] = set()
return threadlocal.limpyd_locked_fields[cls._name] | def _thread_lock_storage(cls) | We mark each locked field in a thread, to allow other operations in the
same thread on the same field (for the same instance or others). This
way, operations within the lock, in the same thread, can bypass it (the
whole set of operations must be locked) | 2.584476 | 2.32634 | 1.110962 |
pattern = self.make_key(
self._name,
self.pk.get(),
'*'
)
return self.database.scan_keys(pattern, count) | def scan_keys(self, count=None) | Iter on all the key related to the current instance fields, using redis SCAN command
Parameters
----------
count: int, default to None (redis uses 10)
Hint for redis about the number of expected result
Yields
-------
str
All keys found by the sca... | 10.746408 | 15.229451 | 0.705633 |
pattern = cls.make_key(
cls._name,
"*",
)
return cls.database.scan_keys(pattern, count) | def scan_model_keys(cls, count=None) | Iter on all the key related to the current model, using redis SCAN command
Parameters
----------
count: int, default to None (redis uses 10)
Hint for redis about the number of expected result
Yields
-------
str
All keys found by the scan, one by ... | 11.745924 | 18.746599 | 0.626563 |
try:
if isinstance(model, str):
app_label, model_name = model.split('.', 1)
m = loading.get_model(app_label, model_name)
if not m: # pragma: no cover
raise LookupError() # Django < 1.7 just returns None
return m
elif issubclass(m... | def get_model(model) | Given a model name as ``app_label.ModelName``, returns the Django model. | 3.299011 | 2.92756 | 1.126881 |
if from_obj:
from_ctype = ContentType.objects.get_for_model(from_obj)
assert from_ctype.natural_key() == self.from_content_type.natural_key(), (
'Relationship "%s" does not support connections '
'from "%s" types' % (self.name, from_ctype))
... | def _validate_ctypes(self, from_obj, to_obj) | Asserts that the content types for the given object are valid for this
relationship. If validation fails, ``AssertionError`` will be raised. | 2.154223 | 1.941484 | 1.109575 |
self._validate_ctypes(from_obj, to_obj)
return Connection.objects.get_or_create(relationship_name=self.name,
from_pk=from_obj.pk, to_pk=to_obj.pk)[0] | def create_connection(self, from_obj, to_obj) | Creates and returns a connection between the given objects. If a
connection already exists, that connection will be returned instead. | 4.494476 | 4.090117 | 1.098863 |
self._validate_ctypes(from_obj, to_obj)
try:
return self.connections.get(from_pk=from_obj.pk, to_pk=to_obj.pk)
except Connection.DoesNotExist:
return None | def get_connection(self, from_obj, to_obj) | Returns a ``Connection`` instance for the given objects or ``None`` if
there's no connection. | 3.401426 | 3.18277 | 1.0687 |
self._validate_ctypes(from_obj, to_obj)
return self.connections.filter(from_pk=from_obj.pk, to_pk=to_obj.pk).exists() | def connection_exists(self, from_obj, to_obj) | Returns ``True`` if a connection between the given objects exists,
else ``False``. | 4.100459 | 4.177466 | 0.981566 |
self._validate_ctypes(from_obj, None)
return self.connections.filter(from_pk=from_obj.pk) | def connections_from_object(self, from_obj) | Returns a ``Connection`` query set matching all connections with
the given object as a source. | 9.386559 | 7.189157 | 1.305655 |
self._validate_ctypes(None, to_obj)
return self.connections.filter(to_pk=to_obj.pk) | def connections_to_object(self, to_obj) | Returns a ``Connection`` query set matching all connections with
the given object as a destination. | 10.445332 | 7.445765 | 1.402855 |
return self.to_content_type.get_all_objects_for_this_type(pk__in=self.connected_object_ids(from_obj)) | def connected_objects(self, from_obj) | Returns a query set matching all connected objects with the given
object as a source. | 7.873751 | 5.850148 | 1.345906 |
return self.from_content_type.get_all_objects_for_this_type(pk__in=self.connected_to_object_ids(to_obj)) | def connected_to_objects(self, to_obj) | Returns a query set matching all connected objects with the given
object as a destination. | 7.28969 | 5.62193 | 1.296652 |
self._validate_ctypes(from_obj, to_obj)
if from_obj == to_obj:
return 0
d = 1
pk = to_obj.pk
qs = self.connections
pks = qs.filter(from_pk=from_obj.pk).values_list('to_pk', flat=True)
while limit > 0:
if pk in pks... | def distance_between(self, from_obj, to_obj, limit=2) | Calculates the distance between two objects. Distance 0 means
``from_obj`` and ``to_obj`` are the same objects, 1 means ``from_obj``
has a direct connection to ``to_obj``, 2 means that one or more of
``from_obj``'s connected objects are directly connected to ``to_obj``,
etc.
... | 3.094749 | 2.849155 | 1.086199 |
if len(scans):
scanstr = string.join([str(ss) for ss in sorted(scans)], ',')
else:
scanstr = self.allstr
print 'Splitting out all cal scans (%s) with 1s int time' % scanstr
newname = ps.sdm2ms(self.sdmfile, self.sdmfile.rstrip('/')+'.ms', scanstr, intti... | def genms(self, scans=[]) | Generate an MS that contains all calibrator scans with 1 s integration time. | 12.3746 | 9.012242 | 1.373088 |
knowncals = ['3C286', '3C48', '3C147', '3C138']
# find scans with knowncals in the name
sourcenames = [self.sources[source]['source'] for source in self.sources]
calsources = [cal for src in sourcenames for cal in knowncals if cal in src]
calsources_full = [src for src... | def set_fluxinfo(self) | Uses list of known flux calibrators (with models in CASA) to find full name given in scan. | 4.261113 | 3.965054 | 1.074667 |
if not flagfile:
# write flag data to text file
flagfile = os.path.join(self.workdir, 'flags.txt')
print 'Writing flaglist to %s.' % flagfile
if not flaglist:
flaglist = ["mode='unflag'", "mode='shadow'", "mode='clip' clipzeros=True",
... | def flagdata(self, msfile, flagfile='', flaglist=[]) | Use flagfile (first) or flaglist (alternately) to run CASA flagging tool. | 7.391204 | 6.980172 | 1.058886 |
for emoticon, emoticon_html in EMOTICONS_COMPILED:
if emoticon.search(content):
content = emoticon.sub(emoticon_html, content)
return content | def regexp_replace_emoticons(content) | Replace the emoticons string by HTML images,
with regular expressions. | 2.872583 | 3.053309 | 0.94081 |
if not excluded_markups:
return regexp_replace_emoticons(content)
excluded_markups = excluded_markups.split(',') + ['[document]']
soup = BeautifulSoup(content, 'html.parser')
for content_string in list(soup.strings):
if content_string.parent.name not in excluded_markups:
... | def replace_emoticons(content, excluded_markups) | Replace the emoticons string by HTML images.
If some markups should be excluded from replacement,
BeautifulSoup will be used. | 2.433194 | 2.423449 | 1.004021 |
exclude = ''
args = token.split_contents()
if len(args) == 2:
exclude = args[1]
elif len(args) > 2:
raise template.TemplateSyntaxError(
'emoticons tag has only one optional argument')
nodelist = parser.parse(['endemoticons'])
parser.delete_first_token()
retu... | def emoticons_tag(parser, token) | Tag for rendering emoticons. | 2.684618 | 2.622541 | 1.02367 |
esc = autoescape and conditional_escape or (lambda x: x)
content = mark_safe(replace_emoticons(esc(content), exclude))
return content | def emoticons_filter(content, exclude='', autoescape=None) | Filter for rendering emoticons. | 3.589958 | 4.0394 | 0.888735 |
# initialize hidden state directory
objloc = '{0}/{1}'.format(self.statedir, label)
with open(objloc, 'w') as fp:
if format == 'pickle':
pickle.dump(obj, fp)
elif format == 'text':
fp.write(str(obj))
else:
... | def save(self, obj, label, format='text') | Save or update obj as pkl file with name label
format can be 'text' or 'pickle'. | 3.857177 | 3.623823 | 1.064395 |
objloc = '{0}/{1}'.format(self.statedir, label)
try:
obj = pickle.load(open(objloc, 'r'))
except (KeyError, IndexError, EOFError):
obj = open(objloc, 'r').read()
try:
obj = float(obj)
except ValueError:
p... | def load(self, label) | Load obj with give label from hidden state directory | 4.210795 | 3.642784 | 1.155928 |
obj = self.load(label)
if obj == None:
obj=default
self.save(obj, label) # initialize with default
textw = Text(value=obj, description=description)
hndl = interact(self.save, obj=textw, label=fixed(label), format=fixed(format)) | def setText(self, label, default='', description='Set Text', format='text') | Set text in a notebook pipeline (via interaction or with nbconvert) | 6.428242 | 6.009054 | 1.069759 |
obj = self.load(label)
if obj == None:
obj=default
self.save(obj, label) # initialize with default
floatw = FloatSlider(value=obj, min=min, max=max, description=description)
hndl = interact(self.save, obj=floatw, label=fixed(label), format=fixed(format... | def setFloat(self, label, default=0, min=-20, max=20, description='Set Float', format='text') | Set float in a notebook pipeline (via interaction or with nbconvert) | 4.958808 | 4.768738 | 1.039858 |
obj = self.load(label)
if obj == None:
obj=default
self.save(obj, label) # initialize with default
dropdownw = Dropdown(value=obj, options=options, description=description)
hndl = interact(self.save, obj=dropdownw, label=fixed(label), format=fixed(form... | def setDropdown(self, label, default=None, options=[], description='Set Dropdown', format='text') | Set float in a notebook pipeline (via interaction or with nbconvert) | 5.797912 | 5.640849 | 1.027844 |
nint, nbl, nchan, npol = data.shape
niters = int(np.log2(nchan))
assert nchan in 2**np.arange(30) and nint in 2**np.arange(30), "Input dimensions must be a power of 2"
logger.info('Input data dimensions: {0}'.format(data.shape))
data = FDMT_initialization(data, f_min, f_max, maxDT, dataType)... | def FDMT(data, f_min, f_max, maxDT, dataType) | This function implements the FDMT algorithm.
Input: Input visibility array (nints, nbl, nchan, npol)
f_min,f_max are the base-band begin and end frequencies.
The frequencies should be entered in MHz
maxDT - the maximal delay (in time bins) of the maximal dispersion.
... | 4.16884 | 3.841399 | 1.08524 |
maxDM = inttime*maxDT/(4.1488e-3 * (1/f_min**2 - 1/f_max**2))
logger.info('Freqs from {0}-{1}, MaxDT {2}, Int time {3} => maxDM {4}'.format(f_min, f_max, maxDT, inttime, maxDM)) | def FDMT_params(f_min, f_max, maxDT, inttime) | Summarize DM grid and other parameters. | 5.3839 | 5.143532 | 1.046732 |
# maxDT = dmtodt(dm) # need to write
if it>0:
correction = dF/2.
else:
correction = 0
shift = []
nchan = nchan0/2**(iteration_num)
for i_F in range(nchan):
f_start = (f_max - f_min)/float(nchan) * (i_F) + f_min
f_end = (f_max - f_min)/float(nchan) *(i_F+1) ... | def dmtoind(dm, f_min, f_max, nchan0, inttime, it) | Given FDMT state, return indices to slice partial FDMT solution and sump to a given DM | 3.277297 | 3.349857 | 0.978339 |
# Data initialization is done prior to the first FDMT iteration
# See Equations 17 and 19 in Zackay & Ofek (2014)
[nint, nbl, nchan, npol] = datain.shape
deltaF = (f_max - f_min)/float(nchan)
deltaT = int(np.ceil((maxDT-1) *(1./f_min**2 - 1./(f_min + deltaF)**2) / (1./f_min**2 - 1./f_max**2))... | def FDMT_initialization(datain, f_min, f_max, maxDT, dataType) | Input: datain - visibilities of (nint, nbl, nchan, npol)
f_min,f_max - are the base-band begin and end frequencies.
The frequencies can be entered in both MHz and GHz, units are factored out in all uses.
maxDT - the maximal delay (in time bins) of the maximal dispersion.
Appears ... | 3.894119 | 2.991453 | 1.301748 |
while 1:
key = str(uuid.uuid4().hex)
if not connection.exists(key):
break
return key | def unique_key(connection) | Generate a unique keyname that does not exists is the connection
keyspace. | 3.323201 | 3.914314 | 0.848987 |
if value and isinstance(value, bytes):
value = value.decode('utf-8')
return value | def normalize(value) | Simple method to always have the same kind of value | 3.605304 | 3.714373 | 0.970636 |
try:
if self._accept_selector.select(timeout=self.block_time):
client = self._server_socket.accept()
logging.info('Client connected: {}'.format(client[1]))
self._threads_limiter.start_thread(target=self._subthread_handle_accepted,
... | def _mainthread_accept_clients(self) | Accepts new clients and sends them to the to _handle_accepted within a subthread | 6.042751 | 5.209223 | 1.16001 |
events = self._recv_selector.select(self.block_time)
for key, mask in events:
if mask == selectors.EVENT_READ:
self._recv_selector.unregister(key.fileobj)
self._threads_limiter.start_thread(target=self._subthread_handle_readable,
... | def _mainthread_poll_readable(self) | Searches for readable client sockets. These sockets are then put in a subthread
to be handled by _handle_readable | 5.435061 | 5.002148 | 1.086545 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.