code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Call function `subject` and expect the function to raise an exception. >>> expect = Expector([]) >>> expect(lambda: 1 / 0).to(raise_error, ZeroDivisionError) (True, 'Expect ZeroDivisionError to be raised') ''' description = 'Expect {} to be raised'.format(error_class.__name__) try: ...
def raise_error(subject, error_class)
Call function `subject` and expect the function to raise an exception. >>> expect = Expector([]) >>> expect(lambda: 1 / 0).to(raise_error, ZeroDivisionError) (True, 'Expect ZeroDivisionError to be raised')
5.258605
2.002646
2.625829
''' Calls function `evaluator` before and after a call function `subject`. Output of `evaluator` should change. >>> expect = Expector([]) >>> a = [1, 2, 3] >>> expect(a.clear).to(change, lambda: len(a)) (True, 'expect change: actual from=3 to=0') >>> a = [1, 2, 3] >>> expect(a.clear).t...
def change(subject, evaluator, by=_NOT_SET, frm=_NOT_SET, to=_NOT_SET)
Calls function `evaluator` before and after a call function `subject`. Output of `evaluator` should change. >>> expect = Expector([]) >>> a = [1, 2, 3] >>> expect(a.clear).to(change, lambda: len(a)) (True, 'expect change: actual from=3 to=0') >>> a = [1, 2, 3] >>> expect(a.clear).to(change, la...
2.65877
1.491019
1.78319
''' Merges a series of single page pdfs into one multi-page doc ''' pdf_merger = PdfFileMerger() for pdf in pdf_list: pdf_merger.append(pdf) with NamedTemporaryFile(prefix='pyglass', suffix='.pdf', delete=False) as tempfileobj: dest_path = tempfileobj.name pdf_merger.write(dest_path) pdf_merger.cl...
def stitch_pdfs(pdf_list)
Merges a series of single page pdfs into one multi-page doc
3.500149
2.891966
1.210301
''' Splits a multi-page pdf into a list of single page pdfs ''' pdf = PdfFileReader(pdf_path) pdf_list = [] for page_num in range(pdf.numPages): page = pdf.getPage(page_num) pdf_writer = PdfFileWriter() pdf_writer.addPage(page) with NamedTemporaryFile(prefix='pyglass', suffix='.pdf', delete=F...
def split_pdf(pdf_path)
Splits a multi-page pdf into a list of single page pdfs
2.614728
2.437767
1.072591
''' Converts a single-page pdf to a png image via the `sips` command :returns: Path to the converted png ''' try: with NamedTemporaryFile(prefix='pyglass', suffix='.png', delete=False) as tempfileobj: png_path = tempfileobj.name cmd = ['sips', '-s', 'format', 'png', pdf_path, '--out', png_path] ...
def to_png(pdf_path)
Converts a single-page pdf to a png image via the `sips` command :returns: Path to the converted png
5.003803
3.496039
1.431278
''' Converts a multi-page pdfs to a list of pngs via the `sips` command :returns: A list of converted pngs ''' pdf_list = split_pdf(pdf_path) pngs = [] for pdf in pdf_list: pngs.append(to_png(pdf)) os.remove(pdf) # Clean up return pngs
def to_pngs(pdf_path)
Converts a multi-page pdfs to a list of pngs via the `sips` command :returns: A list of converted pngs
4.759358
2.611105
1.822737
headers = {"Subject": self._subject.format(**context)} md = self._source.format(**context) html = markdown.markdown(md) parts = {"text/html": html, "text/plain": md} return headers, parts
def evaluate(self, context)
Evaluates the markdown source in the given context, producing HTML and (Markdown) plain text. Also interpolates the subject line with the given context.
5.983338
4.614252
1.296708
if self._exceeds_max_file_size(file_info): self.log.info("File '%s' has a size in bytes (%d) greater than the configured limit. Will be ignored.", file_info.path, file_info.size) self.fire(events.FilteredFile(file_info)) return None ...
def process_data(self, file_info)
expects FileInfo
5.28846
5.066856
1.043736
path = self.translate_path(self.path) f = None to_render = False if os.path.isdir(path): if not self.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(301) self.send_header("Lo...
def send_head(self)
Builds response headers and in process renders templates, if any. This method overrides SimpleHTTPRequestHandlet.send_head()
2.28726
2.263539
1.01048
if s is None: return None elif not isinstance(s, unicode): s = str(s) else: s = s.encode('utf8') return PERCENT_CODE_SUB(lambda mo: chr(int(mo.group(0)[1:], 16)), s)
def pct_decode(s)
Return the percent-decoded version of string s. >>> pct_decode('%43%6F%75%63%6F%75%2C%20%6A%65%20%73%75%69%73%20%63%6F%6E%76%69%76%69%61%6C') 'Coucou, je suis convivial' >>> pct_decode('') '' >>> pct_decode('%2525') '%25'
4.642807
4.861101
0.955094
if s is None: return None elif not isinstance(s, unicode): s = str(s) else: s = s.encode('utf8') return ''.join(map(encdct.__getitem__, s))
def pct_encode(s, encdct)
Return a translated version of s where each character is mapped to a string thanks to the encdct dictionary. Use the encdct parameter to construct a string from parameter s where each character k from s is replaced by the value corresponding to key k in encdct. It happens that callers use dictionaries...
2.956793
2.987372
0.989764
if not host: return HOST_REG_NAME elif host[0] == '[': return HOST_IP_LITERAL elif __valid_IPv4address(host): return HOST_IPV4_ADDRESS else: return HOST_REG_NAME
def host_type(host)
Correctly classify correct RFC 3986 compliant hostnames, but do not try hard to validate compliance anyway... NOTE: indeed we allow a small deviation from the RFC 3986: IPv4 addresses are allowed to contain bytes represented in hexadecimal or octal notation when begining respectively with '0x'/'0X' and ...
5.845974
3.228791
1.810577
if '@' in authority: userinfo, hostport = authority.split('@', 1) if userinfo and ':' in userinfo: user, passwd = userinfo.split(':', 1) else: user, passwd = userinfo, None else: user, passwd, hostport = None, None, authority if hostport: ...
def split_authority(authority)
Split authority into component parts. This function supports IP-literal as defined in RFC 3986. >>> split_authority("user:passwd@host:port") ('user', 'passwd', 'host', 'port') >>> split_authority("user:@host:port") ('user', None, 'host', 'port') >>> split_authority("user@host:port") ('user...
2.898102
2.256148
1.284535
def split_assignment(a): sa = a.split('=', 1) return len(sa) == 2 and tuple(sa) or (sa[0], None) assignments = query.split('&') return tuple([split_assignment(a) for a in assignments if a])
def split_query(query)
Handle the query as a WWW HTTP 1630 query, as this is how people usually thinks of URI queries in general. We do not decode anything in split operations, neither percent nor the terrible plus-to-space conversion. Return: >>> split_query("k1=v1&k2=v+2%12&k3=&k4&&&k5==&=k&==") (('k1', 'v1'), ('k2',...
3.922397
4.049506
0.968611
def unsplit_assignment((x, y)): if (x is not None) and (y is not None): return x + '=' + y elif x is not None: return x elif y is not None: return '=' + y else: return '' return '&'.join(map(unsplit_assignment, query))
def unsplit_query(query)
Create a query string using the tuple query with a format as the one returned by split_query()
3.20209
3.164428
1.011902
p = RFC3986_MATCHER(uri).groups() return (p[1], p[3], p[4], p[6], p[8])
def basic_urisplit(uri)
Basic URI Parser according to RFC 3986 >>> basic_urisplit("scheme://authority/path?query#fragment") ('scheme', 'authority', '/path', 'query', 'fragment')
5.269293
7.128807
0.739155
scheme, authority, path, query, fragment = basic_urisplit(uri) if authority: authority = split_authority(authority) if query: query = split_query(query) return (scheme and scheme or None, authority and authority or None, path and path or None, query and query or None, ...
def uri_split_tree(uri)
Return (scheme, (user, passwd, host, port), path, ((k1, v1), (k2, v2), ...), fragment) using basic_urisplit(), then split_authority() and split_query() on the result. >>> uri_split_tree( ... 'http://%42%20+blabla:lol@%77ww.foobar.org/%7Exilun/' + ... '?query=+++%2b&=&===&a=b&...
2.778238
2.46038
1.129191
scheme, authority, path, query, fragment = uri_tree if authority and (filter(bool, authority) == ()): authority = None if query: query = filter(lambda (x, y): bool(x) or bool(y), query) return (scheme or None, authority or None, path or None, query or None, fragment or N...
def uri_tree_normalize(uri_tree)
Transform an URI tree so that adjacent all-empty fields are coalesced into a single None at parent level. The return value can be used for validation. As a result, no distinction is made between empty and absent fields. It is believed that this limitation is harmless because this is the behavior of ...
3.353892
3.532652
0.949398
scheme, authority, path, query, fragment = uri_tree if scheme: if not valid_scheme(scheme): raise InvalidSchemeError, "Invalid scheme %r" % (scheme,) if authority: user, passwd, host, port = authority if user and not __all_in(user, USER_CHAR): raise Inval...
def uri_tree_validate(uri_tree)
Validate a tree splitted URI in format returned by uri_tree_normalize(), raising an exception in case something invalid is detected - that is RFC 3986 is not respected - and returning the unmodified uri_tree otherwise. This function must be called on something similar to the return value of uri_tre...
2.468357
2.450577
1.007256
scheme, authority, path, query, fragment = uri_tree if authority: user, passwd, host, port = authority user, passwd = pct_decode(user), pct_decode(passwd) if host and host_type(host) == HOST_REG_NAME: host = pct_decode(host) authority = (user, passwd, host, port)...
def uri_tree_decode(uri_tree)
Decode a tree splitted URI in format returned by uri_split_tree() or uri_tree_normalize(), the returned value keeping the same layout. user, passwd, path, fragment are percent decoded, and so is host if of type reg-name. >>> uri_tree_decode( ... uri_split_tree( ... 'http://%42%...
2.615516
2.493203
1.049059
scheme, authority, path, query, fragment = uri_tree # pylint: disable-msg=W0612 if scheme: if not valid_scheme(scheme): raise InvalidSchemeError, "Invalid scheme %r" % (scheme,) if authority: user, passwd, host, port = authority # pylint: disable-msg=W0612 if port an...
def uri_tree_precode_check(uri_tree, type_host = HOST_REG_NAME)
Call this function to validate a raw URI tree before trying to encode it.
2.7179
2.655657
1.023438
scheme, authority, path, query, fragment = uri_tree if authority: user, passwd, host, port = authority if user: user = pct_encode(user, USER_ENCDCT) if passwd: passwd = pct_encode(passwd, PASSWD_ENCDCT) if host and type_host == HOST_REG_NAME: ...
def uri_tree_encode(uri_tree, type_host = HOST_REG_NAME)
Percent/Query encode a raw URI tree.
2.454232
2.450453
1.001542
scheme, authority, path, query, fragment = uri_tree if authority: user, passwd, host, port = authority if user and passwd: userinfo = user + ':' + passwd elif user: userinfo = user elif passwd: userinfo = ':' + passwd else: ...
def uri_unsplit_tree(uri_tree)
Unsplit a coded URI tree, which must also be coalesced by uri_tree_normalize().
1.746242
1.723314
1.013304
# check for valid configuration if base_key not in ctx.keys(): exit("[{}ERROR{}] missing configuration for '{}'" .format(ERROR_COLOR, RESET_COLOR, base_key)) # TODO: offer to create configuration file if ctx.releaser is None: exit("[{}ERROR{}] empty configuration f...
def check_configuration(ctx, base_key, needed_keys)
Confrim a valid configuration. Args: ctx (invoke.context): base_key (str): the base configuration key everything is under. needed_keys (list): sub-keys of the base key that are checked to make sure they exist.
3.909143
4.010533
0.974719
if allow_undefined and (to_check is None or to_check.lower() == 'none'): print("{: <14} -> {}UNDEFINED{}".format(name, WARNING_COLOR, RESET_COLOR)) return else: if config_key is None: config_key = "{}.{}".format(base_key, n...
def check_existence(to_check, name, config_key=None, relative_to=None, allow_undefined=False, allow_not_existing=False, base_key='releaser')
Determine whether a file or folder actually exists.
3.197393
3.180898
1.005186
for x in xrange(int(math.sqrt(num_of_pixels)) + 1, 1, -1): if num_of_pixels % x == 0: return num_of_pixels // x, x return 1, num_of_pixels
def _determine_dimensions(num_of_pixels)
Given a number of pixels, determines the largest width and height that define a rectangle with such an area
2.390517
2.582863
0.92553
_log.debug("File '%s' to image", file_path) data = numpy.fromfile(file_path, numpy.uint8) orig_len = len(data) pad_req = (3 - (orig_len % 3)) pad_req += 3 if pad_req == 0 else 0 final_len = orig_len + pad_req num_of_pixels = final_len // 3 w, h = _determine_dimensions(num_of_pixels)...
def _to_image_array(file_path)
Converts the file in file_path to a numpy array (matrix) representing an RGB image The dimensions of the image are calculated using __determine_dimensions. Padding is added provide enough bytes to generate the image (between 1 and 3 bytes can be added).
3.152127
2.809691
1.121877
img = Image.open(img_path) data = numpy.array(img) data = numpy.reshape(data, len(img.getdata()) * 3) to_remove = data[len(data) - 1] data = numpy.delete(data, xrange(len(data) - to_remove, len(data))) data.tofile(file_path)
def from_image_to_file(img_path, file_path)
Expects images created by from_from_file_to_image
3.254092
3.251223
1.000882
src_file_path = block.latest_file_info.path img_path = src_file_path + self.get_extension() self.log.debug("Converting file '%s' to image '%s'", src_file_path, img_path) from_file_to_image(src_file_path, img_path) block.image_converted_file_info = FileInfo(img_path) ...
def do_heavy_work(self, block)
Note: Expects Compressor Block like objects
3.702243
3.61661
1.023678
# If the details are a list if isinstance(details, list): # Create a list of options for the key return OptionsNode(details) # Else if we got a dictionary elif isinstance(details, dict): # If array is present if '__array__' in details: return ArrayNode(details) # Else if we have a hash elif '_...
def _child(details)
Child A private function to figure out the child node type Arguments: details {dict} -- A dictionary describing a data point Returns: _NodeInterface
2.925612
2.841375
1.029647
# Load the file oFile = open(filename) # Convert it to a dictionary dDetails = JSON.decodef(oFile) # Create and return the new instance return cls(dDetails)
def fromFile(cls, filename)
From File Loads a JSON file and creates a Node instance from it Args: filename (str): The filename to load Returns: _NodeInterface
7.586554
8.177167
0.927773
# If there's no value, this is a getter if value is None: return this._optional # Else, set the flag else: this._optional = value and True or False
def optional(self, value = None)
Optional Getter/Setter method for optional flag Args: value (bool): If set, the method is a setter Returns: bool | None
5.558795
4.980709
1.116065
# Check the name is a string if not isinstance(name, basestring): raise TypeError('name must be a string') # Check the name is valid if not _specialName.match(name): raise ValueError('special name must match "%s"' % _specialSyntax) # If the value is not set, this is a getter if value is None: ...
def special(self, name, value=None, default=None)
Special Getter/Setter method for special values associated with nodes that are not fields To retrieve a value or values, pass only the name or names, to set a single special value, pass a name and value Args: name (str): The name of the value to either set or get value (mixed): The value to set M...
3.102704
2.863522
1.083527
# Create the dict we will return dRet = {} # If the optional flag is set if self._optional: dRet['__optional__'] = True # Add all the special fields found for k in self._special.keys(): dRet[_specialSet % k] = self._special[k] # Return return dRet
def toDict(self)
To Dictionary Returns the basic node as a dictionary in the same format as is used in constructing it Returns: dict
5.656026
6.226315
0.908407
# If the value is None and it's optional, return as is if value is None and self._optional: return None # If the value is not a list if not isinstance(value, list): raise ValueError('value') # Recurse and return it return [self._node.clean(m) for m in value]
def clean(self, value)
Clean Goes through each of the values in the list, cleans it, stores it, and returns a new list Arguments: value {list} -- The value to clean Returns: list
4.197614
4.534369
0.925733
# If neither minimum or maximum is set, this is a getter if(minimum is None and maximum is None): return {"minimum": self._minimum, "maximum": self._maximum} # If the minimum is set if minimum is not None: # If the value is not a valid int or long if not isinstance(minimum, (int, long)): # I...
def minmax(self, minimum=None, maximum=None)
Min/Max Sets or gets the minimum and maximum number of items for the Array Arguments minimum {uint} -- The minimum value maximum {uint} -- The maximum value Raises: ValueError Returns: None
2.150618
2.117476
1.015652
# Init the dictionary we will return dRet = {} # If either a min or a max is set if self._minimum or self._maximum: # Set the array element as it's own dict dRet['__array__'] = { "type": self._type } # If there is a minimum if self._minimum: dRet['__array__']['minimum'] = self._min...
def toDict(self)
To Dictionary Returns the Array as a dictionary in the same format as is used in constructing it Returns: dict
2.92132
2.976685
0.981401
# Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # If the value isn't a list if not isinstance(value, list): self.validation_failures.append(('.'.join(level), str(value))) return Fal...
def valid(self, value, level=[])
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
2.559717
2.614842
0.978918
# If the value is None and it's optional, return as is if value is None and self._optional: return None # If the value is not a dict if not isinstance(value, dict): raise ValueError('value') # Recurse and return it return {str(self._key.clean(k)):self._node.clean(v) for k,v in iteritems(value)}
def clean(self, value)
Clean Makes sure both the key and value are properly stored in their correct representation Arguments: value {mixed} -- The value to clean Raises: ValueError Returns: mixed
3.876333
4.120212
0.940809
# Init the dictionary we will return dRet = {} # Add the hash key dRet['__hash__'] = self._key.toDict() # Get the parents dict and add it to the return dRet.update(super(HashNode,self).toDict()) # Get the nodes dict and also add it to the return dRet.update(self._node.toDict()) # Return retu...
def toDict(self)
To Dict Returns the Hashed Node as a dictionary in the same format as is used in constructing it Returns: dict
4.003353
4.145574
0.965693
# Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # If the value isn't a dictionary if not isinstance(value, dict): self.validation_failures.append(('.'.join(level), str(value))) retu...
def valid(self, value, level=[])
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
2.63271
2.713757
0.970135
# If the two IPs are the same, return 0 if first == second: return 0 # Create lists from the split of each IP, store them as ints lFirst = [int(i) for i in first.split('.')] lSecond = [int(i) for i in second.split('.')] # Go through each part from left to right until we find the # difference f...
def __compare_ips(first, second)
Compare IPs Compares two IPs and returns a status based on which is greater If first is less than second: -1 If first is equal to second: 0 If first is greater than second: 1 Arguments: first {str} -- A string representing an IP address second {str} -- A string representing an IP address Returns: ...
2.687099
2.648684
1.014503
# If regex was not set, this is a getter if regex is None: return self._regex # If the type is not a string if self._type != 'string': sys.stderr.write('can not set __regex__ for %s' % self._type) return # If it's not a valid string or regex if not isinstance(regex, (basestring, _REGEX_TYPE))...
def regex(self, regex = None)
Regex Sets or gets the regular expression used to validate the Node Arguments: regex {str} -- A standard regular expression string Raises: ValueError Returns: None | str
4.126291
4.128634
0.999432
# Init the dictionary we will return dRet = { "__type__": self._type } # If there is a regex associated, add it if self._regex: dRet['__regex__'] = str(self._regex) # Else if there were options associated, add them elif self._options: dRet['__options__'] = self._options # Else check for ...
def toDict(self)
To Dict Returns the Node as a dictionary in the same format as is used in constructing it Returns: dict
3.310974
3.382857
0.978751
# If the value is None and it's optional, return as is if value is None and self._optional: return None # Go through each of the nodes for i in range(len(self._nodes)): # If it's valid if self._nodes[i].valid(value): # Use it's clean return self._nodes[i].clean(value) # Something went...
def clean(self, value)
Clean Uses the valid method to check which type the value is, and then calls the correct version of clean on that node Arguments: value {mixed} -- The value to clean Returns: mixed
3.653277
3.360379
1.087162
# Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # Go through each of the nodes for i in range(len(self._nodes)): # If it's valid if self._nodes[i].valid(value): # Return OK ...
def valid(self, value, level=[])
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
3.928337
4.266733
0.92069
# If the value is None and it's optional, return as is if value is None and self._optional: return None # If the value is not a dict if not isinstance(value, dict): raise ValueError('value') # Init the return value dRet = {} # Go through each value and clean it using the associated node for...
def clean(self, value)
Clean Goes through each of the values in the dict, cleans it, stores it, and returns a new dict Arguments: value {dict} -- The value to clean Returns: dict
3.341747
3.341263
1.000145
if key in self._nodes: return self._nodes[key] else: return default
def get(self, key, default=None)
Get Returns the node of a specific key from the parent Arguments: key {str} -- The key to get default {mixed} Value to return if the key does not exist Returns: mixed
4.162565
5.985393
0.695454
if hasattr(self._nodes, 'iterkeys'): return self._nodes.keys() else: return tuple(self._nodes.keys())
def keys(self)
Keys Returns a list of the node names in the parent Returns: list
3.932545
4.624735
0.850329
# If require is None, this is a getter if require is None: return self._requires # If it's not a valid dict if not isinstance(require, dict): raise ValueError('__require__') # Go through each key and make sure it goes with a field for k,v in iteritems(require): # If the field doesn't exist ...
def requires(self, require=None)
Requires Sets the require rules used to validate the Parent Arguments: require {dict} -- A dictionary expressing requirements of fields Raises: ValueError Returns: None
2.761661
2.649874
1.042186
# Get the parents dict as the starting point of our return dRet = super(Parent,self).toDict() # Go through each field and add it to the return for k,v in iteritems(self._nodes): dRet[k] = v.toDict() # Return return dRet
def toDict(self)
To Dict Returns the Parent as a dictionary in the same format as is used in constructing it Returns: dict
5.128066
5.178242
0.99031
# Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # If the value isn't a dictionary if not isinstance(value, dict): self.validation_failures.append(('.'.join(level), str(value))) retu...
def valid(self, value, level=[])
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
2.731193
2.7562
0.990927
if hasattr(self._nodes, 'viewkeys'): return self._nodes.viewkeys() else: return self._nodes.keys()
def viewkeys(self)
View Keys Returns a view associated with the parent's keys Returns: dict_view
2.933662
3.872297
0.757603
# Init the dictionary we will return dRet = { "__name__": self._name } # Get the parents dict and add it to the return dRet.update(super(Tree,self).toDict()) # Return return dRet
def toDict(self)
To Dict Returns the Tree as a dictionary in the same format as is used in constructing it Returns: dict
5.992302
6.451355
0.928844
# Call the parent valid method and return the result return super(Tree, self).valid(value, include_name and [self._name] or [])
def valid(self, value, include_name=True)
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate include_name {bool} -- If true, Tree's name will be prepended to all error keys Returns: bool
7.217324
7.19874
1.002581
cleaner = lxml.html.clean.Cleaner(scripts=True) cleaned = cleaner.clean_html(html) return lxml.html.fromstring(cleaned).text_content()
def textFromHTML(html)
Cleans and parses text from the given HTML.
2.899717
2.930387
0.989534
html = self._source.format(**context) parts = {"text/html": html, "text/plain": textFromHTML(html)} return {}, parts
def evaluate(self, context)
Interpolates the HTML source with the context, then returns that HTML and the text extracted from that html.
12.350769
7.657467
1.612905
self.log.info('starting the ``get`` method') if self.fullUpdate: recent = False else: recent = True self.import_new_atlas_pointings(recent) self._run_bookkeeping_sql_scripts() self.log.info('completed the ``get`` method') return...
def clean_all(self)
*clean and sync all the bookkeeping tables* **Return:** - ``bookkeeper`` **Usage:** .. code-block:: python from rockAtlas.bookkeeping import bookkeeper bk = bookkeeper( log=log, settings=settings, ...
12.369084
7.749165
1.596183
self.log.info('starting the ``import_new_atlas_pointings`` method') if recent: mjd = mjdnow( log=self.log ).get_mjd() recent = mjd - 14 recent = " mjd_obs > %(recent)s " % locals() else: recent = "1=1" ...
def import_new_atlas_pointings( self, recent=False)
*Import any new ATLAS pointings from the atlas3/atlas4 databases into the ``atlas_exposures`` table of the Atlas Movers database* **Key Arguments:** - ``recent`` -- only sync the most recent 2 weeks of data (speeds things up) **Return:** - None **Usage:** ...
3.060024
2.767984
1.105506
self.log.info('starting the ``_run_bookkeeping_sql_scripts`` method') moduleDirectory = os.path.dirname(__file__) mysqlScripts = moduleDirectory + "/mysql" directory_script_runner( log=self.log, pathToScriptDirectory=mysqlScripts, databaseNa...
def _run_bookkeeping_sql_scripts( self)
*run bookkeeping sql scripts*
5.581937
5.266955
1.059803
for base in bases: basedir, _ = base.split(".", 1) base = os.path.join(os.path.dirname(__file__), *base.split(".")) rem = len(os.path.dirname(base)) + len(basedir) + 2 for root, dirs, files in os.walk(base): for name in files: ...
def get_files(*bases)
List all files in a data directory.
2.997167
3.039455
0.986087
x = math.radians(other.longitude - self.longitude) \ * math.cos(math.radians(other.latitude + self.latitude) / 2); y = math.radians(other.latitude - self.latitude); return math.sqrt(x * x + y * y) * GeoPoint.EARTH_RADIUS_METERS;
def equirectangular_distance(self, other)
Return the approximate equirectangular when the location is close to the center of the cluster. For small distances, Pythagoras’ theorem can be used on an equirectangular projection. Equirectangular formula:: x = Δλ ⋅ cos φm y = Δφ d = R ⋅ √(x² + y)...
2.913543
3.35193
0.869214
distance_latitude = math.radians(abs(self.latitude - other.latitude)) distance_longitude = math.radians(abs(self.longitude - other.longitude)) a = math.sin(distance_latitude / 2) * math.sin(distance_latitude / 2) \ + math.cos(math.radians(self.latitude)) \ * ma...
def great_circle_distance(self, other)
Return the great-circle distance, in meters, from this geographic coordinates to the specified other point, i.e., the shortest distance over the earth’s surface, ‘as-the-crow-flies’ distance between the points, ignoring any natural elevations of the ground. Haversine formula:: ...
1.544165
1.708726
0.903694
return payload and \ GeoPoint(payload['longitude'], payload['latitude'], accuracy=payload.get('accuracy'), altitude=payload.get('altitude'), bearing=payload.get('bearing'), fix_time=payl...
def from_json(payload)
Build a ``GeoPoint`` instance from the specified JSON object. @param payload: JSON representation of a geographic location:: { "accuracy": decimal, "altitude": decimal, "bearing": decimal, "longitude": decimal, ...
2.950278
2.55711
1.153755
degrees = int(dd) minutes = (dd - degrees) * 60 seconds = int((minutes - int(minutes)) * 60) return unicode(degrees) + u'°' + unicode(int(minutes)) + u"'" + unicode(int(seconds)) + u'"'
def convert_dd_to_dms_string(dd)
Convert decimal degrees (DD), which expresses latitude and longitude geographic coordinates as decimal fraction, to a degrees, minutes, and seconds (DMS) string representation, such as 38° 53' 23" N. @param dd: decimal degrees of the geographic coordinates of a location on the Earth...
2.327557
2.671856
0.871139
degree = float(degree_num) / float(degree_den) minute = float(minute_num) / float(minute_den)/ 60 second = float(second_num) / float(second_den)/ 3600 return degree + minute + second
def convert_dms_to_dd( degree_num, degree_den, minute_num, minute_den, second_num, second_den)
Convert the degree/minute/Second formatted GPS data to decimal degrees. @param degree_num: the numerator of the degree object. @param degree_den: the denominator of the degree object. @param minute_num: the numerator of the minute object. @param minute_den: the denominator of...
1.981268
2.200252
0.900473
degree_mark_offset = dms.find(u'°') degrees = float(dms[:degree_mark_offset].strip()) minute_mark_offset = dms.find(u"'") minutes = float(dms[degree_mark_offset + 1:minute_mark_offset].strip()) second_mark_offset = dms.find(u'"') seconds = float(dms[minute_mark_o...
def convert_dms_string_to_dd(dms)
Convert a degrees, minutes, and seconds (DMS) string representation, such as 38° 53' 23" N, to a decimal degrees (DD), which expresses latitude and longitude geographic coordinates as decimal fraction. @param dms: degrees, minutes, and seconds (DMS) string representation of a locati...
1.747857
1.82266
0.958959
if isinstance(d, dict): safe_dict = dict((key, public_dict(value)) for key, value in d.items() if not key.startswith('_')) if '_cls' in d: safe_dict['type'] = d['_cls'] return safe_dict if isinstance(d, list): return [public_dict(l) for l in d] return d
def public_dict(d)
if type(d) is dict: return dict((k, public_dict(v)) for k, v in d.items() if not k.startswith('_')) elif type(d) is list: return [public_dict(v) for v in d] else: return d
2.441723
2.343014
1.042129
if isinstance(obj, (str, int, float)): return obj if isinstance(obj, dict): new = obj.__class__() for k, v in obj.items(): new[convert(k)] = change_keys(v, convert) elif isinstance(obj, (list, set, tuple)): new = obj.__class__(change_keys(v, convert) for v in...
def change_keys(obj, convert)
Recursively goes through the dictionary obj and replaces keys with the convert function.
1.68297
1.662517
1.012303
try: connection_properties = settings.get(tag, settings[None]) except KeyError: raise RdbmsConnection.DefaultConnectionPropertiesSettingException() return RdbmsConnection( connection_properties['rdbms_hostname'], connection_properties['rd...
def acquire_connection(settings, tag=None, logger_name=None, auto_commit=False)
Return a connection to a Relational DataBase Management System (RDBMS) the most appropriate for the service requesting this connection. @param settings: a dictionary of connection properties:: { None: { 'rdbms_hostname': "...", ...
3.391422
1.822868
1.860487
if parameters: # Convert the simple value of parameters which the database adapter # cannot adapt to SQL type, such as enum values. # [http://initd.org/psycopg/docs/usage.html#query-parameters] # # @note: tuple is a special type used to indica...
def execute(self, sql_statement, parameters=None)
Execute the specified Structured Query Language (SQL) parameterized statement. @note: each result column MUST be named with distinct names. @param sql_statement: a string representation of a Structured Query Language (SQL) expression including Python extended format codes, ...
4.372978
4.429123
0.987324
if isinstance(value, (list, set)) or (isinstance(value, tuple) and len(value) != 1): sql_value = ','.join( [ RdbmsConnection._to_sql_value( element if not isinstance(element, tuple) else element[0], noquote=isinstance(element, tuple)) ...
def _expand_placeholder_value(value)
Return the SQL string representation of the specified placeholder's value. @param value: the value of a placeholder such as a simple element, a list, or a tuple of one string. @note: by convention, a tuple of one string indicates that this string MUST not be quoted as...
3.072696
2.955892
1.039516
# Find the list of placeholders, and their type, defined in the SQL # statement. placeholders = {} try: for match in REGEX_PATTERN_SQL_PLACEHOLDERS.findall(sql_statement): for (i, placeholder_type) in enumerate(PlaceholderType._values): ...
def _get_placeholders(sql_statement, parameters)
Retrieve the list of placeholders and their type defined in an SQL statement. @param sql_statement: a parameterized statement. @param parameters: the list of parameters used in the SQL statement. @return: a dictionary of placeholders where the key represents the name of ...
3.614583
3.523387
1.025883
placehoolders = RdbmsConnection._get_placeholders(sql_statement, parameters) for (variable_name, (variable_type, variable_value)) in placehoolders.iteritems(): # Only expand parameters whose value corresponds to a list. if isinstance(variable_value, (list, set, tuple)):...
def _prepare_statement(sql_statement, parameters)
Prepare the specified SQL statement, replacing the placeholders by the value of the given parameters @param sql_statement: the string expression of a SQL statement. @param parameters: a dictionary of parameters where the key represents the name of a parameter and the value represen...
5.546137
5.437191
1.020037
(variable_name, variable_type, variable_value) = variable sql_value = RdbmsConnection._expand_placeholder_value(variable_value) if variable_type == PlaceholderType.simple_list \ else ','.join([ '(%s)' % RdbmsConnection._expand_placeholder_value(v) for v in variable_value ]) ...
def _replace_placeholder(sql_statement, variable)
Return the string obtained by replacing the specified placeholders by its corresponding value. @param sql_statement: the string expression of a SQL statement to replace placeholders with their corresponding values. @param variable: the variable to use to replace the corresponding ...
4.685436
6.102837
0.767747
# Convert to string the values that the database adapter can't adapt # to a SQL type. # [http://initd.org/psycopg/docs/usage.html#query-parameters] if not isinstance(value, (types.NoneType, bool, int, long, float, basestring)): value = obj.stringify(value) i...
def _to_sql_value(value, noquote=False)
Return the SQL string representation of the specified value. @param value: a value to convert into its SQL string representation. @param noquote: indicate whether to quote or not the specified value. @return: a SQL string representation of the specified value.
6.912594
6.774965
1.020314
attrs = copy.copy(launch.el_attrs) # Remove attributes we overwrite / don't need del attrs["Type"] if attrs.has_key("DependsOn"): del attrs["DependsOn"] if attrs["Properties"].has_key("SpotPrice"): del attrs["Properties"]["SpotPrice"] if a...
def standalone_from_launchable(cls, launch)
Given a launchable resource, create a definition of a standalone instance, which doesn't depend on or contain references to other elements.
4.35981
4.130846
1.055428
def filter_data(self, pattern=''): filtered_profiles = {} with open(self.abspath) as fobj: for idx, line in enumerate(fobj): if 'TIME SERIES' in line: break if pattern in line and (idx-self._attributes['CATALOG']-1) > 0: ...
Filter available varaibles
null
null
null
def extract_geometry(self, branch, branch_begin): raw_geometry = [] with open(self.abspath) as fobj: for line in fobj.readlines()[branch_begin:]: points = [] for point in line.split(' '): try: points...
It adds to self.geometries a specific geometry as (x, y)
null
null
null
def extract(self, variable_idx): branch = self._define_branch(variable_idx) label = self.profiles[variable_idx].replace("\n", "") self.label[variable_idx] = label self.data[variable_idx] = [[], []] with open(self.abspath) as fobj: for line in fobj.read...
Extract a specific varaible
null
null
null
def to_excel(self, *args): path = os.getcwd() fname = self.fname.replace(".ppl", "_ppl") + ".xlsx" if len(args) > 0 and args[0] != "": path = args[0] if os.path.exists(path) == False: os.mkdir(path) xl_file = pd.ExcelWriter(path + ...
Dump all the data to excel, fname and path can be passed as args
null
null
null
if re.search(r'[\\" ]', unquoted_name, re.M): return '"' + email.utils.quote(unquoted_name) + '"' else: return unquoted_name
def quote_as2name(unquoted_name)
Function converts as2 name from unquoted to quoted format :param unquoted_name: the as2 name in unquoted format :return: the as2 name in unquoted format
4.890124
5.250836
0.931304
fp = BytesIO() g = BytesGenerator(fp, maxheaderlen=header_len) g.flatten(msg) return fp.getvalue()
def mime_to_bytes(msg, header_len)
Function to convert and email Message to flat string format :param msg: email.Message to be converted to string :param header_len: the msx length of the header per line :return: the byte string representation of the email message
4.392051
4.565978
0.961908
if message.is_multipart() \ or message.get('Content-Transfer-Encoding') != 'binary': return mime_to_bytes(message, 0).replace( b'\r\n', b'\n').replace(b'\r', b'\n').replace(b'\n', b'\r\n') else: message_header = '' message_body = message.get_payload(decode=...
def canonicalize(message)
Function to convert an email Message to standard format string :param message: email.Message to be converted to standard string :return: the standard representation of the email message in bytes
2.556906
2.434537
1.050264
first_message = message.split(boundary)[1].lstrip() if first_message.endswith(b'\r\n'): first_message = first_message[:-2] else: first_message = first_message[:-1] return first_message
def extract_first_part(message, boundary)
Function to extract the first part of a multipart message
2.127836
2.199534
0.967403
# initialize the certificate array cert_list = [] # If certificate is in DER then un-armour it if pem.detect(cert): for _, _, der_bytes in pem.unarmor(cert, multiple=True): cert_list.append(der_bytes) else: cert_list.append(cert) # return multiple if return_mu...
def pem_to_der(cert, return_multiple=True)
Converts a given certificate or list to PEM format
4.284242
4.266457
1.004169
started, pem_data = False, b'' for line in pem_bytes.splitlines(False): if line == b'' and not started: continue if line[0:5] in (b'-----', b'---- '): if not started: started = True else: pem_data = pem_data + line + b'\r...
def split_pem(pem_bytes)
Split a give PEM file with multiple certificates :param pem_bytes: The pem data in bytes with multiple certs :return: yields a list of certificates contained in the pem file
2.722028
2.982428
0.912689
# Load the certificate certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_str) # Create a certificate store and add your trusted certs try: store = crypto.X509Store() if ignore_self_signed: store.add_cert(certificate) # Assuming the certificates...
def verify_certificate_chain(cert_str, trusted_certs, ignore_self_signed=True)
Verify a given certificate against a trust store
3.164957
3.116616
1.015511
def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: ...
def csrf(request)
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware
4.887593
4.356972
1.121787
root_url = root_url.rstrip('/') path = path.lstrip('/') if root_url == OLD_ROOT_URL: return 'https://{}.taskcluster.net/{}/{}'.format(service, version, path) else: return '{}/api/{}/{}/{}'.format(root_url, service, version, path)
def api(root_url, service, version, path)
Generate URL for path in a Taskcluster service.
2.86845
2.428594
1.181116
root_url = root_url.rstrip('/') if root_url == OLD_ROOT_URL: return 'https://references.taskcluster.net/{}/{}/api.json'.format(service, version) else: return '{}/references/{}/{}/api.json'.format(root_url, service, version)
def api_reference(root_url, service, version)
Generate URL for a Taskcluster api reference.
3.724228
3.183756
1.169759
root_url = root_url.rstrip('/') path = path.lstrip('/') if root_url == OLD_ROOT_URL: return 'https://docs.taskcluster.net/{}'.format(path) else: return '{}/docs/{}'.format(root_url, path)
def docs(root_url, path)
Generate URL for path in the Taskcluster docs.
2.855568
2.31371
1.234194
root_url = root_url.rstrip('/') if root_url == OLD_ROOT_URL: return 'https://references.taskcluster.net/{}/{}/exchanges.json'.format(service, version) else: return '{}/references/{}/{}/exchanges.json'.format(root_url, service, version)
def exchange_reference(root_url, service, version)
Generate URL for a Taskcluster exchange reference.
3.705667
3.136012
1.18165
root_url = root_url.rstrip('/') name = name.lstrip('/') if root_url == OLD_ROOT_URL: return 'https://schemas.taskcluster.net/{}/{}'.format(service, name) else: return '{}/schemas/{}/{}'.format(root_url, service, name)
def schema(root_url, service, name)
Generate URL for a schema in a Taskcluster service.
3.024914
2.627427
1.151284
root_url = root_url.rstrip('/') path = path.lstrip('/') if root_url == OLD_ROOT_URL: return 'https://tools.taskcluster.net/{}'.format(path) else: return '{}/{}'.format(root_url, path)
def ui(root_url, path)
Generate URL for a path in the Taskcluster ui. The purpose of the function is to switch on rootUrl: "The driver for having a ui method is so we can just call ui with a path and any root url, and the returned url should work for both our current deployment (with root URL = https://taskcluster.net) and an...
3.285323
2.195792
1.49619
required = set(fields) - set(defaults) if required: raise TypeError( "regex_validation_sealer doesn't support required arguments. Fields that need fixing: %s" % required) klass = None kwarg_validators = dict( (key, val if isinstance(val, RegexType) else re.compile(val))...
def regex_validation_sealer(fields, defaults, RegexType=type(re.compile("")))
Example sealer that just does regex-based validation.
2.540623
2.543192
0.99899
eps = tf.random_normal([self.batch_size, self.eq_samples, self.iw_samples, self.num_latent]) z = tf.reshape(eps * self.std + self.mu, [-1, self.num_latent]) return z
def compute_samples(self)
Sample from a Normal distribution with inferred mu and std
4.846425
3.952195
1.226262
x_reshape = tf.reshape(x, [self.batch_size, self.eq_samples, self.iw_samples, self.num_latent]) c = - 0.5 * math.log(2 * math.pi) if standard is False: density = c - tf.log(self.std) - (x_reshape - self.mu) ** 2 / (2 * self.std**2) else: density = c - (x_...
def neg_log_likelihood(self, x, standard=False)
Calculate Log Likelihood with particular mean and std x must be 2D. [batch_size * eqsamples* iwsamples, num_latent]
3.651273
2.75672
1.324499
mu, std, h, w = self.params shape = tf.shape(mu) eps = tf.random_normal(shape) z = tf.reshape(eps * std + mu, tf.stack([-1, h, w, self.num_latent])) return z
def compute_samples(self)
Sample from a Normal distribution with inferred mu and std
4.618052
4.126764
1.119049
mu, std, h, w = self.params shape = tf.stack([32, x_dims[0], x_dims[1], self.num_latent, 1, 1]) x_reshape = tf.reshape(x, shape) c = - 0.5 * math.log(2 * math.pi) if standard is False: density = c - tf.log(std + 1e-10) - (x_reshape - mu) ** 2 / (2 * std**2) ...
def log_likelihood(self, x, x_dims=(128, 128), standard=False)
Calculate Log Likelihood with particular mean and std x must be 2D. [batch_size * eqsamples* iwsamples, num_latent]
3.718322
3.182268
1.16845