repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
fakedrake/overlay_parse | overlay_parse/matchers.py | MatcherMatcher.offset_overlays | python | def offset_overlays(self, text, run_matchers=None, **kw):
self._maybe_run_matchers(text, run_matchers)
for i in self._list_match.offset_overlays(text, **kw):
yield i | First all matchers will run and then I will try to combine
them. Use run_matchers to force running(True) or not
running(False) the matchers.
See ListMatcher for arguments. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/matchers.py#L241-L252 | [
"def _maybe_run_matchers(self, text, run_matchers):\n \"\"\"\n OverlayedText should be smart enough to not run twice the same\n matchers but this is an extra handle of control over that.\n \"\"\"\n\n if run_matchers is True or \\\n (run_matchers is not False and text not in self._overlayed_alre... | class MatcherMatcher(BaseMatcher):
"""
Match the matchers.
"""
def __init__(self, matchers, props=None, value_fn=None):
self.matchers = matchers
self.props = props
self.value_fn = value_fn
self._list_match = ListMatcher(
[OverlayMatcher(m.props) for m in ma... |
fakedrake/overlay_parse | overlay_parse/dates.py | date_tuple | python | def date_tuple(ovls):
day = month = year = 0
for o in ovls:
if 'day' in o.props:
day = o.value
if 'month' in o.props:
month = o.value
if 'year' in o.props:
year = o.value
if 'date' in o.props:
day, month, year = [(o or n) for o,... | We should have a list of overlays from which to extract day month
year. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/dates.py#L57-L78 | null | # -*- coding: utf-8 -*-
from datetime import date
import re
import itertools
from .overlays import OverlayedText
from .matchers import mf
from .util import w, words, starts_with, rx_int, rx_int_extra, Rng
def month_names(rxmatch):
for i, m in enumerate(MONTH_NAMES_LONG):
if starts_with(m, rxmatch.group... |
fakedrake/overlay_parse | overlay_parse/dates.py | longest_overlap | python | def longest_overlap(ovls):
# Ovls know how to compare to each other.
ovls = sorted(ovls)
# I know this could be better but ovls wont be more than 50 or so.
for i, s in enumerate(ovls):
passing = True
for l in ovls[i + 1:]:
if s.start in Rng(l.start, l.end, rng=(True, True)... | From a list of overlays if any overlap keep the longest. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/dates.py#L81-L100 | null | # -*- coding: utf-8 -*-
from datetime import date
import re
import itertools
from .overlays import OverlayedText
from .matchers import mf
from .util import w, words, starts_with, rx_int, rx_int_extra, Rng
def month_names(rxmatch):
for i, m in enumerate(MONTH_NAMES_LONG):
if starts_with(m, rxmatch.group... |
fakedrake/overlay_parse | overlay_parse/overlays.py | Overlay.copy | python | def copy(self, props=None, value=None):
return Overlay(self.text,
(self.start, self.end),
props=props or self.props,
value=value or self.value) | Copy the Overlay possibly overriding props. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L41-L49 | null | class Overlay(object):
def __init__(self, text, rng, props=None, value=None):
"""
:param text: The text this overlay refers to.
:param start: The starting index of the overlay.
:param end: The end index of the overlay.
:param props: A list of strings that are the properties ... |
fakedrake/overlay_parse | overlay_parse/overlays.py | Overlay.match | python | def match(self, props=None, rng=None, offset=None):
if rng:
s, e = rng
else:
e = s = None
return ((e is None or self.end == e) and
(s is None or self.start == s)) and \
(props is None or props.issubset(self.props)) and \
(offset i... | Provide any of the args and match or dont.
:param props: Should be a subset of my props.
:param rng: Exactly match my range.
:param offset: I start after this offset.
:returns: True if all the provided predicates match or are None | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L106-L124 | null | class Overlay(object):
def __init__(self, text, rng, props=None, value=None):
"""
:param text: The text this overlay refers to.
:param start: The starting index of the overlay.
:param end: The end index of the overlay.
:param props: A list of strings that are the properties ... |
fakedrake/overlay_parse | overlay_parse/overlays.py | OverlayedText.overlays_at | python | def overlays_at(self, key):
if isinstance(key, slice):
s, e, _ = key.indices(len(self.text))
else:
s = e = key
return [o for o in self.overlays if o.start in Rng(s, e)] | Key may be a slice or a point. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L164-L174 | null | class OverlayedText(object):
"""
Both the text and it's overlays.
"""
def __init__(self, text, overlays=None):
self.text = text
self.overlays = overlays or []
self._ran_matchers = []
def copy(self):
t = OverlayedText(self.text, [o.copy() for o in self.overlays])
... |
fakedrake/overlay_parse | overlay_parse/overlays.py | OverlayedText.overlay | python | def overlay(self, matchers, force=False):
for m in matchers:
if m in self._ran_matchers:
continue
self._ran_matchers.append(m)
self.overlays += list(m.offset_overlays(self))
self.overlays.sort(key=lambda o: o.start, reverse=True) | Given a list of matchers create overlays based on them. Normally I
will remember what overlays were run this way and will avoid
re-running them but you can `force` me to. This is the
recommended way of running overlays.c | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L176-L191 | null | class OverlayedText(object):
"""
Both the text and it's overlays.
"""
def __init__(self, text, overlays=None):
self.text = text
self.overlays = overlays or []
self._ran_matchers = []
def copy(self):
t = OverlayedText(self.text, [o.copy() for o in self.overlays])
... |
fakedrake/overlay_parse | overlay_parse/overlays.py | OverlayedText.get_overlays | python | def get_overlays(self, **kw):
return [o for o in self.overlays if o.match(**kw)] | See Overlay.match() for arguments. | train | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L193-L198 | null | class OverlayedText(object):
"""
Both the text and it's overlays.
"""
def __init__(self, text, overlays=None):
self.text = text
self.overlays = overlays or []
self._ran_matchers = []
def copy(self):
t = OverlayedText(self.text, [o.copy() for o in self.overlays])
... |
tagcubeio/tagcube-cli | tagcube_cli/subcommands/batch.py | create_scans | python | def create_scans(urls_file):
cli_logger.debug('Starting to process batch input file')
created_scans = []
for line in urls_file:
line = line.strip()
if line.startswith('#'):
continue
if not line:
continue
try:
protocol, domain, port, pat... | This method is rather simple, it will group the urls to be scanner together
based on (protocol, domain and port).
:param urls_file: The filename with all the URLs
:return: A list of scans to be run | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/subcommands/batch.py#L23-L61 | null | from urlparse import urlparse
from tagcube_cli.logger import cli_logger
def do_batch_scan(client, cmd_args):
if not client.test_auth_credentials():
raise ValueError('Invalid TagCube REST API credentials.')
cli_logger.debug('Authentication credentials are valid')
for scan in create_scans(cmd_args... |
tagcubeio/tagcube-cli | tagcube_cli/subcommands/batch.py | parse_url | python | def parse_url(url):
split_url = url.split('/', 3)
if len(split_url) == 3:
# http://foo.com
path = '/'
elif len(split_url) == 4:
path = '/' + split_url[3]
else:
raise ValueError('Invalid URL: %s' % url)
try:
parse_result = urlparse(url)
except Exception:
... | Parse a URL into the parts I need for processing:
* protocol
* domain
* port
* path
:param url: A string
:return: A tuple containing the above | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/subcommands/batch.py#L64-L110 | null | from urlparse import urlparse
from tagcube_cli.logger import cli_logger
def do_batch_scan(client, cmd_args):
if not client.test_auth_credentials():
raise ValueError('Invalid TagCube REST API credentials.')
cli_logger.debug('Authentication credentials are valid')
for scan in create_scans(cmd_args... |
tagcubeio/tagcube-cli | tagcube_cli/utils.py | parse_config_file | python | def parse_config_file():
for filename in ('.tagcube', os.path.expanduser('~/.tagcube')):
filename = os.path.abspath(filename)
if not os.path.exists(filename):
msg = 'TagCube configuration file "%s" does not exist'
cli_logger.debug(msg % filename)
continue
... | Find the .tagcube config file in the current directory, or in the
user's home and parse it. The one in the current directory has precedence.
:return: A tuple with:
- email
- api_token | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/utils.py#L38-L73 | [
"def _parse_config_file_impl(filename):\n \"\"\"\n Format for the file is:\n\n credentials:\n email: ...\n api_token: ...\n\n :param filename: The filename to parse\n :return: A tuple with:\n - email\n - api_token\n \"\"\"\n api_key = N... | import re
import os
import yaml
import argparse
from tagcube_cli.logger import cli_logger
INVALID_UUID = ('Invalid REST API key, the right format looks like'
' 208e57a8-1173-49c9-b5f3-e15535e70e83 (include the dashes and'
' verify length)')
INVALID_FILE = '''\
Invalid .tagcube configu... |
tagcubeio/tagcube-cli | tagcube_cli/utils.py | _parse_config_file_impl | python | def _parse_config_file_impl(filename):
api_key = None
email = None
try:
doc = yaml.load(file(filename).read())
email = doc['credentials']['email']
api_key = doc['credentials']['api_key']
except (KeyError, TypeError):
print(INVALID_FILE)
return None, None... | Format for the file is:
credentials:
email: ...
api_token: ...
:param filename: The filename to parse
:return: A tuple with:
- email
- api_token | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/utils.py#L76-L117 | [
"def is_valid_api_key(api_key):\n \"\"\"\n API keys are UUID4(), so we just check that the length and format is the\n expected one.\n\n :param api_key:\n :return:\n \"\"\"\n uuid_re = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'\n return bool(re.match(uuid_re, api_key))\n... | import re
import os
import yaml
import argparse
from tagcube_cli.logger import cli_logger
INVALID_UUID = ('Invalid REST API key, the right format looks like'
' 208e57a8-1173-49c9-b5f3-e15535e70e83 (include the dashes and'
' verify length)')
INVALID_FILE = '''\
Invalid .tagcube configu... |
tagcubeio/tagcube-cli | tagcube_cli/utils.py | is_valid_path | python | def is_valid_path(path):
if not path.startswith('/'):
msg = 'Invalid path "%s". Paths need to start with "/".'
raise ValueError(msg % path[:40])
for c in ' \t':
if c in path:
msg = ('Invalid character "%s" found in path. Paths need to be'
' URL-encoded.')
... | :return: True if the path is valid, else raise a ValueError with the
specific error | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/utils.py#L144-L159 | null | import re
import os
import yaml
import argparse
from tagcube_cli.logger import cli_logger
INVALID_UUID = ('Invalid REST API key, the right format looks like'
' 208e57a8-1173-49c9-b5f3-e15535e70e83 (include the dashes and'
' verify length)')
INVALID_FILE = '''\
Invalid .tagcube configu... |
tagcubeio/tagcube-cli | tagcube_cli/utils.py | path_file_to_list | python | def path_file_to_list(path_file):
paths = []
path_file_fd = file(path_file)
for line_no, line in enumerate(path_file_fd.readlines(), start=1):
line = line.strip()
if not line:
# Blank line support
continue
if line.startswith('#'):
# Comment supp... | :return: A list with the paths which are stored in a text file in a line-by-
line format. Validate each path using is_valid_path | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/utils.py#L205-L231 | [
"def is_valid_path(path):\n \"\"\"\n :return: True if the path is valid, else raise a ValueError with the\n specific error\n \"\"\"\n if not path.startswith('/'):\n msg = 'Invalid path \"%s\". Paths need to start with \"/\".'\n raise ValueError(msg % path[:40])\n\n for c in ... | import re
import os
import yaml
import argparse
from tagcube_cli.logger import cli_logger
INVALID_UUID = ('Invalid REST API key, the right format looks like'
' 208e57a8-1173-49c9-b5f3-e15535e70e83 (include the dashes and'
' verify length)')
INVALID_FILE = '''\
Invalid .tagcube configu... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.quick_scan | python | def quick_scan(self, target_url, email_notify=None,
scan_profile='full_audit', path_list=('/',)):
#
# Scan profile handling
#
scan_profile_resource = self.get_scan_profile(scan_profile)
if scan_profile_resource is None:
msg = 'The specified scan pro... | :param target_url: The target url e.g. https://www.tagcube.io/
:param email_notify: The notification email e.g. user@example.com
:param scan_profile: The name of the scan profile
:param path_list: The list of paths to use in the crawling bootstrap
The basic idea around this method is to... | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L97-L180 | [
"def get_domain_from_url(url):\n return urlparse.urlparse(url).netloc.split(':')[0]\n",
"def use_ssl(url):\n return url.lower().startswith('https://')",
"def get_port_from_url(url):\n if url.lower().startswith('http://'):\n default = '80'\n elif url.lower().startswith('https://'):\n de... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.low_level_scan | python | def low_level_scan(self, verification_resource, scan_profile_resource,
path_list, notification_resource_list):
data = {"verification_href": verification_resource.href,
"profile_href": scan_profile_resource.href,
"start_time": "now",
"email_n... | Low level implementation of the scan launch which allows you to start
a new scan when you already know the ids for the required resources.
:param verification_resource: The verification associated with the
domain resource to scan
:param scan_profile_resourc... | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L182-L218 | [
"def create_resource(self, url, data):\n \"\"\"\n Shortcut for creating a new resource\n :return: The newly created resource as a Resource object\n \"\"\"\n status_code, json_data = self.send_request(url, data, method='POST')\n\n if status_code != 201:\n msg = 'Expected 201 status code, got... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.verification_add | python | def verification_add(self, domain_resource_id, port, is_ssl):
data = {"domain_href": self.build_api_path('domains',
domain_resource_id),
"port": port,
"ssl": 'true' if is_ssl else 'false'}
url = self.build_full_url(self.V... | Sends a POST to /1.0/verifications/ using this post-data:
{"domain_href": "/1.0/domains/2",
"port":80,
"ssl":false}
:param domain_resource_id: The domain id to verify
:param port: The TCP port
:param is_ssl: Boolean indicating if we should use ssl
... | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L226-L245 | [
"def create_resource(self, url, data):\n \"\"\"\n Shortcut for creating a new resource\n :return: The newly created resource as a Resource object\n \"\"\"\n status_code, json_data = self.send_request(url, data, method='POST')\n\n if status_code != 201:\n msg = 'Expected 201 status code, got... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.filter_resource | python | def filter_resource(self, resource_name, field_name, field_value,
result_handler=ONE_RESULT):
return self.multi_filter_resource(resource_name,
{field_name: field_value},
result_handler=result_handler) | :return: The resource (as json), or None | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L276-L283 | [
"def multi_filter_resource(self, resource_name, filter_dict,\n result_handler=ONE_RESULT):\n url = self.build_full_url('/%s/?%s' % (resource_name,\n urllib.urlencode(filter_dict)))\n code, _json = self.send_request(url)\n\n if isinstance(_j... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.email_notification_add | python | def email_notification_add(self, notif_email, first_name='None',
last_name='None', description=DESCRIPTION):
data = {"email": notif_email,
"first_name": first_name,
"last_name": last_name,
"description": description}
url = se... | Sends a POST to /1.0/notifications/email/ using this post-data:
{"email": "andres.riancho@gmail.com",
"first_name": "Andres",
"last_name": "Riancho",
"description": "Notification email"}
:return: The id of the newly created email notification resource | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L291-L308 | [
"def create_resource(self, url, data):\n \"\"\"\n Shortcut for creating a new resource\n :return: The newly created resource as a Resource object\n \"\"\"\n status_code, json_data = self.send_request(url, data, method='POST')\n\n if status_code != 201:\n msg = 'Expected 201 status code, got... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.domain_add | python | def domain_add(self, domain, description=DESCRIPTION):
data = {"domain": domain,
"description": description}
url = self.build_full_url(self.DOMAINS)
return self.create_resource(url, data) | Sends a POST to /1.0/domains/ using this post-data:
{"domain": "www.fogfu.com",
"description":"Added by tagcube-api"}
:param domain: The domain name to add as a new resource
:return: The newly created resource | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L347-L360 | [
"def create_resource(self, url, data):\n \"\"\"\n Shortcut for creating a new resource\n :return: The newly created resource as a Resource object\n \"\"\"\n status_code, json_data = self.send_request(url, data, method='POST')\n\n if status_code != 201:\n msg = 'Expected 201 status code, got... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.get_scan | python | def get_scan(self, scan_id):
url = self.build_full_url('%s%s' % (self.SCANS, scan_id))
_, json_data = self.send_request(url)
return Resource(json_data) | :param scan_id: The scan ID as a string
:return: A resource containing the scan information | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L362-L369 | [
"def send_request(self, url, json_data=None, method='GET'):\n if method == 'GET':\n response = self.session.get(url, verify=self.verify)\n\n elif method == 'POST':\n data = json.dumps(json_data)\n response = self.session.post(url, data=data, verify=self.verify)\n\n else:\n raise... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.create_resource | python | def create_resource(self, url, data):
status_code, json_data = self.send_request(url, data, method='POST')
if status_code != 201:
msg = 'Expected 201 status code, got %s. Failed to create resource.'
raise TagCubeAPIException(msg % status_code)
try:
return Re... | Shortcut for creating a new resource
:return: The newly created resource as a Resource object | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L371-L388 | [
"def send_request(self, url, json_data=None, method='GET'):\n if method == 'GET':\n response = self.session.get(url, verify=self.verify)\n\n elif method == 'POST':\n data = json.dumps(json_data)\n response = self.session.post(url, data=data, verify=self.verify)\n\n else:\n raise... | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.handle_api_errors | python | def handle_api_errors(self, status_code, json_data):
error_list = []
if 'error' in json_data and len(json_data) == 1 \
and isinstance(json_data, dict) and isinstance(json_data['error'], list):
error_list = json_data['error']
elif status_code == 400:
for main_err... | This method parses all the HTTP responses sent by the REST API and
raises exceptions if required. Basically tries to find responses with
this format:
{
'error': ['The domain foo.com already exists.']
}
Or this other:
{
"scans"... | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L422-L460 | null | class TagCubeClient(object):
DEFAULT_ROOT_URL = 'https://api.tagcube.io/'
API_VERSION = '1.0'
SELF_URL = '/users/~'
DOMAINS = '/domains/'
SCANS = '/scans/'
VERIFICATIONS = '/verifications/'
SCAN_PROFILES = '/profiles/'
DESCRIPTION = 'Created by TagCube REST API client'
def __ini... |
tagcubeio/tagcube-cli | tagcube_cli/cli.py | TagCubeCLI.run | python | def run(self):
client = None
if self.cmd_args.subcommand in self.API_SUBCOMMAND:
email, api_key = TagCubeCLI.get_credentials(self.cmd_args)
client = TagCubeClient(email, api_key, verbose=self.cmd_args.verbose)
subcommands = {'auth': do_auth_test,
... | This method handles the user's command line arguments, for example, if
the user specified a path file we'll open it and read the contents.
Finally it will run the scan using TagCubeClient.scan(...)
:return: The exit code for our process | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/cli.py#L50-L81 | [
"def get_credentials(cmd_args):\n \"\"\"\n :return: The email and api_key to use to connect to TagCube. This\n function will try to get the credentials from:\n * Command line arguments\n * Environment variables\n * Configuration file\n\n It ... | class TagCubeCLI(object):
"""
The main class for the CLI:
* Receives parsed command line arguments
* Creates and configures a TagCubeClient instance
* Launches a scan
"""
API_SUBCOMMAND = {'auth', 'scan', 'batch'}
def __init__(self, cmd_args):
self.cmd_args = cmd_arg... |
tagcubeio/tagcube-cli | tagcube_cli/cli.py | TagCubeCLI.parse_args | python | def parse_args(args=None):
#
# The main parser
#
parser = argparse.ArgumentParser(prog='tagcube',
description=DESCRIPTION,
epilog=EPILOG)
#
# Parser for the common arguments
#
... | :return: The result of applying argparse to sys.argv | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/cli.py#L84-L215 | null | class TagCubeCLI(object):
"""
The main class for the CLI:
* Receives parsed command line arguments
* Creates and configures a TagCubeClient instance
* Launches a scan
"""
API_SUBCOMMAND = {'auth', 'scan', 'batch'}
def __init__(self, cmd_args):
self.cmd_args = cmd_arg... |
tagcubeio/tagcube-cli | tagcube_cli/cli.py | TagCubeCLI.get_credentials | python | def get_credentials(cmd_args):
# Check the cmd args, return if we have something here
cmd_credentials = cmd_args.email, cmd_args.key
if cmd_credentials != (None, None):
cli_logger.debug('Using command line configured credentials')
return cmd_credentials
env_email... | :return: The email and api_key to use to connect to TagCube. This
function will try to get the credentials from:
* Command line arguments
* Environment variables
* Configuration file
It will return the first match, in the ord... | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/cli.py#L259-L287 | null | class TagCubeCLI(object):
"""
The main class for the CLI:
* Receives parsed command line arguments
* Creates and configures a TagCubeClient instance
* Launches a scan
"""
API_SUBCOMMAND = {'auth', 'scan', 'batch'}
def __init__(self, cmd_args):
self.cmd_args = cmd_arg... |
tagcubeio/tagcube-cli | tagcube_cli/main.py | main | python | def main():
cmd_args = TagCubeCLI.parse_args()
try:
tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args)
except ValueError, ve:
# We get here when there are no credentials configured
print '%s' % ve
sys.exit(1)
try:
sys.exit(tagcube_cli.run())
except ValueError,... | Project's main method which will parse the command line arguments, run a
scan using the TagCubeClient and exit. | train | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/main.py#L6-L26 | [
"def from_cmd_args(cls, cmd_args):\n return cls(cmd_args)\n",
"def run(self):\n \"\"\"\n This method handles the user's command line arguments, for example, if\n the user specified a path file we'll open it and read the contents.\n Finally it will run the scan using TagCubeClient.scan(...)\n\n :... | import sys
from tagcube_cli.cli import TagCubeCLI
if __name__ == '__main__':
main()
|
radjkarl/appBase | appbase/mainWindowRessources/menuabout.py | MenuAbout.setModule | python | def setModule(self, mod):
"""
fill the about about label txt with the module attributes of the module
"""
txt = """<b>%s</b> - %s<br><br>
Author: %s<br>
Email: %s<br>
Version: %s<br>
License: %s<br>
Url: <a href="%s">%s</a>""" % (
... | fill the about about label txt with the module attributes of the module | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/mainWindowRessources/menuabout.py#L30-L48 | null | class MenuAbout(QtWidgets.QWidget):
"""Create a simple about window, showing a logo
and general information defined in the main modules __init__.py file
"""
def __init__(self, parent=None):
self.app = QtWidgets.QApplication.instance()
super(MenuAbout, self).__init__(parent)
se... |
radjkarl/appBase | appbase/mainWindowRessources/menuabout.py | MenuAbout.setInstitutionLogo | python | def setInstitutionLogo(self, pathList: tuple):
"""
takes one or more [logo].svg paths
if logo should be clickable, set
pathList = (
(my_path1.svg,www.something1.html),
(my_path2.svg,www.something2.html),
...)
"""... | takes one or more [logo].svg paths
if logo should be clickable, set
pathList = (
(my_path1.svg,www.something1.html),
(my_path2.svg,www.something2.html),
...) | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/mainWindowRessources/menuabout.py#L50-L71 | null | class MenuAbout(QtWidgets.QWidget):
"""Create a simple about window, showing a logo
and general information defined in the main modules __init__.py file
"""
def __init__(self, parent=None):
self.app = QtWidgets.QApplication.instance()
super(MenuAbout, self).__init__(parent)
se... |
radjkarl/appBase | appbase/mainWindowRessources/menubar.py | MenuBar.setFullscreen | python | def setFullscreen(self, fullscreen):
"""toggle between fullscreen and normal window"""
if not fullscreen:
self.ckBox_fullscreen.setChecked(False)
self.parent().showNormal()
else:
self.ckBox_fullscreen.setChecked(True)
self.parent().showFullS... | toggle between fullscreen and normal window | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/mainWindowRessources/menubar.py#L165-L172 | null | class MenuBar(FWMenuBar):
"""
MenuBar including
* File (Save, Load, New...)
* State (Next, Previous...)
* View (Fullscreen)
* Help (Shortcuts, About)
"""
def __init__(self):
super(MenuBar, self).__init__()
self.app = QtWidgets.QApplication.instance()
#MENU - FILE... |
radjkarl/appBase | appbase/dialogs/FirstStart.py | FirstStart.accept | python | def accept(self, evt):
"""
write setting to the preferences
"""
# determine if application is a script file or frozen exe (pyinstaller)
frozen = getattr(sys, 'frozen', False)
if frozen:
app_file = sys.executable
else:
app_file = Pa... | write setting to the preferences | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/dialogs/FirstStart.py#L56-L92 | [
"def embeddIntoOS(app_file, ftype, app_name):\n if app_file:\n args = (app_file, '-o')\n else:\n args = '-o'\n assignFtypeToPyFile(\n ftype,\n args,\n mimetype='%s.file' %\n app_name,\n showTerminal=False)\n"
] | class FirstStart(QtWidgets.QDialog):
"""
Dialog to ask user to embed the application into the OS
"""
def __init__(self, session):
QtWidgets.QDialog.__init__(self)
self.name = session.NAME
self.ftype = session.FTYPE
self.icon = session.ICON
self.setWindowTitle('... |
radjkarl/appBase | appbase/MultiWorkspaceWindow.py | MultiWorkspaceWindow.workspaces | python | def workspaces(self, index=None):
"""return generator for all all workspace instances"""
c = self.centralWidget()
if index is None:
return (c.widget(n) for n in range(c.count()))
else:
return c.widget(index) | return generator for all all workspace instances | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/MultiWorkspaceWindow.py#L77-L83 | null | class MultiWorkspaceWindow(MainWindow):
"""Adding workspace management to appbase.MainWindow
* 'Workspace' menu in menu bar
* Switch between workspaces with [Ctrl]+[Page up/down]
* Add workspace with [Ctrl]+[W]
* Remove current workspace with [Ctrl]+[Q]
"""
def __init__(self, workspaceClas... |
radjkarl/appBase | appbase/Launcher.py | _FileSystemModel.data | python | def data(self, index, role):
"""use zipped icon.png as icon"""
if index.column() == 0 and role == QtCore.Qt.DecorationRole:
if self.isPyz(index):
with ZipFile(str(self.filePath(index)), 'r') as myzip:
# print myzip.namelist()
t... | use zipped icon.png as icon | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Launcher.py#L524-L536 | [
"def isPyz(self, index):\n return str(self.fileName(index)).endswith('.%s' % self.file_type)\n"
] | class _FileSystemModel(QtWidgets.QFileSystemModel):
def __init__(self, view, file_type):
QtWidgets.QFileSystemModel.__init__(self, view)
self.view = view
self.file_type = file_type
self.setReadOnly(False)
self._editedSessions = {}
self._tmp_dir_work = tempfile.mkdte... |
radjkarl/appBase | appbase/Launcher.py | _FileSystemModel.editStartScript | python | def editStartScript(self, index):
"""open, edit, replace __main__.py"""
f = str(self.fileName(index))
if f.endswith('.%s' % self.file_type):
zipname = str(self.filePath(index))
with ZipFile(zipname, 'a') as myzip:
# extract+save script in tmp-dir:
... | open, edit, replace __main__.py | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Launcher.py#L538-L555 | null | class _FileSystemModel(QtWidgets.QFileSystemModel):
def __init__(self, view, file_type):
QtWidgets.QFileSystemModel.__init__(self, view)
self.view = view
self.file_type = file_type
self.setReadOnly(False)
self._editedSessions = {}
self._tmp_dir_work = tempfile.mkdte... |
radjkarl/appBase | appbase/Session.py | Session.checkMaxSessions | python | def checkMaxSessions(self, nMax=None):
"""
check whether max. number of saved sessions is reached
if: remove the oldest session
"""
if nMax is None:
nMax = self.opts['maxSessions']
l = self.stateNames()
if len(l) > nMax:
for f in l... | check whether max. number of saved sessions is reached
if: remove the oldest session | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L208-L218 | [
" def stateNames(self):\n \"\"\"Returns:\n list: the names of all saved sessions\n \"\"\"\n# if self.current_session:\n s = self.tmp_dir_session\n l = [x for x in s.listdir() if s.join(x).isdir()]\n naturalSorting(l)\n # else:\n # l=[]\n ... | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session.stateNames | python | def stateNames(self):
"""Returns:
list: the names of all saved sessions
"""
# if self.current_session:
s = self.tmp_dir_session
l = [x for x in s.listdir() if s.join(x).isdir()]
naturalSorting(l)
# else:
# l=[]
# bring aut... | Returns:
list: the names of all saved sessions | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L220-L234 | null | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session._inspectArguments | python | def _inspectArguments(self, args):
"""inspect the command-line-args and give them to appBase"""
if args:
self.exec_path = PathStr(args[0])
else:
self.exec_path = None
session_name = None
args = args[1:]
openSession = False
for ... | inspect the command-line-args and give them to appBase | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L327-L356 | null | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session.save | python | def save(self):
"""save the current session
override, if session was saved earlier"""
if self.path:
self._saveState(self.path)
else:
self.saveAs() | save the current session
override, if session was saved earlier | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L368-L374 | [
"def saveAs(self, filename=None):\n if filename is None:\n # ask for filename:\n filename = self.dialogs.getSaveFileName(filter=\"*.%s\" % self.FTYPE)\n if filename:\n self.path = filename\n self._saveState(self.path)\n if self._createdAutosaveFile:\n self._create... | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session.open | python | def open(self):
"""open a session to define in a dialog in an extra window"""
filename = self.dialogs.getOpenFileName(filter="*.%s" % self.FTYPE)
if filename:
self.new(filename) | open a session to define in a dialog in an extra window | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L397-L401 | [
"def new(self, filename=None):\n \"\"\"start a session an independent process\"\"\"\n path = (self.exec_path,)\n if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE):\n # get the absolute path to the python-executable\n p = find_executable(\"python\")\n path = (p, 'python')... | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session.new | python | def new(self, filename=None):
"""start a session an independent process"""
path = (self.exec_path,)
if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE):
# get the absolute path to the python-executable
p = find_executable("python")
path = (p... | start a session an independent process | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L403-L416 | null | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session._saveState | python | def _saveState(self, path):
"""save current state and add a new state"""
self.addSession() # next session
self._save(str(self.n_sessions), path) | save current state and add a new state | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L456-L459 | [
"def addSession(self):\n self.current_session = self.n_sessions\n self.n_sessions += 1\n self.tmp_dir_save_session = self.tmp_dir_session.join(\n str(self.n_sessions)).mkdir()\n self.checkMaxSessions()\n",
"def _save(self, stateName, path):\n \"\"\"save into 'stateName' to pyz-path\"\"\"\n ... | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session._autoSave | python | def _autoSave(self):
"""save state into 'autosave' """
a = 'autoSave'
path = self.path
if not path:
path = self.dir.join('%s.%s' % (a, self.FTYPE))
self._createdAutosaveFile = path
self.tmp_dir_save_session = self.tmp_dir_session.join(a).mkdir()
... | save state into 'autosave' | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L461-L469 | null | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session.blockingSave | python | def blockingSave(self, path):
"""
saved session to file - returns after finish
only called by interactiveTutorial-save at the moment
"""
self.tmp_dir_save_session = self.tmp_dir_session.join('block').mkdir()
state = {'session': dict(self.opts),
'di... | saved session to file - returns after finish
only called by interactiveTutorial-save at the moment | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L471-L481 | null | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | Session._save | python | def _save(self, stateName, path):
"""save into 'stateName' to pyz-path"""
print('saving...')
state = {'session': dict(self.opts),
'dialogs': self.dialogs.saveState()}
self.sigSave.emit(state)
self.saveThread.prepare(stateName, path, self.tmp_dir_session... | save into 'stateName' to pyz-path | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L483-L503 | null | class Session(QtCore.QObject):
"""Session management to be accessible
in QtWidgets.QApplication.instance().session
* extract the opened (as pyz-zipped) session in a temp folder
* create 2nd temp-folder for sessions to be saved
* send a close signal to all child structures when exit
* write a l... |
radjkarl/appBase | appbase/Session.py | _SaveThread._recusiveReplaceArrayWithPlaceholder | python | def _recusiveReplaceArrayWithPlaceholder(self, state):
"""
replace all numpy.array within the state dict
with a placeholder
this allows to save the arrays extra using numpy.save_compressed
"""
arrays = {}
def recursive(state):
for key, val in... | replace all numpy.array within the state dict
with a placeholder
this allows to save the arrays extra using numpy.save_compressed | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L516-L536 | null | class _SaveThread(QtCore.QThread):
"""Run the saving procedure in a thread to be non-blocking
"""
def prepare(self, stateName, path, dirpath, state):
self.stateName = stateName
self.path = path
self.dirpath = dirpath
self._state = state
def _recusiveReplaceArrayWithPlac... |
radjkarl/appBase | setup.py | read | python | def read(*paths):
"""Build a file path from *paths* and return the contents."""
p = os.path.join(*paths)
if os.path.exists(p):
with open(p, 'r') as f:
return f.read()
return '' | Build a file path from *paths* and return the contents. | train | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/setup.py#L36-L42 | null | # -*- coding: utf-8 -*-
"""
usage:
(sudo) python setup.py +
install ... local
register ... at http://pypi.python.org/pypi
sdist ... create *.tar to be uploaded to pyPI
sdist upload ... build the package and upload in to pyPI
"""
import os
import shutil
from setuptools i... |
anti1869/sunhead | src/sunhead/conf.py | Settings.discover_config_path | python | def discover_config_path(self, config_filename: str) -> str:
if config_filename and os.path.isfile(config_filename):
return config_filename
for place in _common_places:
config_path = os.path.join(place, config_filename)
if os.path.isfile(config_path):
... | Search for config file in a number of places.
If there is no config file found, will return None.
:param config_filename: Config file name or custom path to filename with config.
:return: Path to the discovered config file or None. | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/conf.py#L120-L137 | null | class Settings(object):
def __init__(self):
self._configured = False
self._configuring = False
self._envvar = DEFAULT_ENVIRONMENT_VARIABLE
def __getattribute__(self, item):
# Some sort of Lazy Settings implementation.
# All this stuff is to allow using custom settings e... |
anti1869/sunhead | src/sunhead/conf.py | Settings.gen_from_yaml_config | python | def gen_from_yaml_config(self, config_path: str) -> Iterator:
if not config_path:
return {}
with open(config_path, 'r') as f:
yaml_config = yaml.load(f)
gen = map(lambda x: (x[0].upper(), x[1]), yaml_config.items())
return gen | Convention is to uppercase first level keys.
:param config_path: Valid path to the yml config file.
:return: Config loaded from yml file | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/conf.py#L139-L154 | null | class Settings(object):
def __init__(self):
self._configured = False
self._configuring = False
self._envvar = DEFAULT_ENVIRONMENT_VARIABLE
def __getattribute__(self, item):
# Some sort of Lazy Settings implementation.
# All this stuff is to allow using custom settings e... |
anti1869/sunhead | src/sunhead/conf.py | Settings.remove_handler_if_not_configured | python | def remove_handler_if_not_configured(self, dict_config, requested_handlers, handler_name, check_key) -> None:
try:
if not dict_config["handlers"][handler_name][check_key]:
dict_config["handlers"].pop(handler_name)
if handler_name in requested_handlers:
... | Remove ``handler_name`` from ``dict_config`` and ``requested_handlers`` if ``check_key`` is empty. | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/conf.py#L173-L184 | null | class Settings(object):
def __init__(self):
self._configured = False
self._configuring = False
self._envvar = DEFAULT_ENVIRONMENT_VARIABLE
def __getattribute__(self, item):
# Some sort of Lazy Settings implementation.
# All this stuff is to allow using custom settings e... |
anti1869/sunhead | src/sunhead/serializers/json.py | JSONSerializer.json_serial | python | def json_serial(cls, obj):
if isinstance(obj, datetime):
serial = obj.isoformat()
elif issubclass(obj.__class__, enum.Enum):
serial = obj.value
elif isinstance(obj, timedelta):
serial = str(obj)
elif isinstance(obj, set):
serial = list(... | JSON serializer for objects not serializable by default json code | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/serializers/json.py#L34-L57 | null | class JSONSerializer(AbstractSerializer):
_DEF_SERIALIZED_DEFAULT = "{}"
_DEF_DESERIALIZED_DEFAULT = {}
def __init__(self, graceful=False):
super().__init__(graceful)
self._graceful = graceful
self._serialized_default = self._DEF_SERIALIZED_DEFAULT
self._deserialized_defaul... |
anti1869/sunhead | src/sunhead/decorators.py | cached_property | python | def cached_property():
def _stored_value(f):
storage_var_name = "__{}".format(f.__name__)
def _wrapper(self, *args, **kwargs):
value_in_cache = getattr(self, storage_var_name, Sentinel)
if value_in_cache is not Sentinel:
return value_in_cache
calc... | Handy utility to build caching properties in your classes.
Decorated code will be run only once and then result will be stored in private class property
with the given name. When called for the second time, property will return cached value.
:param storage_var_name: Name of the class property to store cac... | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/decorators.py#L18-L40 | null | """
Miscellaneous decorators to make your life easier.
"""
import logging
default_logger = logging.getLogger(__name__)
DEPRECATION_MESSAGE = "WARNING: Using {name} is deprecated. It will be removed soon"
class Sentinel(object):
"""Use this instead of None"""
def deprecated(message=DEPRECATION_MESSAGE, log... |
anti1869/sunhead | src/sunhead/decorators.py | deprecated | python | def deprecated(message=DEPRECATION_MESSAGE, logger=None):
if logger is None:
logger = default_logger
def _deprecated(f):
def _wrapper(*args, **kwargs):
f_name = f.__name__
logger.warning(message.format(name=f_name))
result = f(*args, **kwargs)
retu... | This decorator will simply print warning before running decoratee.
So, presumably, you want to use it with console-based commands.
:return: Decorator for the function. | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/decorators.py#L43-L59 | null | """
Miscellaneous decorators to make your life easier.
"""
import logging
default_logger = logging.getLogger(__name__)
DEPRECATION_MESSAGE = "WARNING: Using {name} is deprecated. It will be removed soon"
class Sentinel(object):
"""Use this instead of None"""
def cached_property():
"""
Handy utility... |
anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient.connect | python | async def connect(self):
if self.connected or self.is_connecting:
return
self._is_connecting = True
try:
logger.info("Connecting to RabbitMQ...")
self._transport, self._protocol = await aioamqp.connect(**self._connection_parameters)
logger.info("... | Create new asynchronous connection to the RabbitMQ instance.
This will connect, declare exchange and bind itself to the configured queue.
After that, client is ready to publish or consume messages.
:return: Does not return anything. | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L87-L119 | null | class AMQPClient(AbstractTransport):
"""
Handy implementation of the asynchronous AMQP client.
Useful for building both publishers and consumers.
"""
DEFAULT_EXCHANGE_NAME = "default_exchange"
DEFAULT_EXCHANGE_TYPE = "topic"
def __init__(
self,
connection_parameters... |
anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient.consume_queue | python | async def consume_queue(self, subscriber: AbstractSubscriber) -> None:
queue_name = subscriber.name
topics = subscriber.requested_topics
if queue_name in self._known_queues:
raise exceptions.ConsumerError("Queue '%s' already being consumed" % queue_name)
await self._declar... | Subscribe to the queue consuming.
:param subscriber:
:return: | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L140-L171 | null | class AMQPClient(AbstractTransport):
"""
Handy implementation of the asynchronous AMQP client.
Useful for building both publishers and consumers.
"""
DEFAULT_EXCHANGE_NAME = "default_exchange"
DEFAULT_EXCHANGE_TYPE = "topic"
def __init__(
self,
connection_parameters... |
anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient._bind_key_to_queue | python | async def _bind_key_to_queue(self, routing_key: AnyStr, queue_name: AnyStr) -> None:
logger.info("Binding key='%s'", routing_key)
result = await self._channel.queue_bind(
exchange_name=self._exchange_name,
queue_name=queue_name,
routing_key=routing_key,
)
... | Bind to queue with specified routing key.
:param routing_key: Routing key to bind with.
:param queue_name: Name of the queue
:return: Does not return anything | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L179-L194 | null | class AMQPClient(AbstractTransport):
"""
Handy implementation of the asynchronous AMQP client.
Useful for building both publishers and consumers.
"""
DEFAULT_EXCHANGE_NAME = "default_exchange"
DEFAULT_EXCHANGE_TYPE = "topic"
def __init__(
self,
connection_parameters... |
anti1869/sunhead | src/sunhead/events/transports/amqp.py | AMQPClient._on_message | python | async def _on_message(self, channel, body, envelope, properties) -> None:
subscribers = self._get_subscribers(envelope.routing_key)
if not subscribers:
logger.debug("No route for message with key '%s'", envelope.routing_key)
return
body = self._serializer.deserialize(bo... | Fires up when message is received by this consumer.
:param channel: Channel, through which message is received
:param body: Body of the message (serialized).
:param envelope: Envelope object with message meta
:type envelope: aioamqp.Envelope
:param properties: Properties of the ... | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/transports/amqp.py#L196-L219 | null | class AMQPClient(AbstractTransport):
"""
Handy implementation of the asynchronous AMQP client.
Useful for building both publishers and consumers.
"""
DEFAULT_EXCHANGE_NAME = "default_exchange"
DEFAULT_EXCHANGE_TYPE = "topic"
def __init__(
self,
connection_parameters... |
anti1869/sunhead | src/sunhead/metrics/factory.py | Metrics._disable_prometheus_process_collector | python | def _disable_prometheus_process_collector(self) -> None:
logger.info("Removing prometheus process collector")
try:
core.REGISTRY.unregister(PROCESS_COLLECTOR)
except KeyError:
logger.debug("PROCESS_COLLECTOR already removed from prometheus") | There is a bug in SDC' Docker implementation and intolerable prometheus_client code, due to which
its process_collector will fail.
See https://github.com/prometheus/client_python/issues/80 | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/metrics/factory.py#L63-L74 | null | class Metrics(object):
# Not sure it's needed
DEFAULT_APP_PREFIX = "sunhead"
SNAPSHOT_PROMETHEUS = "prometheus"
def __init__(self):
self._app_prefix = self.DEFAULT_APP_PREFIX
self._data = {
"counters": {},
"gauges": {},
"summaries": {},
... |
anti1869/sunhead | src/sunhead/events/stream.py | init_stream_from_settings | python | async def init_stream_from_settings(cfg: dict) -> Stream:
cfg_name = cfg["active_stream"]
stream_init_kwargs = cfg["streams"][cfg_name]
stream = Stream(**stream_init_kwargs)
await stream.connect()
_stream_storage.push(cfg_name, stream)
return stream | Shortcut to create Stream from configured settings.
Will definitely fail if there is no meaningful configuration provided. Example of such is::
{
"streams": {
"rabbitmq": {
"transport": "sunhead.events.transports.amqp.AMQPClient",
"connec... | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/events/stream.py#L124-L157 | [
"async def connect(self):\n if self.connected or self._transport.is_connecting:\n return\n\n try:\n await self._transport.connect()\n except StreamConnectionError:\n logger.error(\"Can't initialize Stream connection\", exc_info=True)\n finally:\n self._reconnecter.start()\n",... | """
Stream is a flow of messages in one particular bus. It could be RabbitMQ exchange, for example.
You can subscribe to messages from the Stream, organize distributed dequeuing or publish data there.
"""
import asyncio
from importlib import import_module
import logging
from typing import Sequence, AnyStr
from sunhe... |
anti1869/sunhead | src/sunhead/workers/http/ext/runtime.py | RuntimeStatsView.get | python | async def get(self):
context_data = self.get_context_data()
context_data.update(getattr(self.request.app, "stats", {}))
response = self.json_response(context_data)
return response | Printing runtime statistics in JSON | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/workers/http/ext/runtime.py#L56-L63 | null | class RuntimeStatsView(JSONView):
def get_context_data(self):
# TODO: Add more useful stuff here
context_data = {
"pkg_version": getattr(settings, "PKG_VERSION", None),
}
return context_data
|
anti1869/sunhead | src/sunhead/cli/banners.py | print_banner | python | def print_banner(filename: str, template: str = DEFAULT_BANNER_TEMPLATE) -> None:
if not os.path.isfile(filename):
logger.warning("Can't find logo banner at %s", filename)
return
with open(filename, "r") as f:
banner = f.read()
formatted_banner = template.format(banner)
print(f... | Print text file to output.
:param filename: Which file to print.
:param template: Format string which specified banner arrangement.
:return: Does not return anything | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/cli/banners.py#L15-L31 | null | """
Cozy utility to print ASCII banners and other stuff for your CLI app.
"""
import logging
import os
logger = logging.getLogger(__name__)
DEFAULT_BANNER_TEMPLATE = "\n\n{}\n"
|
anti1869/sunhead | src/sunhead/utils.py | get_class_by_path | python | def get_class_by_path(class_path: str, is_module: Optional[bool] = False) -> type:
if is_module:
try:
backend_module = importlib.import_module(class_path)
except ImportError:
logger.warning("Can't import backend with name `%s`", class_path)
raise
else:
... | Get class by its name within a package structure.
:param class_path: E.g. brandt.some.module.ClassName
:param is_module: Whether last item is module rather than class name
:return: Class ready to be instantiated. | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L26-L58 | null | """
Helper utilities that everyone needs.
"""
import asyncio
from collections import namedtuple, OrderedDict
from datetime import datetime
from enum import Enum
import importlib
import logging
import pkgutil
import re
from typing import Sequence, Tuple, Dict, Optional, Any
from dateutil import tz
from sunhead.conf i... |
anti1869/sunhead | src/sunhead/utils.py | get_submodule_list | python | def get_submodule_list(package_path: str) -> Tuple[ModuleDescription, ...]:
pkg = importlib.import_module(package_path)
subs = (
ModuleDescription(
name=modname,
path="{}.{}".format(package_path, modname), is_package=ispkg
)
for importer, modname, ispkg in pkguti... | Get list of submodules for some package by its path. E.g ``pkg.subpackage`` | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L61-L73 | null | """
Helper utilities that everyone needs.
"""
import asyncio
from collections import namedtuple, OrderedDict
from datetime import datetime
from enum import Enum
import importlib
import logging
import pkgutil
import re
from typing import Sequence, Tuple, Dict, Optional, Any
from dateutil import tz
from sunhead.conf i... |
anti1869/sunhead | src/sunhead/utils.py | parallel_results | python | async def parallel_results(future_map: Sequence[Tuple]) -> Dict:
ctx_methods = OrderedDict(future_map)
fs = list(ctx_methods.values())
results = await asyncio.gather(*fs)
results = {
key: results[idx] for idx, key in enumerate(ctx_methods.keys())
}
return results | Run parallel execution of futures and return mapping of their results to the provided keys.
Just a neat shortcut around ``asyncio.gather()``
:param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) )
:return: Dict with futures results mapped to keys {'nav': {1:2}, '... | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L99-L113 | null | """
Helper utilities that everyone needs.
"""
import asyncio
from collections import namedtuple, OrderedDict
from datetime import datetime
from enum import Enum
import importlib
import logging
import pkgutil
import re
from typing import Sequence, Tuple, Dict, Optional, Any
from dateutil import tz
from sunhead.conf i... |
anti1869/sunhead | src/sunhead/utils.py | positive_int | python | def positive_int(integer_string: str, strict: bool = False, cutoff: Optional[int] = None) -> int:
ret = int(integer_string)
if ret < 0 or (ret == 0 and strict):
raise ValueError()
if cutoff:
ret = min(ret, cutoff)
return ret | Cast a string to a strictly positive integer. | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L116-L125 | null | """
Helper utilities that everyone needs.
"""
import asyncio
from collections import namedtuple, OrderedDict
from datetime import datetime
from enum import Enum
import importlib
import logging
import pkgutil
import re
from typing import Sequence, Tuple, Dict, Optional, Any
from dateutil import tz
from sunhead.conf i... |
anti1869/sunhead | src/sunhead/utils.py | choices_from_enum | python | def choices_from_enum(source: Enum) -> Tuple[Tuple[Any, str], ...]:
result = tuple((s.value, s.name.title()) for s in source)
return result | Makes tuple to use in Django's Fields ``choices`` attribute.
Enum members names will be titles for the choices.
:param source: Enum to process.
:return: Tuple to put into ``choices`` | train | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/utils.py#L135-L144 | null | """
Helper utilities that everyone needs.
"""
import asyncio
from collections import namedtuple, OrderedDict
from datetime import datetime
from enum import Enum
import importlib
import logging
import pkgutil
import re
from typing import Sequence, Tuple, Dict, Optional, Any
from dateutil import tz
from sunhead.conf i... |
svasilev94/GraphLibrary | graphlibrary/dijkstra.py | dijkstra | python | def dijkstra(G, start, weight='weight'):
"""
Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, })
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't ex... | Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor, }) | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/dijkstra.py#L6-L32 | null | from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def dijkstra(G, start, weight='weight'):
"""
Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor... |
svasilev94/GraphLibrary | graphlibrary/dijkstra.py | dijkstra_single_path_length | python | def dijkstra_single_path_length(G, start, end):
"""
Compute shortest path length between satrt
and end for a weight graph. return -> (length, [path])
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
if end not in G.vertices:
ra... | Compute shortest path length between satrt
and end for a weight graph. return -> (length, [path]) | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/dijkstra.py#L35-L54 | [
"def dijkstra(G, start, weight='weight'):\n \"\"\"\n Compute shortest path length between satrt\n and all other reachable nodes for a weight graph.\n return -> ({vertex: weight form start, }, {vertex: predeseccor, })\n \"\"\"\n if start not in G.vertices:\n raise GraphInsertError(\"Vertex %... | from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def dijkstra(G, start, weight='weight'):
"""
Compute shortest path length between satrt
and all other reachable nodes for a weight graph.
return -> ({vertex: weight form start, }, {vertex: predeseccor... |
svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.add_vertex | python | def add_vertex(self, vertex, **attr):
"""
Add vertex and update vertex attributes
"""
self.vertices[vertex] = []
if attr:
self.nodes[vertex] = attr
self.pred[vertex] = []
self.succ[vertex] = [] | Add vertex and update vertex attributes | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L25-L33 | null | class DiGraph(Graph):
"""
Class for directed graphs
"""
def __init__(self):
"""
Initialize directed graphs
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u, v): {data: 'info', }, }
vertex attributes dictionary -> {u: {data: 'info', }, }
v... |
svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.add_edge | python | def add_edge(self, u, v, **attr):
"""
Add an edge from u to v and update edge attributes
"""
if u not in self.vertices:
self.vertices[u] = []
self.pred[u] = []
self.succ[u] = []
if v not in self.vertices:
self.vertices[v] =... | Add an edge from u to v and update edge attributes | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L35-L52 | null | class DiGraph(Graph):
"""
Class for directed graphs
"""
def __init__(self):
"""
Initialize directed graphs
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u, v): {data: 'info', }, }
vertex attributes dictionary -> {u: {data: 'info', }, }
v... |
svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.remove_vertex | python | def remove_vertex(self, vertex):
"""
Remove vertex from G
"""
try:
self.vertices.pop(vertex)
self.succ.pop(vertex)
except KeyError:
raise GraphInsertError("Vertex %s doesn't exist." % (vertex,))
if vertex in self.nodes:
... | Remove vertex from G | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L54-L79 | null | class DiGraph(Graph):
"""
Class for directed graphs
"""
def __init__(self):
"""
Initialize directed graphs
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u, v): {data: 'info', }, }
vertex attributes dictionary -> {u: {data: 'info', }, }
v... |
svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.has_successor | python | def has_successor(self, u, v):
"""
Check if vertex u has successor v
"""
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return (u in self.succ and v in self.succ[u]) | Check if vertex u has successor v | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L99-L105 | null | class DiGraph(Graph):
"""
Class for directed graphs
"""
def __init__(self):
"""
Initialize directed graphs
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u, v): {data: 'info', }, }
vertex attributes dictionary -> {u: {data: 'info', }, }
v... |
svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.has_predecessor | python | def has_predecessor(self, u, v):
"""
Check if vertex u has predecessor v
"""
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return(u in self.pred and v in self.pred[u]) | Check if vertex u has predecessor v | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L107-L113 | null | class DiGraph(Graph):
"""
Class for directed graphs
"""
def __init__(self):
"""
Initialize directed graphs
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u, v): {data: 'info', }, }
vertex attributes dictionary -> {u: {data: 'info', }, }
v... |
svasilev94/GraphLibrary | graphlibrary/paths.py | find_all_paths | python | def find_all_paths(G, start, end, path=[]):
"""
Find all paths between vertices start and end in graph.
"""
path = path + [start]
if start == end:
return [path]
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
if end not in G.... | Find all paths between vertices start and end in graph. | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/paths.py#L6-L23 | [
"def find_all_paths(G, start, end, path=[]):\n \"\"\"\n Find all paths between vertices start and end in graph.\n \"\"\"\n path = path + [start]\n if start == end:\n return [path]\n if start not in G.vertices:\n raise GraphInsertError(\"Vertex %s doesn't exist.\" % (start,))\n if ... | from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def find_all_paths(G, start, end, path=[]):
"""
Find all paths between vertices start and end in graph.
"""
path = path + [start]
if start == end:
return [path]
if start not in G.verti... |
svasilev94/GraphLibrary | graphlibrary/first_search.py | BFS | python | def BFS(G, start):
"""
Algorithm for breadth-first searching the vertices of a graph.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
color = {}
pred = {}
dist = {}
queue = Queue()
queue.put(start)
for vertex in G.v... | Algorithm for breadth-first searching the vertices of a graph. | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/first_search.py#L8-L32 | null | from queue import Queue
from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def BFS(G, start):
"""
Algorithm for breadth-first searching the vertices of a graph.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist."... |
svasilev94/GraphLibrary | graphlibrary/first_search.py | BFS_Tree | python | def BFS_Tree(G, start):
"""
Return an oriented tree constructed from bfs starting at 'start'.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
pred = BFS(G, start)
T = digraph.DiGraph()
queue = Queue()
queue.put(start)
wh... | Return an oriented tree constructed from bfs starting at 'start'. | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/first_search.py#L35-L51 | [
"def BFS(G, start):\n \"\"\"\n Algorithm for breadth-first searching the vertices of a graph.\n \"\"\"\n if start not in G.vertices:\n raise GraphInsertError(\"Vertex %s doesn't exist.\" % (start,))\n color = {}\n pred = {}\n dist = {}\n queue = Queue()\n queue.put(start)\n for ... | from queue import Queue
from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def BFS(G, start):
"""
Algorithm for breadth-first searching the vertices of a graph.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist."... |
svasilev94/GraphLibrary | graphlibrary/first_search.py | DFS | python | def DFS(G):
"""
Algorithm for depth-first searching the vertices of a graph.
"""
if not G.vertices:
raise GraphInsertError("This graph have no vertices.")
color = {}
pred = {}
reach = {}
finish = {}
def DFSvisit(G, current, time):
color[current] = 'grey'
... | Algorithm for depth-first searching the vertices of a graph. | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/first_search.py#L54-L92 | [
"def DFSvisit(G, current, time):\n color[current] = 'grey'\n time += 1\n reach[current] = time\n for vertex in G.vertices[current]:\n if color[vertex] == 'white':\n pred[vertex] = current\n time = DFSvisit(G, vertex, time)\n color[current] = 'black'\n time += 1\n fi... | from queue import Queue
from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def BFS(G, start):
"""
Algorithm for breadth-first searching the vertices of a graph.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist."... |
svasilev94/GraphLibrary | graphlibrary/first_search.py | DFS_Tree | python | def DFS_Tree(G):
"""
Return an oriented tree constructed from dfs.
"""
if not G.vertices:
raise GraphInsertError("This graph have no vertices.")
pred = {}
T = digraph.DiGraph()
vertex_data = DFS(G)
for vertex in vertex_data:
pred[vertex] = vertex_data[vertex][0]... | Return an oriented tree constructed from dfs. | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/first_search.py#L95-L116 | [
"def DFS(G):\n \"\"\"\n Algorithm for depth-first searching the vertices of a graph.\n \"\"\"\n if not G.vertices:\n raise GraphInsertError(\"This graph have no vertices.\")\n color = {}\n pred = {}\n reach = {}\n finish = {}\n\n def DFSvisit(G, current, time):\n color[curre... | from queue import Queue
from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def BFS(G, start):
"""
Algorithm for breadth-first searching the vertices of a graph.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist."... |
svasilev94/GraphLibrary | graphlibrary/prim.py | connected_components | python | def connected_components(G):
"""
Check if G is connected and return list of sets. Every
set contains all vertices in one connected component.
"""
result = []
vertices = set(G.vertices)
while vertices:
n = vertices.pop()
group = {n}
queue = Queue()
q... | Check if G is connected and return list of sets. Every
set contains all vertices in one connected component. | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/prim.py#L8-L29 | null | from queue import Queue
from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def connected_components(G):
"""
Check if G is connected and return list of sets. Every
set contains all vertices in one connected component.
"""
result = []
vertices ... |
svasilev94/GraphLibrary | graphlibrary/prim.py | prim | python | def prim(G, start, weight='weight'):
"""
Algorithm for finding a minimum spanning
tree for a weighted undirected graph.
"""
if len(connected_components(G)) != 1:
raise GraphInsertError("Prim algorithm work with connected graph only")
if start not in G.vertices:
raise Grap... | Algorithm for finding a minimum spanning
tree for a weighted undirected graph. | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/prim.py#L43-L73 | [
"def connected_components(G):\n \"\"\"\n Check if G is connected and return list of sets. Every\n set contains all vertices in one connected component.\n \"\"\"\n result = []\n vertices = set(G.vertices)\n while vertices:\n n = vertices.pop()\n group = {n}\n queue = Queue()... | from queue import Queue
from graphlibrary import digraph
from graphlibrary import graph
from graphlibrary.exceptions import *
def connected_components(G):
"""
Check if G is connected and return list of sets. Every
set contains all vertices in one connected component.
"""
result = []
vertices ... |
svasilev94/GraphLibrary | graphlibrary/graph.py | Graph.add_vertex | python | def add_vertex(self, vertex, **attr):
"""
Add vertex and update vertex attributes
"""
self.vertices[vertex] = []
if attr:
self.nodes[vertex] = attr | Add vertex and update vertex attributes | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L49-L55 | null | class Graph:
"""
Class for undirected graphs
"""
vertices = dict
edges = dict
def __init__(self):
"""
Initialize undirected graph
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u;v): {data: 'info', }, }
vertex attributes dictionary -> {u:... |
svasilev94/GraphLibrary | graphlibrary/graph.py | Graph.add_edge | python | def add_edge(self, u, v, **attr):
"""
Add an edge between vertices u and v and update edge attributes
"""
if u not in self.vertices:
self.vertices[u] = []
if v not in self.vertices:
self.vertices[v] = []
vertex = (u, v)
self.edges[... | Add an edge between vertices u and v and update edge attributes | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L57-L70 | null | class Graph:
"""
Class for undirected graphs
"""
vertices = dict
edges = dict
def __init__(self):
"""
Initialize undirected graph
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u;v): {data: 'info', }, }
vertex attributes dictionary -> {u:... |
svasilev94/GraphLibrary | graphlibrary/graph.py | Graph.remove_vertex | python | def remove_vertex(self, vertex):
"""
Remove vertex from G
"""
try:
self.vertices.pop(vertex)
except KeyError:
raise GraphInsertError("Vertex %s doesn't exist." % (vertex,))
if vertex in self.nodes:
self.nodes.pop(vertex)
... | Remove vertex from G | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L72-L90 | null | class Graph:
"""
Class for undirected graphs
"""
vertices = dict
edges = dict
def __init__(self):
"""
Initialize undirected graph
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u;v): {data: 'info', }, }
vertex attributes dictionary -> {u:... |
svasilev94/GraphLibrary | graphlibrary/graph.py | Graph.remove_edge | python | def remove_edge(self, u, v):
"""
Remove the edge between vertices u and v
"""
try:
self.edges.pop((u, v))
except KeyError:
raise GraphInsertError("Edge %s-%s doesn't exist." % (u, v))
self.vertices[u].remove(v)
self.vertices[v].rem... | Remove the edge between vertices u and v | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L92-L101 | null | class Graph:
"""
Class for undirected graphs
"""
vertices = dict
edges = dict
def __init__(self):
"""
Initialize undirected graph
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u;v): {data: 'info', }, }
vertex attributes dictionary -> {u:... |
svasilev94/GraphLibrary | graphlibrary/graph.py | Graph.degree | python | def degree(self, vertex):
"""
Return the degree of a vertex
"""
try:
return len(self.vertices[vertex])
except KeyError:
raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) | Return the degree of a vertex | train | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L112-L119 | null | class Graph:
"""
Class for undirected graphs
"""
vertices = dict
edges = dict
def __init__(self):
"""
Initialize undirected graph
vertices dictionary -> {u: [neigbours], }
edges dictionary -> {(u;v): {data: 'info', }, }
vertex attributes dictionary -> {u:... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_xfac.py | gp_xfac | python | def gp_xfac():
# prepare data
inDir, outDir = getWorkDirs()
data = OrderedDict()
# TODO: "really" reproduce plot using spectral data
for file in os.listdir(inDir):
info = os.path.splitext(file)[0].split('_')
key = ' '.join(info[:2] + [':',
' - '.join([
str(float(s)/1e3) for s in info[-1]... | example using QM12 enhancement factors
- uses `gpcalls` kwarg to reset xtics
- numpy.loadtxt needs reshaping for input files w/ only one datapoint
- according poster presentations see QM12_ & NSD_ review
.. _QM12: http://indico.cern.ch/getFile.py/access?contribId=268&sessionId=10&resId=0&materialId=slides&con... | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_xfac.py#L12-L63 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import logging, argparse, os, sys
import numpy as np
from collections import OrderedDict
from ..ccsgp.ccsgp import make_plot
from .utils import getWorkDirs
from ..ccsgp.utils import getOpts
shift = {
'STAR Au+Au : 0.3 - 0.75 GeV': 1.06, 'STAR Au+Au : 0.2 - 0.6 GeV': 1.12
}
if __name__ == '__main__':
parser = arg... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_ptspec.py | gp_ptspec | python | def gp_ptspec():
fenergies = ['19', '27', '39', '62', ]# '200']
nen = len(fenergies)
mee_keys = ['pi0', 'LMR', 'omega', 'phi', 'IMR', 'jpsi']
#mee_keys = ['LMR', ]
mee_dict = OrderedDict((k,'') for k in mee_keys)
yscale = { '200': '300', '62': '5000', '39': '50', '27': '0.3', '19': '0.001' }
inDir, outDir... | example for a 2D-panel plot etc. | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_ptspec.py#L32-L239 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import logging, argparse, os, sys, re
import numpy as np
from collections import OrderedDict
from .utils import getWorkDirs, getEnergy4Key
from ..ccsgp.ccsgp import make_panel, make_plot
from ..ccsgp.utils import getOpts
from ..ccsgp.config import default_colors
from decimal import Decimal
import uncertainties.umath as... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_panel.py | gp_panel | python | def gp_panel(version, skip):
scale = { # QM14 (19 GeV skip later, factor here only informational)
'19': 1.0340571932983775, '200': 1.0, '39': 0.7776679085382481,
'27': 0.6412140408244136, '62': 0.9174700031778402
} if version == 'QM14' else {
'19': 1.3410566491548412, '200': 1.1051002240771077,
... | example for a panel plot using QM12 data (see gp_xfac)
.. image:: pics/panelQM12.png
:width: 700 px
:param version: plot version / input subdir name
:type version: str | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_panel.py#L10-L100 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import logging, argparse, os, sys, re
import numpy as np
from collections import OrderedDict
from .utils import getWorkDirs, getEnergy4Key
from ..ccsgp.ccsgp import make_panel
from ..ccsgp.utils import getOpts
from ..ccsgp.config import default_colors
from fnmatch import fnmatch
if __name__ == '__main__':
parser = ... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_ccX.py | gp_ccX | python | def gp_ccX():
inDir, outDir = getWorkDirs()
data, alldata = OrderedDict(), None
for infile in os.listdir(inDir):
# get key and import data
key = os.path.splitext(infile)[0].replace('_', '/')
data_import = np.loadtxt(open(os.path.join(inDir, infile), 'rb'))
# convert to log10 ... | fit experimental data | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_ccX.py#L19-L92 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import os, argparse, logging
from .utils import getWorkDirs, getEnergy4Key, particleLabel4Key
from collections import OrderedDict
from ..ccsgp.ccsgp import make_plot, make_panel
from ..ccsgp.config import default_colors
from scipy.optimize import curve_fit
import numpy as np
from uncertainties import ufloat
def linear... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_rapp.py | gp_rapp | python | def gp_rapp():
inDir, outDir = getWorkDirs()
# prepare data
yields = {}
for infile in os.listdir(inDir):
energy = re.compile('\d+').search(infile).group()
medium = np.loadtxt(open(os.path.join(inDir, infile), 'rb'))
getMassRangesSums(energy, medium, yields)
data = dict( # sort by energy
(k, np... | rho in-medium ratios by Rapp (based on protected data) | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_rapp.py#L9-L36 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import logging, argparse, os, re
import numpy as np
from ..ccsgp.config import default_colors
from ..ccsgp.ccsgp import make_plot, make_panel
from .utils import getWorkDirs, getMassRangesSums, getEnergy4Key
from math import pi, log
from collections import OrderedDict
def calc_REW_eta(nf):
charges = [2./3., -1./3., ... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_sims.py | gp_sims | python | def gp_sims(version):
inDir, outDir = getWorkDirs()
inDir = os.path.join(inDir, version, 'cocktail_contribs')
xmax = {
'pion': 0.125, 'eta': 0.52, 'etap': 0.92, 'omega': 1.22,
'phi': 1.22, 'jpsi': 3.52
}
for particles in [
'pion', 'eta', 'etap', ['omega', 'rho'], 'phi', 'jpsi'
]:
if ... | example for a batch generating simple plots (cocktail contributions)
:param version: plot version / input subdir name
:type version: str | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_sims.py#L12-L60 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import os, argparse, logging
from .utils import getWorkDirs, getEnergy4Key, particleLabel4Key
from collections import OrderedDict
from ..ccsgp.ccsgp import make_plot, make_panel
from ..ccsgp.config import default_colors
import numpy as np
energies = [19, 27, 39, 62]
xlabel = 'dielectron invariant mass, M_{ee} (GeV/c^{... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_sims.py | gp_sims_panel | python | def gp_sims_panel(version):
inDir, outDir = getWorkDirs()
inDir = os.path.join(inDir, version)
mesons = ['pion', 'eta', 'etap', 'rho', 'omega', 'phi', 'jpsi']
fstems = ['cocktail_contribs/'+m for m in mesons] + ['cocktail', 'cocktail_contribs/ccbar']
data = OrderedDict((energy, [
np.loadtxt(open(os.path... | panel plot of cocktail simulations at all energies, includ. total
:param version: plot version / input subdir name
:type version: str | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_sims.py#L62-L100 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import os, argparse, logging
from .utils import getWorkDirs, getEnergy4Key, particleLabel4Key
from collections import OrderedDict
from ..ccsgp.ccsgp import make_plot, make_panel
from ..ccsgp.config import default_colors
import numpy as np
energies = [19, 27, 39, 62]
xlabel = 'dielectron invariant mass, M_{ee} (GeV/c^{... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_sims.py | gp_sims_total_overlay | python | def gp_sims_total_overlay(version):
inDir, outDir = getWorkDirs()
inDir = os.path.join(inDir, version)
data = OrderedDict()
for energy in energies:
fname = os.path.join(inDir, 'cocktail'+str(energy)+'.dat')
data[energy] = np.loadtxt(open(fname, 'rb'))
data[energy][:,2:] = 0
make_plot(
... | single plot comparing total cocktails at all energies
:param version: plot version / input subdir name
:type version: str | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_sims.py#L102-L130 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import os, argparse, logging
from .utils import getWorkDirs, getEnergy4Key, particleLabel4Key
from collections import OrderedDict
from ..ccsgp.ccsgp import make_plot, make_panel
from ..ccsgp.config import default_colors
import numpy as np
energies = [19, 27, 39, 62]
xlabel = 'dielectron invariant mass, M_{ee} (GeV/c^{... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/utils.py | getWorkDirs | python | def getWorkDirs():
# get caller module
caller_fullurl = inspect.stack()[1][1]
caller_relurl = os.path.relpath(caller_fullurl)
caller_modurl = os.path.splitext(caller_relurl)[0]
# split caller_url & append 'Dir' to package name
dirs = caller_modurl.split('/')
dirs[0] = 'data' # TODO de-hardcode
# get, ch... | get input/output dirs (same input/output layout as for package) | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/utils.py#L9-L27 | null | import sys, os, itertools, inspect, logging, math
import numpy as np
from uncertainties import ufloat
from uncertainties.umath import fsum
from decimal import Decimal
mass_titles = [ 'pi0', 'LMR', 'omphi', 'IMR' ]
eRanges = np.array([ Decimal(str(e)) for e in [ 0, 0.4, 0.75, 1.1, 3. ] ])
def getUArray(npArr):
"""un... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/utils.py | getUArray | python | def getUArray(npArr):
ufloats = []
for dp in npArr:
u = ufloat(dp[1], abs(dp[3]), 'stat')
v = ufloat(dp[1], abs(dp[4]), 'syst')
r = (u+v)/2.*dp[2]*2.
ufloats.append(r)
# NOTE: center value ok, but both error contribs half!
# see getErrorComponent()
return np.array(ufloats) | uncertainty array multiplied by binwidth (col2 = dx) | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/utils.py#L29-L39 | null | import sys, os, itertools, inspect, logging, math
import numpy as np
from uncertainties import ufloat
from uncertainties.umath import fsum
from decimal import Decimal
mass_titles = [ 'pi0', 'LMR', 'omphi', 'IMR' ]
eRanges = np.array([ Decimal(str(e)) for e in [ 0, 0.4, 0.75, 1.1, 3. ] ])
def getWorkDirs():
"""get in... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/utils.py | getErrorComponent | python | def getErrorComponent(result, tag):
return math.sqrt(sum(
(error*2)**2
for (var, error) in result.error_components().items()
if var.tag == tag
)) | get total error contribution for component with specific tag | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/utils.py#L41-L47 | null | import sys, os, itertools, inspect, logging, math
import numpy as np
from uncertainties import ufloat
from uncertainties.umath import fsum
from decimal import Decimal
mass_titles = [ 'pi0', 'LMR', 'omphi', 'IMR' ]
eRanges = np.array([ Decimal(str(e)) for e in [ 0, 0.4, 0.75, 1.1, 3. ] ])
def getWorkDirs():
"""get in... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/utils.py | getEdges | python | def getEdges(npArr):
edges = np.concatenate(([0], npArr[:,0] + npArr[:,2]))
return np.array([Decimal(str(i)) for i in edges]) | get np array of bin edges | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/utils.py#L49-L52 | null | import sys, os, itertools, inspect, logging, math
import numpy as np
from uncertainties import ufloat
from uncertainties.umath import fsum
from decimal import Decimal
mass_titles = [ 'pi0', 'LMR', 'omphi', 'IMR' ]
eRanges = np.array([ Decimal(str(e)) for e in [ 0, 0.4, 0.75, 1.1, 3. ] ])
def getWorkDirs():
"""get in... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/utils.py | getMaskIndices | python | def getMaskIndices(mask):
return [
list(mask).index(True), len(mask) - 1 - list(mask)[::-1].index(True)
] | get lower and upper index of mask | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/utils.py#L54-L58 | null | import sys, os, itertools, inspect, logging, math
import numpy as np
from uncertainties import ufloat
from uncertainties.umath import fsum
from decimal import Decimal
mass_titles = [ 'pi0', 'LMR', 'omphi', 'IMR' ]
eRanges = np.array([ Decimal(str(e)) for e in [ 0, 0.4, 0.75, 1.1, 3. ] ])
def getWorkDirs():
"""get in... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/utils.py | getCocktailSum | python | def getCocktailSum(e0, e1, eCocktail, uCocktail):
# get mask and according indices
mask = (eCocktail >= e0) & (eCocktail <= e1)
# data bin range wider than single cocktail bin
if np.any(mask):
idx = getMaskIndices(mask)
# determine coinciding flags
eCl, eCu = eCocktail[idx[0]], eCocktail[idx[1]]
... | get the cocktail sum for a given data bin range | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/utils.py#L64-L108 | [
"def getMaskIndices(mask):\n \"\"\"get lower and upper index of mask\"\"\"\n return [\n list(mask).index(True), len(mask) - 1 - list(mask)[::-1].index(True)\n ]\n"
] | import sys, os, itertools, inspect, logging, math
import numpy as np
from uncertainties import ufloat
from uncertainties.umath import fsum
from decimal import Decimal
mass_titles = [ 'pi0', 'LMR', 'omphi', 'IMR' ]
eRanges = np.array([ Decimal(str(e)) for e in [ 0, 0.4, 0.75, 1.1, 3. ] ])
def getWorkDirs():
"""get in... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_background.py | gp_background | python | def gp_background():
inDir, outDir = getWorkDirs()
data, REBIN = OrderedDict(), None
titles = [ 'SE_{+-}', 'SE@^{corr}_{/Symbol \\261\\261}', 'ME@^{N}_{+-}' ]
Apm = OrderedDict([
('19', 0.026668), ('27', 0.026554), ('39', 0.026816), ('62', 0.026726)
])
fake = np.array([[-1, 1, 0, 0, 0]])... | plot background methods and S/B vs energy | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_background.py#L26-L121 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import logging, argparse, re, os, glob
import numpy as np
from .utils import getWorkDirs, getEnergy4Key
from ..ccsgp.ccsgp import make_plot, make_panel
from ..ccsgp.config import default_colors
from ..ccsgp.utils import colorscale
from collections import OrderedDict
from fnmatch import fnmatch
MIL = 1e6
NEVTS = { '19'... |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_background.py | gp_norm | python | def gp_norm(infile):
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.path.realpath(os.path.join(
inDir, 'rawdata', energy, 'pt-integrated', infile+'.dat'
))
data_import = np.loadtxt(open(file_url, '... | indentify normalization region | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_background.py#L201-L245 | [
"def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package... | import logging, argparse, re, os, glob
import numpy as np
from .utils import getWorkDirs, getEnergy4Key
from ..ccsgp.ccsgp import make_plot, make_panel
from ..ccsgp.config import default_colors
from ..ccsgp.utils import colorscale
from collections import OrderedDict
from fnmatch import fnmatch
MIL = 1e6
NEVTS = { '19'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.