code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if payload.get('service') == SERVICE_UDP:
self.gateway = Gateway(addr[0], payload['port'], header.gateway)
self.gateway_found_event.set() | def _on_gateway(self, header, payload, rest, addr) | Records a discovered gateway, for connecting to later. | 8.207187 | 6.580413 | 1.247215 |
with self.lock:
self.power_state[header.mac] = payload
if len(self.power_state) >= self.num_bulbs:
self.power_state_event.set()
self.callbacks.put(EVENT_POWER_STATE, self.get_bulb(header.mac),
is_on=bool(payload['is_on'])) | def _on_power_state(self, header, payload, rest, addr) | Records the power (on/off) state of bulbs, and forwards to a high-level
callback with human-friendlier arguments. | 5.118139 | 4.586911 | 1.115814 |
with self.lock:
label = payload['label'].strip('\x00')
self.bulbs[header.mac] = bulb = Bulb(label, header.mac)
if len(self.bulbs) >= self.num_bulbs:
self.bulbs_found_event.set()
self.light_state[header.mac] = payload
if len(se... | def _on_light_state(self, header, payload, rest, addr) | Records the light state of bulbs, and forwards to a high-level callback
with human-friendlier arguments. | 3.34468 | 3.24234 | 1.031564 |
return self.bulbs.get(mac, Bulb('Bulb %s' % _bytes(mac), mac)) | def get_bulb(self, mac) | Returns a Bulb object corresponding to the bulb with the mac address
`mac` (a 6-byte bytestring). | 7.427835 | 8.56317 | 0.867417 |
packet = build_packet(packet_type, self.gateway.mac, bulb,
packet_fmt, *packet_args)
self.logger('>> %s', _bytes(packet))
self.sender.put(packet) | def send(self, packet_type, bulb, packet_fmt, *packet_args) | Builds and sends a packet to one or more bulbs. | 5.505212 | 5.497887 | 1.001332 |
with _blocking(self.lock, self.power_state, self.light_state_event,
timeout):
self.send(REQ_SET_POWER_STATE,
bulb, '2s', '\x00\x01' if is_on else '\x00\x00')
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
return self.power_stat... | def set_power_state(self, is_on, bulb=ALL_BULBS, timeout=None) | Sets the power state of one or more bulbs. | 5.207859 | 5.142056 | 1.012797 |
with _blocking(self.lock, self.light_state, self.light_state_event,
timeout):
self.send(REQ_SET_LIGHT_STATE, bulb, 'xHHHHI',
hue, saturation, brightness, kelvin, 0)
self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '')
return self.lig... | def set_light_state_raw(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None) | Sets the (low-level) light state of one or more bulbs. | 4.713141 | 4.916193 | 0.958697 |
raw_hue = int((hue % 360) / 360.0 * 0xffff) & 0xffff
raw_sat = int(saturation * 0xffff) & 0xffff
raw_bright = int(brightness * 0xffff) & 0xffff
return self.set_light_state_raw(raw_hue, raw_sat, raw_bright, kelvin,
bulb, timeout) | def set_light_state(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None) | Sets the light state of one or more bulbs.
Hue is a float from 0 to 360, saturation and brightness are floats from
0 to 1, and kelvin is an integer. | 2.006056 | 2.097308 | 0.956491 |
def _wrapper(fn):
return self.callbacks.register(packet_type, fn)
return _wrapper | def on_packet(self, packet_type) | Registers a function to be called when packet data is received with a
specific type. | 6.850461 | 7.470604 | 0.916989 |
# Broadcast discovery packets until we find a gateway.
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
with closing(sock):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
discover_packet = build_packet(REQ_GATEWAY,
... | def connect(self, attempts=20, delay=0.5) | Connects to a gateway, blocking until a connection is made and bulbs
are found.
Step 1: send a gateway discovery packet to the broadcast address, wait
until we've received some info about the gateway.
Step 2: connect to a discovered gateway, wait until the connection has
been c... | 3.945736 | 3.512514 | 1.123337 |
listener_thr = _spawn(self.receiver.run)
callback_thr = _spawn(self.callbacks.run)
sender_thr = _spawn(self.sender.run)
logger_thr = _spawn(self.logger.run)
self.connect()
try:
yield
finally:
self.stop()
# Wait for th... | def run(self) | A context manager starting up threads to send and receive data from a
gateway and handle callbacks. Yields when a connection has been made,
and cleans up connections and threads when it's done. | 3.56328 | 3.339167 | 1.067116 |
'''
Enqueues in succession all conversions steps necessary to take the
given URL and convert it to to_type, storing the result in the cache
'''
async def enq_convert(*args):
await self.enqueue(Task.CONVERT, args)
await tasks.multiconvert(url_string, to_type, e... | async def run_multiconvert(self, url_string, to_type) | Enqueues in succession all conversions steps necessary to take the
given URL and convert it to to_type, storing the result in the cache | 10.193254 | 3.630709 | 2.807511 |
for line in lines:
if is_empty(line):
continue
tokens = line.strip().split('\t')
distance_str = tokens.pop(0)
if distance_str.lstrip().lower().startswith('u'):
distance = 0.0
elif distance_str == '0.0':
distance = float(precision)
... | def parse_otu_list(lines, precision=0.0049) | Parser for mothur *.list file
To ensure all distances are of type float, the parser returns a
distance of 0.0 for the unique groups. However, if some sequences
are very similar, mothur may return a grouping at zero distance.
What Mothur really means by this, however, is that the clustering
is at t... | 3.064144 | 2.628272 | 1.16584 |
if tmp_dir is None:
tmp_dir = gettempdir()
ref_seq_ids = set()
user_ref_file = open(ref_fp)
tmp_ref_file = NamedTemporaryFile(dir=tmp_dir, suffix=".ref.fa")
for seq_id, seq in parse_fasta(user_ref_file):
id_token = seq_id.split()[0]
ref_seq_ids.add(id_token)
tm... | def mothur_classify_file(
query_file, ref_fp, tax_fp, cutoff=None, iters=None, ksize=None,
output_fp=None, tmp_dir=None) | Classify a set of sequences using Mothur's naive bayes method
Dashes are used in Mothur to provide multiple filenames. A
filepath with a dash typically breaks an otherwise valid command
in Mothur. This wrapper script makes a copy of both files, ref_fp
and tax_fp, to ensure that the path has no dashes... | 2.619812 | 2.603873 | 1.006121 |
def format_opts(*opts):
return ', '.join(filter(None, map(str, opts)))
vars = {
'in': self._input_filename,
'unique': self._derive_unique_path(),
'dist': self._derive_dist_path(),
'names': self._derive_names_path(),
... | def _compile_mothur_script(self) | Returns a Mothur batch script as a string | 5.093804 | 5.116243 | 0.995614 |
filenames = listdir(self.WorkingDir)
lognames = [
x for x in filenames if re.match(
"^mothur\.\d+\.logfile$",
x)]
if not lognames:
raise ApplicationError(
'No log file detected in directory %s. Contents: \n\t%s' % (... | def _derive_log_path(self) | Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the l... | 4.910095 | 3.999576 | 1.227654 |
base, ext = path.splitext(self._input_filename)
return '%s.unique%s' % (base, ext) | def _derive_unique_path(self) | Guess unique sequences path produced by Mothur | 5.737016 | 4.384419 | 1.308501 |
abbrevs = {
'furthest': 'fn',
'nearest': 'nn',
'average': 'an',
}
if self.Parameters['method'].isOn():
method = self.Parameters['method'].Value
else:
method = self.Parameters['method'].Default
return abbrevs[met... | def __get_method_abbrev(self) | Abbreviated form of clustering method parameter.
Used to guess output filenames for MOTHUR. | 4.333532 | 4.307888 | 1.005953 |
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.list' % (base, self.__get_method_abbrev()) | def _derive_list_path(self) | Guess otu list file path produced by Mothur | 10.470702 | 7.751177 | 1.350853 |
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.rabund' % (base, self.__get_method_abbrev()) | def _derive_rank_abundance_path(self) | Guess rank abundance file path produced by Mothur | 11.109782 | 9.92012 | 1.119924 |
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.sabund' % (base, self.__get_method_abbrev()) | def _derive_species_abundance_path(self) | Guess species abundance file path produced by Mothur | 13.335928 | 11.755816 | 1.134411 |
# Override to change default constructor to str(). FilePath
# objects muck up the Mothur script.
return super(Mothur, self).getTmpFilename(
tmp_dir=tmp_dir, prefix=prefix, suffix=suffix,
result_constructor=str) | def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt') | Returns a temporary filename
Similar interface to tempfile.mktmp() | 14.410304 | 13.959406 | 1.032301 |
self._input_filename = self.getTmpFilename(
self.WorkingDir, suffix='.fasta')
with open(self._input_filename, 'w') as f:
f.write(data)
return self._input_filename | def _input_as_multiline_string(self, data) | Write multiline string to temp file, return filename
data: a multiline string to be written to a file. | 4.875425 | 3.964043 | 1.229912 |
self._input_filename = self.getTmpFilename(
self.WorkingDir, suffix='.fasta')
with open(self._input_filename, 'w') as f:
# Use lazy iteration instead of list comprehension to
# prevent reading entire file into memory
for line in data:
... | def _input_as_lines(self, data) | Write sequence of lines to temp file, return filename
data: a sequence to be written to a file, each element of the
sequence will compose a line in the file
* Note: '\n' will be stripped off the end of each sequence
element before writing to a file in order to avoid
... | 5.007509 | 4.332345 | 1.155843 |
self._input_filename = self.getTmpFilename(
self.WorkingDir, suffix='.fasta')
copyfile(data, self._input_filename)
return self._input_filename | def _input_as_path(self, data) | Copys the provided file to WorkingDir and returns the new filename
data: path or filename | 8.024649 | 5.710044 | 1.405357 |
self._curr_working_dir = path
try:
mkdir(self.WorkingDir)
except OSError:
# Directory already exists
pass | def _set_WorkingDir(self, path) | Sets the working directory | 5.149983 | 5.541704 | 0.929314 |
params = [self.Parameters[x] for x in opts]
return ', '.join(filter(None, map(str, params))) | def _format_function_arguments(self, opts) | Format a series of function arguments in a Mothur script. | 6.597303 | 5.642703 | 1.169174 |
fasta = self._input_filename
required_params = ["reference", "taxonomy"]
for p in required_params:
if self.Parameters[p].Value is None:
raise ValueError("Must provide value for parameter %s" % p)
optional_params = ["ksize", "cutoff", "iters"]
... | def _compile_mothur_script(self) | Returns a Mothur batch script as a string | 6.894916 | 6.567194 | 1.049903 |
'''
Force adds a `Parameter` object to the instance.
'''
if isinstance(parameter, MethodParameter):
# create a bound instance of the MethodParameter
parameter = parameter.bind(alloy=self)
self._parameters[parameter.name] = parameter
for alias in pa... | def _add_parameter(self, parameter) | Force adds a `Parameter` object to the instance. | 6.290174 | 4.533354 | 1.387532 |
'''
Adds a `Parameter` object to the instance.
If a `Parameter` with the same name or alias has already been added
and `overload` is False (the default), a `ValueError` is thrown.
If a class member or method with the same name or alias is already
defined... | def add_parameter(self, parameter, overload=False) | Adds a `Parameter` object to the instance.
If a `Parameter` with the same name or alias has already been added
and `overload` is False (the default), a `ValueError` is thrown.
If a class member or method with the same name or alias is already
defined, a `ValueError` is ... | 2.417957 | 1.684069 | 1.435783 |
'''
Returns the named parameter if present, or the value of `default`,
otherwise.
'''
if hasattr(self, name):
item = getattr(self, name)
if isinstance(item, Parameter):
return item
return default | def get_parameter(self, name, default=None) | Returns the named parameter if present, or the value of `default`,
otherwise. | 4.334671 | 2.730264 | 1.587638 |
'''
Returns a list of the unique parameters (no duplicates).
'''
# start with parameters in the `_parameters` dictionary
parameters = self._parameters.values()
# add parameters defined with the class
for name in dir(self):
item = getattr(self, name)
... | def get_unique_parameters(self) | Returns a list of the unique parameters (no duplicates). | 4.168181 | 3.470896 | 1.200895 |
if level == 'info':
to_set = logging.INFO
if level == 'debug':
to_set = logging.DEBUG
if level == 'error':
to_set = logging.ERROR
self.log.setLevel(to_set) | def set_log_level(self, level: str) -> None | Override the default log level of the class. | 2.622119 | 2.205897 | 1.188686 |
if not urls:
raise Exception("No results were found")
session: FuturesSession = FuturesSession(max_workers=len(urls))
self.log.info("Bulk requesting: %d" % len(urls))
futures = [session.get(u, headers=gen_headers(), timeout=3) for u in urls]
done, incomplete ... | def _request_bulk(self, urls: List[str]) -> List | Batch the requests going out. | 3.702655 | 3.537564 | 1.046668 |
'''
Shallow copies this MethodParameter, and binds it to an alloy.
This is required before calling.
'''
param = MethodParameter(self.name, self.method, self.dependencies,
self.units, self.aliases, self._references)
param.alloy = alloy
... | def bind(self, alloy) | Shallow copies this MethodParameter, and binds it to an alloy.
This is required before calling. | 9.787665 | 3.516137 | 2.783642 |
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=mol... | def align_unaligned_seqs(seqs,moltype=DNA,params=None,accurate=False) | Aligns unaligned sequences
seqs: either list of sequence objects or list of strings
add_seq_names: boolean. if True, sequence names are inserted in the list
of sequences. if False, it assumes seqs is a list of lines of some
proper format that the program can handle | 5.334424 | 5.469591 | 0.975288 |
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
seq_int_map, seq_int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
seq_int_map = SequenceCollection(seq_int... | def add_seqs_to_alignment(seqs, aln, moltype, params=None, accurate=False) | Returns an Alignment object from seqs and existing Alignment.
seqs: a cogent.core.sequence.Sequence object, or data that can be used
to build one.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one
params: dict of parameters to pass in to the Mafft app controlle... | 4.048668 | 3.920339 | 1.032734 |
#create SequenceCollection object from seqs
aln1 = Alignment(aln1,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln1_int_map, aln1_int_keys = aln1.getIntMap()
#Create SequenceCollection from int_map.
aln1_int_map = Alignment(aln1_int_map,MolType=moltype)
#create... | def align_two_alignments(aln1, aln2, moltype, params=None) | Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
- Mafft profile alignment only works with aligned sequences. Alignment
object used to handle unaligned sequences.
params: dict of parameter... | 3.436646 | 3.320304 | 1.03504 |
# Build headers
headers = {}
if not postParameters:
postParameters = {}
for key, value in extraHeaders.iteritems():
# Fixes #197 for values with utf-8 chars to be passed into plugit
if isinstance(value, basestring):
headers[... | def doQuery(self, url, method='GET', getParmeters=None, postParameters=None, files=None, extraHeaders={}, session={}) | Send a request to the server and return the result | 3.003546 | 3.028978 | 0.991604 |
randomToken = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(32))
r = self.doQuery('ping?data=' + randomToken)
if r.status_code == 200: # Query ok ?
if r.json()['data'] == randomToken: # Token equal ?
... | def ping(self) | Return true if the server successfully pinged | 4.401617 | 4.228857 | 1.040853 |
r = self.doQuery('version')
if r.status_code == 200: # Query ok ?
data = r.json()
if data['result'] == 'Ok' and data['version'] == self.PI_API_VERSION and data['protocol'] == self.PI_API_NAME:
return True
return False | def checkVersion(self) | Check if the server use the same version of our protocol | 5.228641 | 4.683776 | 1.11633 |
r = self.doQuery('mail', method='POST', postParameters={'response_id': str(data), 'message': str(message)})
if r.status_code == 200: # Query ok ?
data = r.json()
return data['result'] == 'Ok'
return False | def newMail(self, data, message) | Send a mail to a plugit server | 7.615722 | 7.153298 | 1.064645 |
r = self.doQuery('media/' + uri)
if r.status_code == 200:
content_type = 'application/octet-stream'
if 'content-type' in r.headers:
content_type = r.headers['content-type']
cache_control = None
if 'cache-control' in r.headers:... | def getMedia(self, uri) | Return a tuple with a media and his content-type. Don't cache anything ! | 2.131315 | 1.965281 | 1.084484 |
action = urlparse(uri).path
mediaKey = self.cacheKey + '_meta_' + action
mediaKey = mediaKey.replace(' ', '__')
meta = cache.get(mediaKey, None)
# Nothing found -> Retrieve it from the server and cache it
if not meta:
r = self.doQuery('meta/' + u... | def getMeta(self, uri) | Return meta information about an action. Cache the result as specified by the server | 6.072987 | 5.828499 | 1.041947 |
if not meta:
metaKey = self.cacheKey + '_templatesmeta_cache_' + uri
meta = cache.get(metaKey, None)
if not meta:
meta = self.getMeta(uri)
cache.set(metaKey, meta, 15)
if not meta: # No meta, can return a template
... | def getTemplate(self, uri, meta=None) | Return the template for an action. Cache the result. Can use an optional meta parameter with meta information | 4.867757 | 4.672155 | 1.041866 |
#
# collect unique instrument set / deltas combinations
#
delta_sets = {}
for vect in offsetvectors:
for instruments in iterutils.choices(sorted(vect), n):
# NOTE: the arithmetic used to construct the
# offsets *must* match the arithmetic used by
# offsetvector.deltas so that the results of the
#... | def component_offsetvectors(offsetvectors, n) | Given an iterable of offset vectors, return the shortest list of
the unique n-instrument offset vectors from which all the vectors
in the input iterable can be constructed. This can be used to
determine the minimal set of n-instrument coincs required to
construct all of the coincs for all of the requested instrume... | 6.849922 | 5.994821 | 1.14264 |
# FIXME: instead of raising ValueError when the
# offsetvector is empty this should return an empty
# dictionary. the inverse, .fromdeltas() accepts
# empty dictionaries
# NOTE: the arithmetic used to construct the offsets
# *must* match the arithmetic used by
# time_slide_component_vectors() so tha... | def deltas(self) | Dictionary of relative offsets. The keys in the result are
pairs of keys from the offset vector, (a, b), and the
values are the relative offsets, (offset[b] - offset[a]).
Raises ValueError if the offsetvector is empty (WARNING:
this behaviour might change in the future).
Example:
>>> x = offsetvector({"H... | 11.771601 | 8.501474 | 1.384654 |
return offsetvector((key, offset) for key, offset in self.items() if key in other).deltas == other.deltas | def contains(self, other) | Returns True if offset vector @other can be found in @self,
False otherwise. An offset vector is "found in" another
offset vector if the latter contains all of the former's
instruments and the relative offsets among those
instruments are equal (the absolute offsets need not be).
Example:
>>> a = offsetve... | 13.837147 | 14.43901 | 0.958317 |
# FIXME: should it be performed in place? if it should
# be, the should there be no return value?
for key, offset in sorted(kwargs.items()):
if key in self:
delta = offset - self[key]
for key in self.keys():
self[key] += delta
break
return self | def normalize(self, **kwargs) | Adjust the offsetvector so that a particular instrument has
the desired offset. All other instruments have their
offsets adjusted so that the relative offsets are
preserved. The instrument to noramlize, and the offset one
wishes it to have, are provided as a key-word argument.
The return value is the time s... | 6.462288 | 6.12477 | 1.055107 |
return cls((key, value) for (refkey, key), value in deltas.items()) | def fromdeltas(cls, deltas) | Construct an offsetvector from a dictionary of offset
deltas as returned by the .deltas attribute.
Example:
>>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20})
>>> y = offsetvector.fromdeltas(x.deltas)
>>> y
offsetvector({'V1': 20, 'H1': 0, 'L1': 10})
>>> y == x
True
See also .deltas, .fromkeys() | 9.42803 | 13.167713 | 0.715996 |
'''
This function returns the url of the gif searched for
with the given search parameters using the Giphy API.
Thanks!
Fails gracefully when it can't find a gif by returning an
appropriate image url with the failure message on it.
'''
# Sanitizing searchStr
# TODO: Find a bet... | def processGif(searchStr) | This function returns the url of the gif searched for
with the given search parameters using the Giphy API.
Thanks!
Fails gracefully when it can't find a gif by returning an
appropriate image url with the failure message on it. | 3.765507 | 2.523038 | 1.492449 |
self.reset_purified()
HTMLParser.feed(self, data)
return self.html() | def feed(self, data) | Main method for purifying HTML (overrided) | 16.423914 | 7.568724 | 2.169971 |
self.log.debug( u'Encountered a start tag: {0} {1}'.format(tag, attrs) )
if tag in self.sanitizelist:
self.level += 1
return
if self.isNotPurify or tag in self.whitelist_keys:
attrs = self.__attrs_str(tag, attrs)
attrs = ' ' + attrs if att... | def handle_starttag(self, tag, attrs) | Handler of starting tag processing (overrided, private) | 5.761829 | 5.698861 | 1.011049 |
self.log.debug( u'Encountered an end tag : {0}'.format(tag) )
if tag in self.sanitizelist:
self.level -= 1
return
if tag in self.unclosedTags:
return
if self.isNotPurify or tag in self.whitelist_keys:
self.data.append(u'</%s>' % ta... | def handle_endtag(self, tag) | Handler of ending tag processing (overrided, private) | 7.164746 | 6.807817 | 1.052429 |
self.log.debug( u'Encountered some data : {0}'.format(data) )
if not self.level:
self.data.append(data) | def handle_data(self, data) | Handler of processing data inside tag (overrided, private) | 8.339986 | 6.96832 | 1.196843 |
self.log.debug( u'Encountered entity : {0}'.format(name) )
if not self.removeEntity:
self.data.append('&%s;' % name) | def handle_entityref(self, name) | Handler of processing entity (overrided, private) | 8.404357 | 7.391971 | 1.136958 |
# add tag's names as key and list of enabled attributes as value for defaults
self.whitelist = {}
# tags that removed with contents
self.sanitizelist = ['script', 'style']
if isinstance(whitelist, dict) and '*' in whitelist.keys():
self.isNotPurify = True
... | def __set_whitelist(self, whitelist=None) | Update default white list by customer white list | 8.841125 | 8.740851 | 1.011472 |
enabled = self.whitelist.get(tag, ['*'])
all_attrs = '*' in enabled
items = []
for attr in attrs:
key = attr[0]
value = attr[1] or ''
if all_attrs or key in enabled:
items.append( u'%s="%s"' % (key, value,) )
return u' ... | def __attrs_str(self, tag, attrs) | Build string of attributes list for tag | 3.880174 | 3.853571 | 1.006904 |
if isinstance(val, integer_types):
hex_str = '%x' % val
if len(hex_str) % 2:
hex_str = '0' + hex_str
return hex_str
return hexlify(val) | def hex_from(val) | Returns hex string representation for a given value.
:param bytes|str|unicode|int|long val:
:rtype: bytes|str | 2.470533 | 2.714449 | 0.910142 |
if isinstance(val, integer_types):
val = int_to_bytes(val)
return b64encode(val).decode('ascii') | def b64_from(val) | Returns base64 encoded bytes for a given int/long/bytes value.
:param int|long|bytes val:
:rtype: bytes|str | 3.302966 | 3.806744 | 0.867662 |
if output_format == 'wiki':
ttx = '== '
xtt = ' =='
tx = ''
xt = ''
capx = "'''"
xcap = "'''"
rx = '|'
xr = '|'
rspx = '|<|'
xrsp = '>'
cx = '|'
xc = '|'
hlx = '['
hxl = ' '
xhl = ']'
el... | def set_output_format( output_format ) | Sets output format; returns standard bits of table. These are:
ttx: how to start a title for a set of tables
xtt: how to end a title for a set of tables
tx: how to start a table
xt: how to close a table
capx: how to start a caption for the table
xcap: how to close a capti... | 3.568457 | 2.407081 | 1.482483 |
if isinstance(val, float) and val != 0.0:
if val >= 10.**-(decimal_places - 1):
conv_str = ''.join([ '%.', str(decimal_places), 'f' ])
else:
conv_str = ''.join([ '%.', str(decimal_places), 'e' ])
val = float( conv_str % val )
return val | def smart_round( val, decimal_places = 2 ) | For floats >= 10.**-(decimal_places - 1), rounds off to the valber of decimal places specified.
For floats < 10.**-(decimal_places - 1), puts in exponential form then rounds off to the decimal
places specified.
@val: value to round; if val is not a float, just returns val
@decimal_places: number of deci... | 3.240963 | 2.909819 | 1.113802 |
if '<a href="' in str(val) and hlx != '<a href="':
val = val.replace('<a href="', hlx).replace('">', hxl, 1).replace('</a>', xhl)
return val | def format_hyperlink( val, hlx, hxl, xhl ) | Formats an html hyperlink into other forms.
@hlx, hxl, xhl: values returned by set_output_format | 4.22697 | 4.76755 | 0.886613 |
if round_floats:
val = smart_round(val, decimal_places = decimal_places)
if format_links:
val = format_hyperlink(val, hlx, hxl, xhl)
return val | def format_cell(val, round_floats = False, decimal_places = 2, format_links = False,
hlx = '', hxl = '', xhl = '') | Applys smart_round and format_hyperlink to values in a cell if desired. | 2.426253 | 1.791373 | 1.35441 |
return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) ))) | def format_header_cell(val) | Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and
all other '_' to spaces. | 8.654692 | 3.36517 | 2.571844 |
column_name_ns = re.sub(r'_time', r'_time_ns', column_name)
try:
rowattrs = [attr for attr in row.__slots__]
except AttributeError:
rowattrs = [attr for attr in row.__dict__.iterkeys()]
if cat_time_ns and "_time" in column_name and column_name_ns in rowattrs:
return int(get... | def get_row_data(row, column_name, cat_time_ns = True) | Retrieves the requested column's data from the given row.
@cat_time_ns: If the column_name has "_time" in it, will concatenate
the column with any column having the same name but "_time_ns". | 3.205002 | 3.131727 | 1.023398 |
date = branch = tag = author = committer = status = builder_name = build_date = ""
id = "1.1.0"
try:
v = gvcsi.generate_git_version_info()
id, date, branch, tag, author = v.id, v.date, b.branch, v.tag, v.author
committer, status = v.committer, v.status
# determine ... | def write_build_info() | Get VCS info from pycbc_glue/generate_vcs_info.py and add build information.
Substitute these into pycbc_glue/git_version.py.in to produce
pycbc_glue/git_version.py. | 3.035829 | 2.750252 | 1.103837 |
padding = len(int_to_bytes(self._prime))
padded = int_to_bytes(val).rjust(padding, b'\x00')
return padded | def pad(self, val) | :param val:
:rtype: bytes | 5.210856 | 4.754935 | 1.095884 |
joiner = kwargs.get('joiner', '').encode('utf-8')
as_bytes = kwargs.get('as_bytes', False)
def conv(arg):
if isinstance(arg, integer_types):
arg = int_to_bytes(arg)
if PY3:
if isinstance(arg, str):
arg = arg.e... | def hash(self, *args, **kwargs) | :param args:
:param kwargs:
joiner - string to join values (args)
as_bytes - bool to return hash bytes instead of default int
:rtype: int|bytes | 3.011577 | 2.663271 | 1.130781 |
bits_len = bits_len or self._bits_random
return random().getrandbits(bits_len) | def generate_random(self, bits_len=None) | Generates a random value.
:param int bits_len:
:rtype: int | 5.803013 | 8.15681 | 0.711432 |
return self.hash(self.pad(client_public), self.pad(server_public)) | def get_common_secret(self, server_public, client_public) | u = H(PAD(A) | PAD(B))
:param int server_public:
:param int client_public:
:rtype: int | 6.123872 | 4.857289 | 1.260759 |
password_verifier = self.get_common_password_verifier(password_hash)
return pow(
(server_public - (self._mult * password_verifier)),
(client_private + (common_secret * password_hash)), self._prime) | def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret) | S = (B - (k * g^x)) ^ (a + (u * x)) % N
:param int server_public:
:param int password_hash:
:param int client_private:
:param int common_secret:
:rtype: int | 6.70338 | 6.3711 | 1.052154 |
return pow((client_public * pow(password_verifier, common_secret, self._prime)), server_private, self._prime) | def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret) | S = (A * v^u) ^ b % N
:param int password_verifier:
:param int server_private:
:param int client_public:
:param int common_secret:
:rtype: int | 5.577685 | 5.421297 | 1.028847 |
return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime | def get_server_public(self, password_verifier, server_private) | B = (k*v + g^b) % N
:param int password_verifier:
:param int server_private:
:rtype: int | 10.439837 | 5.740528 | 1.81862 |
password = self._password
if password is None:
raise SRPException('User password should be in context for this scenario.')
return self.hash(salt, self.hash(self._user, password, joiner=':')) | def get_common_password_hash(self, salt) | x = H(s | H(I | ":" | P))
:param int salt:
:rtype: int | 12.661313 | 12.838687 | 0.986184 |
h = self.hash
prove = h(
h(self._prime) ^ h(self._gen),
h(self._user),
salt,
client_public,
server_public,
session_key,
as_bytes=True
)
return prove | def get_common_session_key_proof(self, session_key, salt, server_public, client_public) | M = H(H(N) XOR H(g) | H(U) | s | A | B | K)
:param bytes session_key:
:param int salt:
:param int server_public:
:param int client_public:
:rtype: bytes | 6.773732 | 6.40188 | 1.058085 |
return self.hash(client_public, session_key_proof, session_key, as_bytes=True) | def get_common_session_key_proof_hash(self, session_key, session_key_proof, client_public) | H(A | M | K)
:param bytes session_key:
:param bytes session_key_proof:
:param int client_public:
:rtype: bytes | 5.800269 | 5.35375 | 1.083403 |
salt = self.generate_salt()
verifier = self.get_common_password_verifier(self.get_common_password_hash(salt))
verifier = value_encode(verifier, base64)
salt = value_encode(salt, base64)
return self._user, verifier, salt | def get_user_data_triplet(self, base64=False) | ( <_user>, <_password verifier>, <salt> )
:param base64:
:rtype: tuple | 5.188484 | 4.889931 | 1.061055 |
if filename not in self.__input_files:
self.__input_files.append(filename) | def add_input_file(self, filename) | Add filename as a necessary input file for this DAG node.
@param filename: input filename to add | 3.813573 | 4.83684 | 0.788443 |
if filename not in self.__output_files:
self.__output_files.append(filename) | def add_output_file(self, filename) | Add filename as a output file for this DAG node.
@param filename: output filename to add | 3.808078 | 4.985218 | 0.763874 |
if filename not in self.__checkpoint_files:
self.__checkpoint_files.append(filename) | def add_checkpoint_file(self, filename) | Add filename as a checkpoint file for this DAG job. | 3.958331 | 3.192259 | 1.239978 |
self.__arguments.append(filename)
if filename not in self.__input_files:
self.__input_files.append(filename) | def add_file_arg(self, filename) | Add a file argument to the executable. Arguments are appended after any
options and their order is guaranteed. Also adds the file name to the
list of required input data for this job.
@param filename: file to add as argument. | 3.783009 | 3.702576 | 1.021724 |
if self.__options.has_key(opt):
return self.__options[opt]
return None | def get_opt( self, opt) | Returns the value associated with the given command line option.
Returns None if the option does not exist in the options list.
@param opt: command line option | 4.697052 | 4.352741 | 1.079102 |
self.__options[opt] = filename
if filename not in self.__input_files:
self.__input_files.append(filename) | def add_file_opt(self, opt, filename) | Add a command line option to the executable. The order that the arguments
will be appended to the command line is not guaranteed, but they will
always be added before any command line arguments. The name of the option
is prefixed with double hyphen and the program is expected to parse it
with getopt_lon... | 3.62722 | 5.857173 | 0.619278 |
for opt in cp.options(section):
arg = string.strip(cp.get(section,opt))
self.__options[opt] = arg | def add_ini_opts(self, cp, section) | Parse command line options from a given section in an ini file and
pass to the executable.
@param cp: ConfigParser object pointing to the ini file.
@param section: section of the ini file to add to the options. | 5.095114 | 5.056046 | 1.007727 |
if not self.__log_file:
raise CondorSubmitError, "Log file not specified."
if not self.__err_file:
raise CondorSubmitError, "Error file not specified."
if not self.__out_file:
raise CondorSubmitError, "Output file not specified."
if not self.__sub_file_path:
raise CondorSub... | def write_sub_file(self) | Write a submit file for this Condor job. | 1.834399 | 1.794007 | 1.022515 |
self.__grid_site=str(site)
if site != 'local':
self.set_executable_installed(False) | def set_grid_site(self,site) | Set the grid site to run on. If not specified,
will not give hint to Pegasus | 9.57897 | 10.067912 | 0.951436 |
if opt not in self.__var_opts:
self.__var_opts.append(opt)
macro = self.__bad_macro_chars.sub( r'', opt )
if short:
self.add_short_opt(opt,'$(macro' + macro + ')')
else:
self.add_opt(opt,'$(macro' + macro + ')') | def add_var_opt(self, opt, short=False) | Add a variable (or macro) option to the condor job. The option is added
to the submit file and a different argument to the option can be set for
each node in the DAG.
@param opt: name of option to add. | 4.730554 | 5.050239 | 0.936699 |
if command not in self.__var_cmds:
self.__var_cmds.append(command)
macro = self.__bad_macro_chars.sub( r'', command )
self.add_condor_cmd(command, '$(macro' + macro + ')') | def add_var_condor_cmd(self, command) | Add a condor command to the submit file that allows variable (macro)
arguments to be passes to the executable. | 7.991793 | 7.031306 | 1.136601 |
try:
self.__var_args[arg_index]
except IndexError:
if arg_index != self.__arg_index:
raise CondorDAGJobError, "mismatch between job and node var_arg index"
self.__var_args.append('$(macroargument%s)' % str(arg_index))
self.add_arg(self.__var_args[self.__arg_index])
sel... | def add_var_arg(self,arg_index) | Add a command to the submit file to allow variable (macro) arguments
to be passed to the executable. | 5.372324 | 5.106285 | 1.0521 |
self.__pegasus_profile.append((str(namespace),str(key),str(value))) | def add_pegasus_profile(self, namespace, key, value) | Add a Pegasus profile to this job which will be written to the dax as
<profile namespace="NAMESPACE" key="KEY">VALUE</profile>
This can be used to add classads to particular jobs in the DAX
@param namespace: A valid Pegasus namespace, e.g. condor.
@param key: The name of the attribute.
@param value:... | 4.875869 | 4.953455 | 0.984337 |
if filename not in self.__input_files:
self.__input_files.append(filename)
if not isinstance(self.job(), CondorDAGManJob):
if self.job().get_universe() == 'grid':
self.add_input_macro(filename) | def add_input_file(self, filename) | Add filename as a necessary input file for this DAG node.
@param filename: input filename to add | 6.564316 | 6.792614 | 0.96639 |
if filename not in self.__output_files:
self.__output_files.append(filename)
if not isinstance(self.job(), CondorDAGManJob):
if self.job().get_universe() == 'grid':
self.add_output_macro(filename) | def add_output_file(self, filename) | Add filename as a output file for this DAG node.
@param filename: output filename to add | 6.570518 | 6.808908 | 0.964988 |
if filename not in self.__checkpoint_files:
self.__checkpoint_files.append(filename)
if not isinstance(self.job(), CondorDAGManJob):
if self.job().get_universe() == 'grid':
self.add_checkpoint_macro(filename) | def add_checkpoint_file(self,filename) | Add filename as a checkpoint file for this DAG node
@param filename: checkpoint filename to add | 6.838781 | 6.62724 | 1.03192 |
input_files = list(self.__input_files)
if isinstance(self.job(), CondorDAGJob):
input_files = input_files + self.job().get_input_files()
return input_files | def get_input_files(self) | Return list of input files for this DAG node and its job. | 5.146831 | 3.459885 | 1.487573 |
output_files = list(self.__output_files)
if isinstance(self.job(), CondorDAGJob):
output_files = output_files + self.job().get_output_files()
return output_files | def get_output_files(self) | Return list of output files for this DAG node and its job. | 5.008936 | 3.406137 | 1.470562 |
checkpoint_files = list(self.__checkpoint_files)
if isinstance(self.job(), CondorDAGJob):
checkpoint_files = checkpoint_files + self.job().get_checkpoint_files()
return checkpoint_files | def get_checkpoint_files(self) | Return a list of checkpoint files for this DAG node and its job. | 5.617038 | 3.730313 | 1.505782 |
macro = self.__bad_macro_chars.sub( r'', name )
self.__opts[macro] = value | def add_macro(self,name,value) | Add a variable (macro) for this node. This can be different for
each node in the DAG, even if they use the same CondorJob. Within
the CondorJob, the value of the macro can be referenced as
'$(name)' -- for instance, to define a unique output or error file
for each node.
@param name: macro name.
... | 21.220163 | 34.548779 | 0.614209 |
io = self.__bad_macro_chars.sub( r'', io )
if io not in self.__opts:
self.__opts[io] = filename
else:
if filename not in self.__opts[io]:
self.__opts[io] += ',%s' % filename | def add_io_macro(self,io,filename) | Add a variable (macro) for storing the input/output files associated
with this node.
@param io: macroinput or macrooutput
@param filename: filename of input/output file | 4.619388 | 6.110656 | 0.755956 |
macro = self.__bad_macro_chars.sub( r'', command )
self.__macros['macro' + macro] = value
self.__job.add_var_condor_cmd(command) | def add_var_condor_cmd(self, command, value) | Add a variable (macro) condor command for this node. If the command
specified does not exist in the CondorJob, it is added so the submit file
will be correct.
PLEASE NOTE: AS with other add_var commands, the variable must be set for
all nodes that use the CondorJob instance.
@param command: command ... | 11.919497 | 12.636816 | 0.943236 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.