code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
result = dict.fromkeys(META_FIELDS) # get etext no about = ebook.get('{%(rdf)s}about' % NS) result['id'] = int(os.path.basename(about)) # author creator = ebook.find('.//{%(dc)s}creator' % NS) if creator is not None: name = creator.find('.//{%(pg)s}name' % NS) if name is not None: result['author'] = saf...
def parsemetadata(ebook)
Parses an etext meta-data definition to extract fields. Args: ebook (xml.etree.ElementTree.Element): An ebook meta-data definition.
2.154317
2.133705
1.00966
for line in lines: match = ETEXTRE.search(line) if match is not None: front_match = match.group('etextid_front') back_match = match.group('etextid_back') if front_match is not None: return int(front_match) elif back_match is not None: return int(back_match) else: raise ValueError('no r...
def etextno(lines)
Retrieves the id for an etext. Args: lines (iter): The lines of the etext to search. Returns: int: The id of the etext. Raises: ValueError: If no etext id was found. Examples: >>> etextno(['Release Date: March 17, 2004 [EBook #11609]']) 11609 >>> etextno(['Release Date: July, 2003 [Etext# 4263]']) 426...
2.745841
2.521738
1.088869
return arg if isinstance(arg, unicode) else unicode(arg, *args, **kwargs)
def safeunicode(arg, *args, **kwargs)
Coerce argument to unicode, if it's not already.
2.888946
2.455789
1.176382
if False: # If there was a Test version of this method, it would go here. But alas. pass else: rows = _Constants._DATABASE.execute("SELECT data FROM energy".format( hardware=_Constants._HARDWARE)) data = [r[0] for r in rows] data = [_Auxiliary._byteify(_j...
def get_reports()
Returns energy data from 1960 to 2014 across various factors.
11.449774
10.219152
1.120423
for name, point in six.iteritems(src): inst = dst.pop(name, None) if inst is None: self.print_(1, "Registering %s for %s" % (model.__name__, name)) inst = model(pythonpath=name) ...
def available(self, src, dst, model)
Iterate over all registered plugins or plugin points and prepare to add them to database.
6.973387
5.680397
1.227623
for inst in six.itervalues(dst): if inst.status != REMOVED: inst.status = REMOVED inst.save()
def missing(self, dst)
Mark all missing plugins, that exists in database, but are not registered.
8.727516
7.27069
1.20037
# Django >= 1.9 changed something with the migration logic causing # plugins to be executed before the corresponding database tables # exist. This method will only return something if the database # tables have already been created. # XXX: I don't fully understand the is...
def all(self)
Synchronize all registered plugins and plugin points to database.
8.862604
7.401278
1.197442
if _Constants._TEST or test: rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format( hardware=_Constants._HARDWARE)) data = [r[0] for r in rows] data = [_Auxiliary._byteify(_json.loads(r)) for r in data] return _Auxiliary._byt...
def get_weather(test=False)
Returns weather reports from the dataset.
3.500107
3.292455
1.063069
''' Makes a GET request, setting Authorization header by default ''' headers = kw.pop('headers', {}) headers.setdefault('Content-Type', 'application/json') headers.setdefault('Accept', 'application/json') headers.setdefault('Authorization', self.AUTHORIZAT...
def _get(self, url, **kw)
Makes a GET request, setting Authorization header by default
2.972036
2.150537
1.381997
''' Makes a POST request, setting Authorization header by default ''' headers = kw.pop('headers', {}) headers.setdefault('Authorization', self.AUTHORIZATION_HEADER) kw['headers'] = headers resp = self.session.post(url, **kw) self._raise_for_status(...
def _post(self, url, **kw)
Makes a POST request, setting Authorization header by default
3.849959
2.546573
1.51182
''' Makes a POST request, setting Authorization and Content-Type headers by default ''' data = json.dumps(data) headers = kw.pop('headers', {}) headers.setdefault('Content-Type', 'application/json') headers.setdefault('Accept', 'application/json') ...
def _post_json(self, url, data, **kw)
Makes a POST request, setting Authorization and Content-Type headers by default
2.943613
2.07312
1.419895
''' Instantiates an instance of ``GamerProfile`` from an xuid :param xuid: Xuid to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance ''' url = 'https://profile.xboxlive.com/users/xuid(%s)/profile...
def from_xuid(cls, xuid)
Instantiates an instance of ``GamerProfile`` from an xuid :param xuid: Xuid to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance
4.897999
2.894676
1.692071
''' Instantiates an instance of ``GamerProfile`` from a gamertag :param gamertag: Gamertag to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance ''' url = 'https://profile.xboxlive.com/users/gt(%s)...
def from_gamertag(cls, gamertag)
Instantiates an instance of ``GamerProfile`` from a gamertag :param gamertag: Gamertag to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance
3.945693
2.399005
1.64472
''' Gets a specific game clip :param xuid: xuid of an xbox live user :param scid: scid of a clip :param clip_id: id of a clip ''' url = ( 'https://gameclipsmetadata.xboxlive.com/users' '/xuid(%(xuid)s)/scids/%(scid)s/clips/%(clip_id)s' % {...
def get(cls, xuid, scid, clip_id)
Gets a specific game clip :param xuid: xuid of an xbox live user :param scid: scid of a clip :param clip_id: id of a clip
3.903069
3.435318
1.136159
''' Gets all clips 'saved' by a user. :param user: :class:`~xbox.GamerProfile` instance :param bool include_pending: whether to ignore clips that are not yet uploaded. These clips will have thumbnails and media_url set to ``None`` :returns: Iterator of :c...
def saved_from_user(cls, user, include_pending=False)
Gets all clips 'saved' by a user. :param user: :class:`~xbox.GamerProfile` instance :param bool include_pending: whether to ignore clips that are not yet uploaded. These clips will have thumbnails and media_url set to ``None`` :returns: Iterator of :class:`~xbox.Clip` in...
5.83129
2.526005
2.308503
if self.total is False and error: # Disabled, indicate to re-raise the error. raise six.reraise(type(error), error, _stacktrace) total = self.total if total is not None: total -= 1 _observed_errors = self._observed_errors connect = s...
def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None)
Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or No...
3.469931
3.243958
1.06966
# Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get('content-encoding', '').lower() if self._decoder is None: if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_deco...
def read(self, amt=None, decode_content=None, cache_content=False)
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full ...
4.630638
4.71769
0.981548
headers = HTTPHeaderDict() for k, v in r.getheaders(): headers.add(k, v) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) return ResponseCls(body=r, headers=headers, ...
def from_httplib(ResponseCls, r, **response_kw)
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``.
2.893319
2.861604
1.011083
self._data.setdefault(key.lower(), []).append((key, value))
def add(self, key, value)
Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz'
7.416365
10.09853
0.7344
if self.pos is not None: # Rewind the file position indicator of the body to where # it was to resend the request. r.request.body.seek(self.pos) num_401_calls = getattr(self, 'num_401_calls', 1) s_auth = r.headers.get('www-authenticate', '') ...
def handle_401(self, r, **kwargs)
Takes the given response and tries digest-auth, if needed.
3.235309
3.135191
1.031934
p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, params=self.params, auth=self.auth, cookies=self.cookies, hooks=...
def prepare(self)
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
2.064991
1.714117
1.204697
url = to_native_string(url) # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url ...
def prepare_url(self, url, params)
Prepares the given HTTP URL.
3.043638
2.98015
1.021303
# Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None length = None is_stream = all([ hasattr(data, '__iter__'), not isinstance(data, (basestring, list,...
def prepare_body(self, data, files)
Prepares the given HTTP body data.
3.760223
3.781941
0.994257
proxies = proxies or {} scheme = urlparse(request.url).scheme proxy = proxies.get(scheme) if proxy and scheme != 'https': url, _ = urldefrag(request.url) else: url = request.path_url return url
def request_url(self, request, proxies)
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the ...
3.816712
4.447332
0.858203
conn = self.get_connection(request.url, proxies) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request) chunked = not (request.body is None or 'Content-Length' in request.headers) if isinstance(tim...
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None)
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up...
2.674279
2.673264
1.00038
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I) xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') return (charset_re.findall(content) + pragma_re.findall(content) + ...
def get_encodings_from_content(content)
Returns encodings from given content string. :param content: bytestring to extract encodings from.
2.655602
2.594178
1.023677
if isinstance(conn, VerifiedHTTPSConnection): conn.set_cert(key_file=self.key_file, cert_file=self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs, assert_hostname=self.asser...
def _prepare_conn(self, conn)
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used.
3.078239
2.943253
1.045863
u = UniversalDetector() for line in file: u.feed(line) u.close() result = u.result if result['encoding']: return '%s: %s with confidence %s' % (name, result['encoding'], result['confidenc...
def description_of(file, name='stdin')
Return a string describing the probable encoding of a file.
3.346297
2.643026
1.266085
''' Download the video. ''' #Callback self._debug('Provider', 'run', 'Running pre-download callback.') self._pre_download() url = None out = None success = False try: url = Provider._download(self.get_download_url()) ...
def run(self)
Download the video.
3.710572
3.50361
1.059071
''' Serialize `obj` to a JSON formatted `str`. Accepts the same arguments as `json` module in stdlib. :param obj: a JSON serializable Python object. :param kwargs: all the arguments that `json.dumps <http://docs.python.org/ 2/library/json.html#json.dumps>`_ accepts. :raises: comm...
def dumps(obj, **kwargs)
Serialize `obj` to a JSON formatted `str`. Accepts the same arguments as `json` module in stdlib. :param obj: a JSON serializable Python object. :param kwargs: all the arguments that `json.dumps <http://docs.python.org/ 2/library/json.html#json.dumps>`_ accepts. :raises: commentjson....
4.85506
1.513608
3.207606
''' Deserialize `fp` (a `.read()`-supporting file-like object containing a JSON document with Python or JavaScript like comments) to a Python object. :param fp: a `.read()`-supporting file-like object containing a JSON document with or without comments. :param kwargs: all the arguments t...
def load(fp, **kwargs)
Deserialize `fp` (a `.read()`-supporting file-like object containing a JSON document with Python or JavaScript like comments) to a Python object. :param fp: a `.read()`-supporting file-like object containing a JSON document with or without comments. :param kwargs: all the arguments that `jso...
4.674409
1.483683
3.150544
''' Serialize `obj` as a JSON formatted stream to `fp` (a `.write()`-supporting file-like object). Accepts the same arguments as `json` module in stdlib. :param obj: a JSON serializable Python object. :param fp: a `.read()`-supporting file-like object containing a JSON document with ...
def dump(obj, fp, **kwargs)
Serialize `obj` as a JSON formatted stream to `fp` (a `.write()`-supporting file-like object). Accepts the same arguments as `json` module in stdlib. :param obj: a JSON serializable Python object. :param fp: a `.read()`-supporting file-like object containing a JSON document with or witho...
4.388299
1.515679
2.89527
@wraps(func) def prepend_prefix(self, name, *args, **kwargs): name = self.name_prefix + name return func(self, name, *args, **kwargs) return prepend_prefix
def prepend_name_prefix(func)
Decorator that wraps instance methods to prepend the instance's filename prefix to the beginning of the referenced filename. Must only be used on instance methods where the first parameter after `self` is `name` or a comparable parameter of a different name.
1.969434
2.24887
0.875744
if level >= logging.ERROR: _chalk = chalk.red elif level >= logging.WARNING: _chalk = chalk.yellow elif level >= logging.INFO: _chalk = chalk.blue elif level >= logging.DEBUG: _chalk = chalk.green else: _chalk = chalk.white return _chalk
def get_chalk(level)
Gets the appropriate piece of chalk for the logging level
1.651167
1.657493
0.996183
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes): obj = obj.decode('utf-8') return obj if isinstance(obj, string_types) else str(obj)
def to_str(obj)
Attempts to convert given object to a string object
2.945709
2.718966
1.083393
if value in COLOR_SET: value = COLOR_MAP[value] else: try: value = int(value) if value >= 8: raise ValueError() except ValueError as exc: raise ValueError( 'Colors should ...
def get_color(self, value)
Helper method to validate and map values used in the instantiation of of the Color object to the correct unicode value.
5.056767
4.891829
1.033717
for n in range(start, 2**64): yield f(nonce, n) while True: for n in range(0, 2**64): yield f(nonce, n)
def ctr_counter(nonce, f, start = 0)
Return an infinite iterator that starts at `start` and iterates by 1 over integers between 0 and 2^64 - 1 cyclically, returning on each iteration the result of combining each number with `nonce` using function `f`. `nonce` should be an random 64-bit integer that is used to make the counter unique. `f` s...
2.979438
2.836925
1.050235
S0, S1, S2, S3 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack try: L, R = self._u4_2_unpack(block) except struct_error: raise ValueError("block is not 8 bytes in length") for p1, p2 in P[:-1]: L ^= p1 a, b, c, d = u...
def encrypt_block(self, block)
Return a :obj:`bytes` object containing the encrypted bytes of a `block`. `block` should be a :obj:`bytes`-like object with exactly 8 bytes. If it is not, a :exc:`ValueError` exception is raised.
2.944315
2.849799
1.033166
S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack encrypt = self._encrypt u4_2_pack = self._u4_2_pack try: LR_iter = self._u4_2_iter_unpack(data) except struct_error: raise ValueError("data is not a multiple of ...
def encrypt_ecb(self, data)
Return an iterator that encrypts `data` using the Electronic Codebook (ECB) mode of operation. ECB mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes) containing the encrypted bytes of the c...
4.095394
3.578621
1.144406
S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack decrypt = self._decrypt u4_2_pack = self._u4_2_pack try: LR_iter = self._u4_2_iter_unpack(data) except struct_error: raise ValueError("data is not a multiple of ...
def decrypt_ecb(self, data)
Return an iterator that decrypts `data` using the Electronic Codebook (ECB) mode of operation. ECB mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes) containing the decrypted bytes of the c...
3.978639
3.462814
1.148961
data_len = len(data) if data_len <= 8: raise ValueError("data is not greater than 8 bytes in length") S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack u4_2_pack = self._u4_2_pack u4_2_unpack = self._u4_2_unpack encr...
def encrypt_ecb_cts(self, data)
Return an iterator that encrypts `data` using the Electronic Codebook with Ciphertext Stealing (ECB-CTS) mode of operation. ECB-CTS mode can only operate on `data` that is greater than 8 bytes in length. Each iteration, except the last, always returns a block-sized :obj:`bytes` object (i.e...
2.267165
2.134449
1.062178
data_len = len(data) if data_len <= 8: raise ValueError("data is not greater than 8 bytes in length") S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack u4_2_pack = self._u4_2_pack u4_2_unpack = self._u4_2_unpack decr...
def decrypt_ecb_cts(self, data)
Return an iterator that decrypts `data` using the Electronic Codebook with Ciphertext Stealing (ECB-CTS) mode of operation. ECB-CTS mode can only operate on `data` that is greater than 8 bytes in length. Each iteration, except the last, always returns a block-sized :obj:`bytes` object (i.e...
2.257214
2.136682
1.056411
S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack encrypt = self._encrypt u4_2_pack = self._u4_2_pack try: prev_cipher_L, prev_cipher_R = self._u4_2_unpack(init_vector) except struct_error: raise ValueError("ini...
def encrypt_cbc(self, data, init_vector)
Return an iterator that encrypts `data` using the Cipher-Block Chaining (CBC) mode of operation. CBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes) containing the encrypted bytes of the...
2.935826
2.769547
1.060038
S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack decrypt = self._decrypt u4_2_pack = self._u4_2_pack try: prev_cipher_L, prev_cipher_R = self._u4_2_unpack(init_vector) except struct_error: raise ValueError("ini...
def decrypt_cbc(self, data, init_vector)
Return an iterator that decrypts `data` using the Cipher-Block Chaining (CBC) mode of operation. CBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes) containing the decrypted bytes of the...
2.889214
2.748218
1.051304
data_len = len(data) if data_len <= 8: raise ValueError("data is not greater than 8 bytes in length") S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack u4_2_pack = self._u4_2_pack u4_2_unpack = self._u4_2_unpack encryp...
def encrypt_cbc_cts(self, data, init_vector)
Return an iterator that encrypts `data` using the Cipher-Block Chaining with Ciphertext Stealing (CBC-CTS) mode of operation. CBC-CTS mode can only operate on `data` that is greater than 8 bytes in length. Each iteration, except the last, always returns a block-sized :obj:`bytes` object (i...
2.121869
2.044555
1.037815
data_len = len(data) if data_len <= 8: raise ValueError("data is not greater than 8 bytes in length") S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack u4_2_pack = self._u4_2_pack u4_2_unpack = self._u4_2_unpack decryp...
def decrypt_cbc_cts(self, data, init_vector)
Return an iterator that decrypts `data` using the Cipher-Block Chaining with Ciphertext Stealing (CBC-CTS) mode of operation. CBC-CTS mode can only operate on `data` that is greater than 8 bytes in length. Each iteration, except the last, always returns a block-sized :obj:`bytes` object (i...
2.156559
2.100894
1.026496
S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack encrypt = self._encrypt u4_2_pack = self._u4_2_pack try: init_L, init_R = self._u4_2_unpack(init_vector) except struct_error: raise ValueError("initialization ve...
def encrypt_pcbc(self, data, init_vector)
Return an iterator that encrypts `data` using the Propagating Cipher-Block Chaining (PCBC) mode of operation. PCBC mode can only operate on `data` that is a multiple of the block-size in length. Each iteration returns a block-sized :obj:`bytes` object (i.e. 8 bytes) containing the encrypte...
2.886671
2.657442
1.086259
S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack encrypt = self._encrypt u4_2_pack = self._u4_2_pack data_len = len(data) extra_bytes = data_len % 8 last_block_stop_i = data_len - extra_bytes try: prev_c...
def encrypt_cfb(self, data, init_vector)
Return an iterator that encrypts `data` using the Cipher Feedback (CFB) mode of operation. CFB mode can operate on `data` of any length. Each iteration, except the last, always returns a block-sized :obj:`bytes` object (i.e. 8 bytes). The last iteration may return a :obj:`bytes` object wit...
2.469019
2.427017
1.017306
S1, S2, S3, S4 = self.S P = self.P u4_1_pack = self._u4_1_pack u1_4_unpack = self._u1_4_unpack encrypt = self._encrypt u4_2_pack = self._u4_2_pack u4_2_unpack = self._u4_2_unpack u8_1_pack = self._u8_1_pack data_len = len(data) extra_bytes = data_len % 8 ...
def encrypt_ctr(self, data, counter)
Return an iterator that encrypts `data` using the Counter (CTR) mode of operation. CTR mode can operate on `data` of any length. Each iteration, except the last, always returns a block-sized :obj:`bytes` object (i.e. 8 bytes). The last iteration may return a :obj:`bytes` object with a leng...
2.390632
2.239021
1.067713
_im = im if self.image_property: _im = self.image_property.convert(im) return _im
def convert(self, im)
Please override this method if you want to resize/grascale the image.
6.007826
4.539574
1.323434
if overwrite: shuffled = self.path else: shuffled = FileAPI.add_ext_name(self.path, "_shuffled") lines = open(self.path).readlines() random.shuffle(lines) open(shuffled, "w").writelines(lines) self.path = shuffled
def shuffle(self, overwrite=False)
This method creates new shuffled file.
3.536225
3.180886
1.111711
# type: (Iterable[str], Namespace) -> OrderedDict[str, List[pd.DataFrame]] bed_windows = OrderedDict() # type: OrderedDict[str, List[pd.DataFrame]] for bed_file in bed_files: logging.info("Binning " + bed_file) if ".bedpe" in bed_file: chromosome_dfs = count_reads_in_window...
def multiple_files_count_reads_in_windows(bed_files, args)
Use count_reads on multiple files and store result in dict. Untested since does the same thing as count reads.
2.908112
3.115959
0.933296
# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame # windows is a list of chromosome dfs per file windows = iter(windows) # can iterate over because it is odict_values merged = next(windows) # if there is only one file, the merging is skipped since the windows is used up for chromosom...
def _merge_files(windows, nb_cpu)
Merge lists of chromosome bin df chromosome-wise. windows is an OrderedDict where the keys are files, the values are lists of dfs, one per chromosome. Returns a list of dataframes, one per chromosome, with the collective count per bin for all files. TODO: is it faster to merge all in one command?
8.579396
8.56894
1.00122
# type: (Dict[int, float], int) -> float cumulative = [0.0] * (total_length + 1) partial_sum = 0.0 island_expectations = [] for i in range(len(cumulative)): if i in island_expectations_d: island_expectations.append(island_expectations_d[i]) else: island...
def generate_cumulative_dist(island_expectations_d, total_length)
Generate cumulative distribution: a list of tuples (bins, hist).
2.855467
2.858593
0.998906
if value > 0: return float(floor(float(value)+0.5)) else: return float(ceil(float(value)-0.5))
def py2round(value)
Round values as in Python 2, for Python 3 compatibility. All x.5 values are rounded away from zero. In Python 3, this has changed to avoid bias: when x is even, rounding is towards zero, when x is odd, rounding is away from zero. Thus, in Python 3, round(2.5) results in 2, round(3.5) is 4. Py...
2.508038
3.240706
0.773917
if not interval.discrete: raise TypeError('Only discrete ranges can be canonicalized') if interval.empty: return interval lower, lower_inc = canonicalize_lower(interval, lower_inc) upper, upper_inc = canonicalize_upper(interval, upper_inc) return interval.__class__( [...
def canonicalize(interval, lower_inc=True, upper_inc=False)
Convert equivalent discrete intervals to different representations.
2.623366
2.510406
1.044997
return self.__class__( [ min(self.lower, other.lower), min(self.upper, other.upper) ], lower_inc=self.lower_inc if self < other else other.lower_inc, upper_inc=self.upper_inc if self > other else other.upper_inc, )
def glb(self, other)
Return the greatest lower bound for given intervals. :param other: AbstractInterval instance
2.593127
2.547476
1.01792
return self.__class__( [ max(self.lower, other.lower), max(self.upper, other.upper), ], lower_inc=self.lower_inc if self < other else other.lower_inc, upper_inc=self.upper_inc if self > other else other.upper_inc, )
def lub(self, other)
Return the least upper bound for given intervals. :param other: AbstractInterval instance
2.313256
2.464857
0.938495
return self.upper > other.lower and other.upper > self.lower or ( self.upper == other.lower and (self.upper_inc or other.lower_inc) ) or ( self.lower == other.upper and (self.lower_inc or other.upper_inc) )
def is_connected(self, other)
Returns ``True`` if there exists a (possibly empty) range which is enclosed by both this range and other. Examples: * [1, 3] and [5, 7] are not connected * [5, 7] and [1, 3] are not connected * [2, 4) and [3, 5) are connected, because both enclose [3, 4) * [1, 3) and [3...
2.957722
2.978992
0.99286
# type: (float) -> int current_threshold, survival_function = 0, 1 for current_threshold in count(start=0, step=1): survival_function -= poisson.pmf(current_threshold, average_window_readcount) if survival_function <= WINDOW_P_VALUE: ...
def compute_enriched_threshold(average_window_readcount)
Computes the minimum number of tags required in window for an island to be enriched.
4.757335
4.411224
1.078462
# type: (int) -> float if num < 20: log_factorial = log(factorial(num)) else: log_factorial = num * log(num) - num + log(num * (1 + 4 * num * ( 1 + 2 * num))) / 6.0 + log(pi) / 2 return log_factorial
def _factln(num)
Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise.
4.510923
4.108151
1.098042
dfs = _remove_epic_enriched(dfs) names = ["Enriched_" + os.path.basename(r) for r in region_files] regions = region_files_to_bins(region_files, names, bin_size) new_dfs = OrderedDict() assert len(regions.columns) == len(dfs) for region, (n, df) in zip(regions, dfs.items()): r...
def add_new_enriched_bins_matrixes(region_files, dfs, bin_size)
Add enriched bins based on bed files. There is no way to find the correspondence between region file and matrix file, but it does not matter.
3.957447
4.088064
0.968049
# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame plus_df, minus_df = df_tuple index_cols = "Chromosome Bin".split() count_column = plus_df.columns[0] if plus_df.empty: return return_other(minus_df, count_column, index_cols) if minus_df.empty: return return_other...
def merge_chromosome_dfs(df_tuple)
Merges data from the two strands into strand-agnostic counts.
2.736221
2.639924
1.036477
# type: (pd.DataFrame, int) -> pd.DataFrame # The dataframe is empty and contains no bins out of bounds if "Bin" not in df: return df df = df.drop(df[df.Bin > chromosome_size].index) return df.drop(df[df.Bin < 0].index)
def remove_out_of_bounds_bins(df, chromosome_size)
Remove all reads that were shifted outside of the genome endpoints.
4.053652
4.384828
0.924472
# type: (pd.DataFrame, int, int) -> pd.DataFrame # The dataframe is empty and contains no bins out of bounds # print(df.head(2)) # print(chromosome_size) # print(window_size) out_of_bounds = df[df.index.get_level_values("Bin") + window_size > chromosome_size].index ...
def remove_bins_with_ends_out_of_bounds(df, chromosome_size, window_size)
Remove all reads that were shifted outside of the genome endpoints.
3.434752
3.567168
0.962879
# type: (pd.DataFrame, str, Namespace) -> None call("mkdir -p {}".format(outdir), shell=True) genome_size_dict = args.chromosome_sizes outpaths = [] for bed_file in matrix[args.treatment]: outpath = join(outdir, splitext(basename(bed_file))[0] + "_log2fc.bw") outpaths.append(o...
def create_log2fc_bigwigs(matrix, outdir, args)
Create bigwigs from matrix.
3.438385
3.400876
1.011029
# type: ( float, int, float, Dict[int, float], float) -> Dict[int, float] scaled_score = current_max_scaled_score + E_VALUE for index in range(current_max_scaled_score + 1, scaled_score + 1): island_expectation = 0.0 i = island_eligibility_threshold #i is the number of tags in the add...
def add_to_island_expectations_dict(average_window_readcount, current_max_scaled_score, island_eligibility_threshold, island_expectations, gap_contribution)
Can probably be heavily optimized. Time required to run can be seen from logging info.
3.091835
3.271341
0.945128
# type: (str, int, int, str) -> None idx = Fasta(fasta) genome_length = sum([len(c) for c in idx]) logging.info("Temporary directory: " + tmpdir) logging.info("File analyzed: " + fasta) logging.info("Genome length: " + str(genome_length)) print("File analyzed: ", fasta) print("Ge...
def effective_genome_size(fasta, read_length, nb_cores, tmpdir="/tmp")
Compute effective genome size for genome.
3.176292
3.161093
1.004808
# type: (Iterable[pd.DataFrame], Iterable[pd.DataFrame], pd.DataFrame, Namespace) -> List[pd.DataFrame] "Creates matrixes which can be written to file as is (matrix) or as bedGraph." genome = args.chromosome_sizes chip = put_dfs_in_chromosome_dict(chip) input = put_dfs_in_chromosome_dict(input) ...
def create_matrixes(chip, input, df, args)
Creates matrixes which can be written to file as is (matrix) or as bedGraph.
4.663539
3.65601
1.275582
# type: (pd.DataFrame, int, str, Namespace) -> Dict[str, Set[int]] # need these chromos because the df might not have islands in all chromos chromosomes = natsorted(list(args.chromosome_sizes)) chromosome_island_bins = {} # type: Dict[str, Set[int]] df_copy = df.reset_index(drop=False) fo...
def get_island_bins(df, window_size, genome, args)
Finds the enriched bins in a df.
3.177572
3.218664
0.987233
# type: (str) -> Dict[str,int] size_file = get_genome_size_file(genome) size_lines = open(size_file).readlines() size_dict = {} for line in size_lines: genome, length = line.split() size_dict[genome] = int(length) return size_dict
def create_genome_size_dict(genome)
Creates genome size dict from string containing data.
2.631034
2.652196
0.992021
# type: (float, int, float, float, float) -> float required_p_value = poisson.pmf(island_enriched_threshold, average_window_readcount) prob = boundary_contribution * required_p_value score = -log(required_p_value) current_scaled_score = int(round(score / B...
def compute_score_threshold(average_window_readcount, island_enriched_threshold, gap_contribution, boundary_contribution, genome_length_in_bins)
What does island_expectations do?
3.200774
3.121953
1.025248
# type: (Namespace) -> int try: bed_file = args.treatment[0] except AttributeError: bed_file = args.infiles[0] filereader = "cat " if bed_file.endswith(".gz") and search("linux", platform, IGNORECASE): filereader = "zcat " elif bed_file.endswith(".gz") and search("...
def find_readlength(args)
Estimate length of reads based on 10000 first.
2.853246
2.818063
1.012485
# type: (int) -> int readlengths = [36, 50, 75, 100] differences = [abs(r - estimated_readlength) for r in readlengths] min_difference = min(differences) index_of_min_difference = [i for i, d in enumerate(differences) if d == min_di...
def get_closest_readlength(estimated_readlength)
Find the predefined readlength closest to the estimated readlength. In the case of a tie, choose the shortest readlength.
2.600154
2.83978
0.915618
values = value.strip().split('-') values = list(map(strip, values)) if len(values) == 1: lower = upper = value.strip() elif len(values) == 2: lower, upper = values if lower == '': # Parse range such as '-3' uppe...
def parse_hyphen_range(self, value)
Parse hyphen ranges such as: 2 - 5, -2 - -1, -3 - 5
3.773914
3.587384
1.051996
for x in output.splitlines(): match = VERSION_PATTERN.match(x) if match: return match.group('version').strip() return None
def parse_version(output)
Parses the supplied output and returns the version string. :param output: A string containing the output of running snort. :returns: Version string for the version of snort run. None if not found.
3.246067
3.748747
0.865907
for x in output.splitlines(): match = ALERT_PATTERN.match(x) if match: rec = {'timestamp': datetime.strptime(match.group('timestamp'), '%m/%d/%y-%H:%M:%S.%f'), 'sid': int(match.group('sid')), 're...
def parse_alert(output)
Parses the supplied output and yields any alerts. Example alert format: 01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900 :param output: A string containing...
2.411494
2.311823
1.043114
cmdline = "'{0}' -A console -N -y -c '{1}' {2} -r '{3}'" \ .format(self.conf['path'], self.conf['config'], self.conf['extra_args'] or '', pcap) # can't seem to capture stderr from snort on windows # unless launched via cmd shell if 'nt' in os.name...
def _snort_cmd(self, pcap)
Given a pcap filename, get the commandline to run. :param pcap: Pcap filename to scan :returns: list of snort command args to scan supplied pcap file
6.006741
6.871238
0.874186
proc = Popen(self._snort_cmd(pcap), stdout=PIPE, stderr=PIPE, universal_newlines=True) stdout, stderr = proc.communicate() if proc.returncode != 0: raise Exception("\n".join(["Execution failed return code: {0}" \ .format(p...
def run(self, pcap)
Runs snort against the supplied pcap. :param pcap: Filepath to pcap file to scan :returns: tuple of version, list of alerts
5.056456
4.244489
1.191299
cmdline = "'{0}' -c '{1}' -l '{2}' {3} -r '{4}'" \ .format(self.conf['path'], self.conf['config'], logs, self.conf['extra_args'] or '', pcap) # can't seem to capture stderr on windows # unless launched via cmd shell if 'nt' in os.name: ...
def _suri_cmd(self, pcap, logs)
Given a pcap filename, get the commandline to run. :param pcap: Pcap filename to scan :param logs: Output directory for logs :returns: list of command args to scan supplied pcap file
5.295883
6.159895
0.859736
tmpdir = None try: tmpdir = tempfile.mkdtemp(prefix='tmpsuri') proc = Popen(self._suri_cmd(pcap, tmpdir), stdout=PIPE, stderr=PIPE, universal_newlines=True) stdout, stderr = proc.communicate() if proc.returncode != 0: ...
def run(self, pcap)
Runs suricata against the supplied pcap. :param pcap: Filepath to pcap file to scan :returns: tuple of version, list of alerts
4.169711
3.78571
1.101434
tmp = tempfile.NamedTemporaryFile(suffix=".pcap", delete=False) m = hashlib.md5() results = {'filename': filename, 'status': 'Failed', 'apiversion': __version__, } try: size = 0 while True: buf = infile.read(16384) ...
def analyse_pcap(infile, filename)
Run IDS across the supplied file. :param infile: File like object containing pcap data. :param filename: Filename of the submitted file. :returns: Dictionary of analysis results.
2.801572
2.84331
0.985321
data = request.files.file template = env.get_template("results.html") if not data: pass results = analyse_pcap(data.file, data.filename) results.update(base) return template.render(results)
def submit_and_render()
Blocking POST handler for file submission. Runs snort on supplied file and returns results as rendered html.
8.083847
5.780334
1.398509
data = request.files.file response.content_type = 'application/json' if not data or not hasattr(data, 'file'): return json.dumps({"status": "Failed", "stderr": "Missing form params"}) return json.dumps(analyse_pcap(data.file, data.filename), default=jsondate, indent=4)
def api_submit()
Blocking POST handler for file submission. Runs snort on supplied file and returns results as json text.
6.122885
5.320906
1.150722
parser = argparse.ArgumentParser() parser.add_argument("-H", "--host", help="Web server Host address to bind to", default="0.0.0.0", action="store", required=False) parser.add_argument("-p", "--port", help="Web server Port to bind to", default=8080, actio...
def main()
Main entrypoint for command-line webserver.
2.453644
2.297487
1.067968
if not end: end = datetime.now() td = end - start return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1000000) \ / 1000000.0
def duration(start, end=None)
Returns duration in seconds since supplied time. Note: time_delta.total_seconds() only available in python 2.7+ :param start: datetime object :param end: Optional end datetime, None = now :returns: Seconds as decimal since start
2.082915
2.175467
0.957457
with open(pcap, 'rb') as tmp: header = tmp.read(4) # check for both big/little endian if header == b"\xa1\xb2\xc3\xd4" or \ header == b"\xd4\xc3\xb2\xa1": return True return False
def is_pcap(pcap)
Simple test for pcap magic bytes in supplied file. :param pcap: File path to Pcap file to check :returns: True if content is pcap (magic bytes present), otherwise False.
3.000587
3.080273
0.97413
run = {'name': runner.conf.get('name'), 'module': runner.conf.get('module'), 'ruleset': runner.conf.get('ruleset', 'default'), 'status': STATUS_FAILED, } try: run_start = datetime.now() version, alerts = runner.run(pcap) run['version'] = v...
def _run_ids(runner, pcap)
Runs the specified IDS runner. :param runner: Runner instance to use :param pcap: File path to pcap for analysis :returns: dict of run metadata/alerts
3.41026
3.534277
0.96491
start = datetime.now() errors = [] status = STATUS_FAILED analyses = [] pool = ThreadPool(MAX_THREADS) try: if not is_pcap(pcap): raise Exception("Not a valid pcap file") runners = [] for conf in Config().modules.values(): runner = registry.g...
def run(pcap)
Runs all configured IDS instances against the supplied pcap. :param pcap: File path to pcap file to analyse :returns: Dict with details and results of run/s
3.71696
3.515575
1.057284
''' Helper to configure pool options during DatabaseWrapper initialization. ''' self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS']) self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns) self._test_on_bor...
def _set_up_pool_config(self)
Helper to configure pool options during DatabaseWrapper initialization.
2.768751
2.12097
1.305417
''' Helper to initialize the connection pool. ''' connection_pools_lock.acquire() try: # One more read to prevent a read/write race condition (We do this # here to avoid the overhead of locking each time we get a connection.) if (self.alias not in connection_pools or ...
def _create_connection_pool(self, conn_params)
Helper to initialize the connection pool.
3.637441
3.40045
1.069694
''' Override to return the connection to the pool rather than closing it. ''' if self._wrapped_connection and self._pool: logger.debug("Returning connection %s to pool %s" % (self._wrapped_connection, self._pool)) self._pool.putconn(self._wrapped_connection) ...
def close(self)
Override to return the connection to the pool rather than closing it.
3.593527
2.406528
1.493242
''' Override _cursor to plug in our connection pool code. We'll return a wrapped Connection which can handle returning itself to the pool when its .close() method is called. ''' from django.db.backends.postgresql.version import get_version new_connection = False ...
def _cursor(self)
Override _cursor to plug in our connection pool code. We'll return a wrapped Connection which can handle returning itself to the pool when its .close() method is called.
4.029233
3.493508
1.153349
'''Encode an integer using Base58''' if not i and default_one: return alphabet[0] string = "" while i: i, idx = divmod(i, 58) string = alphabet[idx] + string return string
def b58encode_int(i, default_one=True)
Encode an integer using Base58
2.687543
2.931769
0.916696
'''Encode a string using Base58''' if not isinstance(v, bytes): raise TypeError("a bytes-like object is required, not '%s'" % type(v).__name__) origlen = len(v) v = v.lstrip(b'\0') newlen = len(v) p, acc = 1, 0 for c in iseq(reversed(v)): acc += p * ...
def b58encode(v)
Encode a string using Base58
3.236784
3.330609
0.97183
'''Decode a Base58 encoded string as an integer''' if not isinstance(v, str): v = v.decode('ascii') decimal = 0 for char in v: decimal = decimal * 58 + alphabet.index(char) return decimal
def b58decode_int(v)
Decode a Base58 encoded string as an integer
3.096032
3.142544
0.985199
'''Decode a Base58 encoded string''' if not isinstance(v, str): v = v.decode('ascii') origlen = len(v) v = v.lstrip(alphabet[0]) newlen = len(v) acc = b58decode_int(v) result = [] while acc > 0: acc, mod = divmod(acc, 256) result.append(mod) return (b'\0'...
def b58decode(v)
Decode a Base58 encoded string
2.739421
2.902648
0.943766
append_breadcrumb(context, _(escape(label)), viewname, args, kwargs) return ''
def breadcrumb(context, label, viewname, *args, **kwargs)
Add link to list of breadcrumbs, usage: {% load bubbles_breadcrumbs %} {% breadcrumb "Home" "index" %} Remember to use it inside {% block %} with {{ block.super }} to get all parent breadcrumbs. :param label: Breadcrumb link label. :param viewname: Name of the view to link this breadcrumb to,...
8.852269
38.715858
0.228647
append_breadcrumb(context, _(label), viewname, args, kwargs) return ''
def breadcrumb_safe(context, label, viewname, *args, **kwargs)
Same as breadcrumb but label is not escaped.
7.933445
7.636969
1.038821
append_breadcrumb(context, escape(label), viewname, args, kwargs) return ''
def breadcrumb_raw(context, label, viewname, *args, **kwargs)
Same as breadcrumb but label is not translated.
7.482715
8.030176
0.931824