id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
600 |
20c/xbahn
|
20c_xbahn/xbahn/connection/zmq.py
|
xbahn.connection.zmq.PULL_Connection
|
class PULL_Connection(SUB_Connection):
connection_type = "client"
def finalize_connection(self):
pass
def receive(self):
Connection.receive(self)
def response(self):
pass
|
class PULL_Connection(SUB_Connection):
def finalize_connection(self):
pass
def receive(self):
pass
def response(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 80 | 12 | 4 | 8 | 5 | 4 | 0 | 8 | 5 | 4 | 1 | 6 | 0 | 3 |
601 |
20c/xbahn
|
20c_xbahn/xbahn/connection/__init__.py
|
xbahn.connection.register
|
class register(object):
"""
Decorator
Register a sender or receiver class to a scheme
scheme <str> scheme name (eg. 'tcp', 'qpid')
"""
def __init__(self, scheme):
self.scheme = scheme
def __call__(self, fnc):
scheme = self.scheme
if scheme not in SCHEMES:
SCHEMES[scheme] = {}
SCHEMES[scheme][fnc.__name__] = fnc
return fnc
|
class register(object):
'''
Decorator
Register a sender or receiver class to a scheme
scheme <str> scheme name (eg. 'tcp', 'qpid')
'''
def __init__(self, scheme):
pass
def __call__(self, fnc):
pass
| 3 | 1 | 4 | 0 | 4 | 0 | 2 | 0.56 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 18 | 4 | 9 | 5 | 6 | 5 | 9 | 5 | 6 | 2 | 1 | 1 | 3 |
602 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.WidgetAwareServer
|
class WidgetAwareServer(ClientAwareServer):
def wire(self, link):
super(WidgetAwareServer, self).wire(link)
self.clients.on("remove", self.on_client_remove)
def on_client_remove(self, id=None, dispatcher=None, event_origin=None):
for widgets in self.widgets.values():
keys = []
for key in widgets.items.keys():
if key.find("%s." % id) == 0:
keys.append(key)
for key in keys:
self.log_debug("Removing widget %s" % key)
del widgets[key]
@expose
def detach_remote(self, id, name):
"""
destroy remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
"""
if name in self.widgets:
if id in self.widgets[name]:
del self.widgets[name]
@expose
def attach_remote(self, id, name, **kwargs):
"""
create remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
Keyword Arguments:
- any further arguments you wish to pass
to the widget constructor
"""
client_id = id.split(".")[0]
widget = self.make_widget(
id,
name,
dispatcher=ProxyDispatcher(
self,
link=getattr(self.clients[client_id], "link", None)
),
**kwargs
)
self.store_widget(widget)
self.log_debug("Attached widget: %s" % id)
|
class WidgetAwareServer(ClientAwareServer):
def wire(self, link):
pass
def on_client_remove(self, id=None, dispatcher=None, event_origin=None):
pass
@expose
def detach_remote(self, id, name):
'''
destroy remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
'''
pass
@expose
def attach_remote(self, id, name, **kwargs):
'''
create remote instance of widget
Arguments:
- id (str): widget id
- name (str): widget type name
Keyword Arguments:
- any further arguments you wish to pass
to the widget constructor
'''
pass
| 7 | 2 | 13 | 2 | 7 | 4 | 3 | 0.47 | 1 | 2 | 1 | 2 | 4 | 0 | 4 | 38 | 59 | 12 | 32 | 12 | 25 | 15 | 22 | 10 | 17 | 5 | 6 | 3 | 10 |
603 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.Widget
|
class Widget(EventMixin):
"""
API Widget
An api widget is a modular object that lives on an established
api communication, it can have its own methods exposed separate
from the comm's methods
Attributes:
- comm (Comm): instance that spawned this widget
- id (str)
- group (str): widget group name
- dispatcher (Comm, Dispatcher, ProxyDispatcher)
- init_kwargs (dict): kwargs passed to the ctor
- remote_name (str)
- name (str)
"""
def __init__(self, comm, id, dispatcher=None, **kwargs):
super(Widget, self).__init__()
self.comm = comm
self.group = kwargs.get("group")
self.dispatcher = dispatcher
self.init_kwargs = kwargs
if "remote_name" in kwargs:
self.remote_name = kwargs.get("remote_name")
if isinstance(comm, Client):
self.id = xbahn.path.append(comm.id, id)
# widget is attached to a client, try to attach at server
try:
self.comm.attach_remote(self.id, self.remote_name, remote_name=self.name, **kwargs)
except APIError as inst:
print(inst)
self.dispatcher = ProxyDispatcher(
comm,
link=comm.link
)
comm.store_widget(self)
elif isinstance(comm, Server):
self.id = id
self.path = xbahn.path.append(comm.widget.path, self.remote_name, self.id)
if self.dispatcher:
self.dispatcher.kwargs['path'] = self.path
self.setup()
def __getattr__(self, k):
if self.dispatcher:
dispatcher = getattr(self.dispatcher, k)
dispatcher.on("api_error", self.on_api_error)
return dispatcher
else:
return getattr(self.comm, k)
def setup(self):
"""
Override for extra widget setup
Is called after __init__ has completed
"""
pass
def on_api_error(self, error_status=None, message=None, event_origin=None):
"""
API error handling
"""
if message.meta["error"].find("Widget instance not found on server") > -1:
# widget is missing on the other side, try to re-attach
# then try again
error_status["retry"] = True
self.comm.attach_remote(
self.id,
self.remote_name,
remote_name=self.name,
**self.init_kwargs
)
|
class Widget(EventMixin):
'''
API Widget
An api widget is a modular object that lives on an established
api communication, it can have its own methods exposed separate
from the comm's methods
Attributes:
- comm (Comm): instance that spawned this widget
- id (str)
- group (str): widget group name
- dispatcher (Comm, Dispatcher, ProxyDispatcher)
- init_kwargs (dict): kwargs passed to the ctor
- remote_name (str)
- name (str)
'''
def __init__(self, comm, id, dispatcher=None, **kwargs):
pass
def __getattr__(self, k):
pass
def setup(self):
'''
Override for extra widget setup
Is called after __init__ has completed
'''
pass
def on_api_error(self, error_status=None, message=None, event_origin=None):
'''
API error handling
'''
pass
| 5 | 3 | 16 | 2 | 11 | 3 | 3 | 0.55 | 1 | 5 | 4 | 9 | 4 | 7 | 4 | 9 | 84 | 16 | 44 | 14 | 39 | 24 | 34 | 13 | 29 | 6 | 2 | 2 | 11 |
604 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.Client
|
class Client(Comm):
"""
API Client
Can connect to an api server and dispatch function calls to it
Attributes:
- id (str): unique id for this client instance
- dispatcher: which Dispatcher class to use for method dispatch
"""
dispatcher = Dispatcher
class widget(Comm.widget):
"""
Decorator to register a widget for this Client class
"""
widgets = {}
def __init__(self, name, remote_name=None):
"""
Keyword Arguments:
- remote_name (str): name of the widget (server side), defaults to <name>
"""
Comm.widget.__init__(self, name)
self.remote_name = remote_name or name
def __call__(self, fn):
Comm.widget.__call__(self, fn)
fn.remote_name = self.remote_name
return fn
def __init__(self, **kwargs):
self.id = None
super(Client, self).__init__(**kwargs)
def __repr__(self):
return "API-CLI-%s" % self.id
def wire(self, link):
super(Client, self).wire(link)
self.id = self.obtain_client_id()
def prepare_message(self, message):
message.meta.update(client=self.id)
return super(Client, self).prepare_message(message)
|
class Client(Comm):
'''
API Client
Can connect to an api server and dispatch function calls to it
Attributes:
- id (str): unique id for this client instance
- dispatcher: which Dispatcher class to use for method dispatch
'''
class widget(Comm.widget):
'''
Decorator to register a widget for this Client class
'''
def __init__(self, name, remote_name=None):
'''
Keyword Arguments:
- remote_name (str): name of the widget (server side), defaults to <name>
'''
pass
def __call__(self, fn):
pass
def __init__(self, name, remote_name=None):
pass
def __repr__(self):
pass
def wire(self, link):
pass
def prepare_message(self, message):
pass
| 8 | 3 | 4 | 0 | 3 | 1 | 1 | 0.64 | 1 | 1 | 0 | 5 | 4 | 1 | 4 | 28 | 50 | 14 | 22 | 12 | 14 | 14 | 22 | 12 | 14 | 1 | 4 | 0 | 6 |
605 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.ClientAwareServer
|
class ClientAwareServer(Server):
"""
API Server that keeps track of connected clients
allowing for independent two-way communication
Attributes:
- clients (DispatcherGroup): map of connected client wires
- inactive_timeout (float=0.0): clients that have not interacted
with the server in the specified timeframe will be closed and
removed.
- time (float): unix timestamp of last time cleanup was run
Events:
- new_client: called whenever a new client makes contact with
the server
payload:
- client (Comm): client dispatcher
- client_id (str): client id
"""
def __init__(self, **kwargs):
self.clients = DispatcherGroup()
super(ClientAwareServer, self).__init__(**kwargs)
self.inactive_timeout = float(kwargs.get("inactive_timeout",0.0))
self.time = time.time()
t = threading.Thread(target=self.cleanup)
t.daemon = True
t.start()
def wire(self, link):
super(ClientAwareServer, self).wire(link)
self.on("before_call", self.store_client)
self.on("after_call", self.cleanup)
@expose
def obtain_client_id(self):
id = str(uuid.uuid4())
n = 0
while id in self.clients:
id = str(uuid.uuid4())
n += 1
if n > 10000:
raise IOError("Unable to generate unique client id (10k tries)")
return id
def cleanup(self):
"""
removes inactive clients (will be run in its own thread, about once
every second)
"""
while self.inactive_timeout > 0:
self.time = time.time()
keys = []
for key, client in self.clients.items.items():
t = getattr(client, "active_at", 0)
if t > 0 and self.time - t > self.inactive_timeout:
client.kwargs["link"].disconnect()
keys.append(key)
for key in keys:
self.log_debug("Removing client (inactive): %s" % key)
del self.clients[key]
time.sleep(1)
def store_client(self, message, event_origin=None):
if message.meta.get("remote") and message.meta.get("client"):
client_id = message.meta.get("client")
if client_id and client_id not in self.clients:
remote = message.meta.get("remote")
self.log_debug("Establishing client wire: %s -> %s" % (client_id, remote))
conn_type, addr = tuple(remote.split("->"))
if conn_type == "connect":
connection = connect(addr)
elif conn_type == "listen":
connection = listen(addr)
else:
self.log_error("Unknown connection type supplied in 'remote' value in client message: %s" % conn_type)
return
client_link = link.Link()
client_wire = client_link.wire(
"main",
send=connection,
receive=connection
)
self.clients[client_id] = ProxyDispatcher(self, link=client_link)
self.clients[client_id].active_at = self.time
self.log_debug("Established client wire! (%s)" % client_id)
self.trigger("new_client", client=self.clients[client_id], id=client_id)
elif client_id:
self.clients[client_id].active_at = self.time
def __getitem__(self, k):
if k in self.clients:
return self.clients[k]
raise KeyError("Client not found: %s", k)
|
class ClientAwareServer(Server):
'''
API Server that keeps track of connected clients
allowing for independent two-way communication
Attributes:
- clients (DispatcherGroup): map of connected client wires
- inactive_timeout (float=0.0): clients that have not interacted
with the server in the specified timeframe will be closed and
removed.
- time (float): unix timestamp of last time cleanup was run
Events:
- new_client: called whenever a new client makes contact with
the server
payload:
- client (Comm): client dispatcher
- client_id (str): client id
'''
def __init__(self, **kwargs):
pass
def wire(self, link):
pass
@expose
def obtain_client_id(self):
pass
def cleanup(self):
'''
removes inactive clients (will be run in its own thread, about once
every second)
'''
pass
def store_client(self, message, event_origin=None):
pass
def __getitem__(self, k):
pass
| 8 | 2 | 13 | 1 | 11 | 1 | 3 | 0.3 | 1 | 9 | 3 | 3 | 6 | 3 | 6 | 34 | 107 | 21 | 66 | 22 | 58 | 20 | 58 | 21 | 51 | 6 | 5 | 3 | 18 |
606 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.Comm
|
class Comm(Base):
"""
API Communicator class, used as base for both client and server
classes
Attributes:
- blocking (bool): if True all request made with this communicator
will block until they receive a response
- timeout (flaot): if blocking is True this specifies a timeout for
blocking requests
- debug (bool): if True error responses sent over the api will contain
a full traceback
- path (str): xbahn path prefix for all api requests this communicator makes
- handlers (list): list of api handlers attached to this communicator
"""
class widget(object):
"""
Decorator to register a widget for this Communicator class
Attributes:
- widgets (dict): holds widgets registered to this communicator
via it's widget decorator
"""
widgets = {}
path = "widgets"
def __init__(self, name):
"""
Arguments:
- name (str): name of the widget
"""
self.name = name
def __call__(self, fn):
self.widgets[self.name] = fn
fn.name = self.name
return fn
def __getitem__(self, k):
return self.widgets.get(k)
timeout = 0
path_default = "comm"
def __init__(self, **kwargs):
"""
Keyword arguments:
- blocking (bool, False): if set to True, all dispatches will block until they
receive a response
- timeout (float, 0.0): if greater than zero any server responses longer than
the timeout will raise a timeout error
- debug (bool, False): if true, error responses over the api will contain a
full trace log
the complete message object, if false dispatched methods will return
the message.data content
- path (str): xbahn path
- handlers (list): list of api handler instances to attach to this communicator
"""
self.path = kwargs.get("path", self.path_default)
self.handlers = []
if "handlers" in kwargs:
handlers = kwargs.get("handlers")
if type(handlers) != list:
raise ValueError("handlers needs to be list of api Handler instances")
for handler in handlers:
self.add_handler(handler)
super(Comm, self).__init__(**kwargs)
self.blocking = bool(kwargs.get("blocking", True))
self.timeout = float(kwargs.get("timeout", 0))
self.debug = bool(kwargs.get("debug", False))
self.widgets = {}
def __getattr__(self, k):
return self.dispatcher(self, k, link=self.link)
def add_handler(self, handler):
if handler in self.handlers:
raise AssertionError("Handler already attached to this communicator")
self.handlers.append(handler)
def prepare_message(self, message):
"""
Prepares the message before sending it out
Returns:
- message.Message: the message
"""
message.meta.update(path=self.path)
for handler in self.handlers:
handler.outgoing(message, self)
return message
def on_receive(self, message=None, wire=None, event_origin=None):
"""
event handler bound to the receive event of the
link the server is wired too.
Arguments:
- message (message.Message): incoming message
Keyword arguments:
- event_origin (connection.Link)
"""
self.trigger("before_call", message)
fn_name = message.data
pmsg = self.prepare_message
try:
for handler in self.handlers:
handler.incoming(message, self)
fn = self.get_function(fn_name, message.path)
except Exception as inst:
wire.respond(message, ErrorMessage(str(inst)))
return
if callable(fn) and getattr(fn, "exposed", False):
try:
r = fn(*message.args, **message.kwargs)
if isinstance(r,Message):
wire.respond(message, pmsg(r))
else:
wire.respond(message, pmsg(Message(r)))
except Exception as inst:
if self.debug:
wire.respond(message, pmsg(ErrorMessage(str(traceback.format_exc()))))
else:
wire.respond(message, pmsg(ErrorMessage(str(inst))))
else:
wire.respond(
message,
pmsg(
ErrorMessage("action '%s' not exposed on API (%s)" % (fn_name, self.__class__.__name__)))
)
self.trigger("after_call", message)
def get_function(self, name, path):
widget_path = xbahn.path.append(self.path, "call", self.widget.path)
if xbahn.path.match(widget_path, path):
widget_name, client_id, widget_id = tuple(xbahn.path.tail(widget_path, path))
if widget_name not in self.widgets:
raise APIError("Widget instance not found on server (1)")
widget_id = xbahn.path.append(client_id, widget_id)
if widget_id not in self.widgets[widget_name]:
raise APIError("Widget instance not found on server (2)")
return getattr(self.widgets[widget_name][widget_id], name, None)
elif path == xbahn.path.append(self.path, "call"):
return getattr(self, name, None)
else:
raise AttributeError("Unknown call route")
def wire(self, link):
super(Comm, self).wire(link)
self.link.on("receive_%s" % xbahn.path.append(self.path,"call"), self.on_receive)
def has_widget(self, name, widget_id):
return name in self.widgets and widget_id in self.widgets[name]
def store_widget(self, widget):
if widget.name not in self.widgets:
self.widgets[widget.name] = DispatcherGroup()
self.widgets[widget.name][widget.id] = widget
def make_widget(self, id, name, dispatcher=None, **kwargs):
if self.has_widget(name, id):
return self.widgets[name][id]
if name not in self.widget.widgets:
return Widget(self, dispatcher=dispatcher)
return self.widget.widgets[name](self, id, dispatcher=dispatcher, **kwargs)
@expose
def request_widget(self, name, id):
self.log_debug("Got widget request %s -> %s" % (name, id))
if name in self.widgets:
if id in self.widgets[name]:
widget = self.widgets[name][id]
self.attach_remote(
widget.id,
widget.remote_name,
remote_name=widget.name,
**widget.init_kwargs
)
|
class Comm(Base):
'''
API Communicator class, used as base for both client and server
classes
Attributes:
- blocking (bool): if True all request made with this communicator
will block until they receive a response
- timeout (flaot): if blocking is True this specifies a timeout for
blocking requests
- debug (bool): if True error responses sent over the api will contain
a full traceback
- path (str): xbahn path prefix for all api requests this communicator makes
- handlers (list): list of api handlers attached to this communicator
'''
class widget(object):
'''
Decorator to register a widget for this Communicator class
Attributes:
- widgets (dict): holds widgets registered to this communicator
via it's widget decorator
'''
def __init__(self, name):
'''
Arguments:
- name (str): name of the widget
'''
pass
def __call__(self, fn):
pass
def __getitem__(self, k):
pass
def __init__(self, name):
'''
Keyword arguments:
- blocking (bool, False): if set to True, all dispatches will block until they
receive a response
- timeout (float, 0.0): if greater than zero any server responses longer than
the timeout will raise a timeout error
- debug (bool, False): if true, error responses over the api will contain a
full trace log
the complete message object, if false dispatched methods will return
the message.data content
- path (str): xbahn path
- handlers (list): list of api handler instances to attach to this communicator
'''
pass
def __getattr__(self, k):
pass
def add_handler(self, handler):
pass
def prepare_message(self, message):
'''
Prepares the message before sending it out
Returns:
- message.Message: the message
'''
pass
def on_receive(self, message=None, wire=None, event_origin=None):
'''
event handler bound to the receive event of the
link the server is wired too.
Arguments:
- message (message.Message): incoming message
Keyword arguments:
- event_origin (connection.Link)
'''
pass
def get_function(self, name, path):
pass
def wire(self, link):
pass
def has_widget(self, name, widget_id):
pass
def store_widget(self, widget):
pass
def make_widget(self, id, name, dispatcher=None, **kwargs):
pass
@expose
def request_widget(self, name, id):
pass
| 17 | 6 | 11 | 2 | 7 | 2 | 2 | 0.45 | 1 | 17 | 6 | 2 | 11 | 5 | 11 | 24 | 205 | 46 | 110 | 39 | 93 | 49 | 95 | 37 | 79 | 7 | 3 | 3 | 34 |
607 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.DispatcherGroup
|
class DispatcherGroup(EventMixin):
"""
Allows to maintain and access and call functions
on multiple dispatchers
"""
def __init__(self):
super(DispatcherGroup, self).__init__()
self.items = {}
def __len__(self):
return len(self.items.values())
def __delitem__(self, k):
self.remove(k)
def __iter__(self):
for k,v in self.items.items():
yield v
def __contains__(self, k):
return (k in self.items)
def __setitem__(self, k, v):
self.add(k, v)
def __getitem__(self, k):
return self.items.get(k)
def __getattr__(self, k):
dispatchers = self.items.values()
def dispatch(*args, **kwargs):
for dsp in dispatchers:
fn = getattr(dsp, k)
fn(*args, **kwargs)
return dispatch
def add(self, id, dispatcher):
if not isinstance(dispatcher, Dispatcher) and not isinstance(dispatcher, ProxyDispatcher) and isinstance(dispatcher, Comm):
raise ValueError("Only objects of type 'Comm', 'Dispatcher' and 'ProxyDispatcher' may be added")
self.items[id] = dispatcher
self.trigger("add", id=id, dispatcher=dispatcher)
def remove(self, id):
if id not in self.items:
raise KeyError("dispatcher with id %s not found" % id)
dispatcher = self.items.get(id)
del self.items[id]
self.trigger("remove", id=id, dispatcher=dispatcher)
def filter(self, **filters):
filtered = DispatcherGroup()
for id, dsp in self.items.items():
add = True
for f,v in filters.items():
if getattr(dsp, f, None) != v:
add = False
if add:
filtered[id] = dsp
return filtered
|
class DispatcherGroup(EventMixin):
'''
Allows to maintain and access and call functions
on multiple dispatchers
'''
def __init__(self):
pass
def __len__(self):
pass
def __delitem__(self, k):
pass
def __iter__(self):
pass
def __contains__(self, k):
pass
def __setitem__(self, k, v):
pass
def __getitem__(self, k):
pass
def __getattr__(self, k):
pass
def dispatch(*args, **kwargs):
pass
def add(self, id, dispatcher):
pass
def remove(self, id):
pass
def filter(self, **filters):
pass
| 13 | 1 | 4 | 0 | 4 | 0 | 2 | 0.09 | 1 | 6 | 3 | 0 | 11 | 1 | 11 | 16 | 67 | 18 | 45 | 23 | 32 | 4 | 45 | 23 | 32 | 5 | 2 | 3 | 20 |
608 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.Handler
|
class Handler(LogMixin, EventMixin):
"""
Base API Handler class
"""
def __init__(self, *args, **kwargs):
super(Handler, self).__init__()
self.setup(*args, **kwargs)
def outgoing(self, message, comm):
"""
override this to do something to an outgoing message before
it is sent.
raising an APIError here will halt sending of the message
"""
pass
def incoming(self, message, comm):
"""
override this to do something to an incoming message before
it is processed (executed)
raising an APIError here will halt processing of the message
"""
pass
def setup(self, *args, **kwargs):
"""
override this (instead of __init__) to setup your handler
"""
pass
|
class Handler(LogMixin, EventMixin):
'''
Base API Handler class
'''
def __init__(self, *args, **kwargs):
pass
def outgoing(self, message, comm):
'''
override this to do something to an outgoing message before
it is sent.
raising an APIError here will halt sending of the message
'''
pass
def incoming(self, message, comm):
'''
override this to do something to an incoming message before
it is processed (executed)
raising an APIError here will halt processing of the message
'''
pass
def setup(self, *args, **kwargs):
'''
override this (instead of __init__) to setup your handler
'''
pass
| 5 | 4 | 6 | 1 | 2 | 3 | 1 | 1.6 | 2 | 1 | 0 | 1 | 4 | 0 | 4 | 14 | 33 | 7 | 10 | 5 | 5 | 16 | 10 | 5 | 5 | 1 | 2 | 0 | 4 |
609 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.ProxyDispatcher
|
class ProxyDispatcher(object):
def __init__(self, comm, **kwargs):
self.comm = comm
self.link = kwargs.get("link")
self.kwargs = kwargs
def __nonzero__(self):
return True
def __getattr__(self, k):
return self.comm.dispatcher(self.comm, k, **self.kwargs)
|
class ProxyDispatcher(object):
def __init__(self, comm, **kwargs):
pass
def __nonzero__(self):
pass
def __getattr__(self, k):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 12 | 3 | 9 | 7 | 5 | 0 | 9 | 7 | 5 | 1 | 1 | 0 | 3 |
610 |
20c/xbahn
|
20c_xbahn/xbahn/api.py
|
xbahn.api.Server
|
class Server(Comm):
"""
API Server
"""
dispatcher = Dispatcher
def __repr__(self):
return "API-SRV"
def wire(self, link):
super(Server, self).wire(link)
@expose
def obtain_client_id(self):
return "$"
@expose
def attach_remote(self, id, name, **kwargs):
widget = self.make_widget(
id,
name,
**kwargs
)
self.store_widget(widget)
|
class Server(Comm):
'''
API Server
'''
def __repr__(self):
pass
def wire(self, link):
pass
@expose
def obtain_client_id(self):
pass
@expose
def attach_remote(self, id, name, **kwargs):
pass
| 7 | 1 | 3 | 0 | 3 | 0 | 1 | 0.18 | 1 | 1 | 0 | 7 | 4 | 0 | 4 | 28 | 25 | 5 | 17 | 9 | 10 | 3 | 11 | 7 | 6 | 1 | 4 | 0 | 4 |
611 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.NodeAdmin.Media
|
class Media:
css = {
"all": ("{}tree/css/page_info.css".format(settings.STATIC_URL),)}
js = (settings.JQUERY_LIB,
'{}tree/js/treenode.js'.format(settings.STATIC_URL),)
|
class Media:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 3 | 3 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
612 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/utility.py
|
tree.utility.Sitemap
|
class Sitemap(object):
"""
It creates sitemap.xml
"""
def __init__(self, request):
self.request = request
def _do_sitemap(self):
host = self.request.get_host()
set_to_return = []
for root in Node.objects.filter(parent__isnull=True):
for node in root.get_descendants():
if node.page:
regex = r'%s' % node.slug
url_sitemap = UrlSitemap(loc=regex)
if node.changefreq:
url_sitemap.changefreq = node.changefreq
if node.priority:
url_sitemap.priority = node.priority
set_to_return.append(url_sitemap)
if node.is_index:
regex = r''
url_sitemap = UrlSitemap(loc=regex)
set_to_return.append(url_sitemap)
tpl_str = render_to_string('tpl/sitemap.tpl.html',
{'set': set_to_return, 'host': host, 'today': date.today(), },
context_instance=RequestContext(self.request))
return tpl_str
|
class Sitemap(object):
'''
It creates sitemap.xml
'''
def __init__(self, request):
pass
def _do_sitemap(self):
pass
| 3 | 1 | 12 | 1 | 12 | 0 | 4 | 0.13 | 1 | 3 | 2 | 0 | 2 | 1 | 2 | 2 | 30 | 3 | 24 | 11 | 21 | 3 | 22 | 11 | 19 | 7 | 1 | 4 | 8 |
613 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/utility.py
|
tree.utility.UrlSitemap
|
class UrlSitemap(object):
"""
It defines sitemap url's structure to make sitemap.xml file
"""
def __init__(self, loc, lastmod=None, changefreq=None, priority=None):
self.loc = loc
self.lastmod = lastmod
self.changefreq = changefreq
self.priority = priority
|
class UrlSitemap(object):
'''
It defines sitemap url's structure to make sitemap.xml file
'''
def __init__(self, loc, lastmod=None, changefreq=None, priority=None):
pass
| 2 | 1 | 5 | 0 | 5 | 0 | 1 | 0.5 | 1 | 0 | 0 | 0 | 1 | 4 | 1 | 1 | 10 | 1 | 6 | 6 | 4 | 3 | 6 | 6 | 4 | 1 | 1 | 0 | 1 |
614 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.TemplateAdmin.Meta
|
class Meta:
model = Template
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
615 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.TemplateAdmin.Media
|
class Media:
js = (settings.JQUERY_LIB,
'{}tree/js/template.js'.format(settings.STATIC_URL),)
|
class Media:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
616 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.PageAdmin.Meta
|
class Meta:
model = Page
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
617 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.PageAdminForm.Meta
|
class Meta:
model = Page
exclude = ()
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
618 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.NodeAdmin.Meta
|
class Meta:
ordering = ['tree_id', 'lft']
model = Node
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
619 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.NodeForm.Meta
|
class Meta:
model = Node
exclude = ()
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
620 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.RobotAdmin.Meta
|
class Meta:
model = Robot
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
621 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/middleware/upy_context.py
|
tree.middleware.upy_context.SetUpyContextMiddleware
|
class SetUpyContextMiddleware(object):
"""
This middleware activates current publication in current thread.
In process_response it deactivates current publication.
"""
def process_request(self, request):
try:
match = resolve(request.path)
except Resolver404:
match = None
try:
return import_module(handler404)
except:
pass
if match and 'upy_context' in match.kwargs:
request.upy_context = match.kwargs['upy_context']
|
class SetUpyContextMiddleware(object):
'''
This middleware activates current publication in current thread.
In process_response it deactivates current publication.
'''
def process_request(self, request):
pass
| 2 | 1 | 11 | 0 | 11 | 0 | 4 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 16 | 0 | 12 | 3 | 10 | 4 | 12 | 3 | 10 | 4 | 1 | 2 | 4 |
622 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/utility.py
|
tree.utility.RobotTXT
|
class RobotTXT(object):
"""
It creates robots.txt
"""
def __init__(self, request):
self.request = request
def _do_robotstxt(self):
set_robot = {}
disallow_all = settings.DISALLOW_ALL_ROBOTS
if not disallow_all:
for root in Node.objects.filter(parent__isnull=True):
for node in root.get_descendants():
if node.page and node.disallow:
regex = r'{0}'.format(node.slug)
for robot in node.robots.all():
if robot.name_id in set_robot.keys():
set_robot[robot.name_id].append(regex)
else:
set_robot[robot.name_id] = [regex, ]
tpl_str = render_to_string('tpl/robots.tpl.html',
{'set': set_robot, 'disallow_all': disallow_all},
context_instance=RequestContext(self.request))
return tpl_str
|
class RobotTXT(object):
'''
It creates robots.txt
'''
def __init__(self, request):
pass
def _do_robotstxt(self):
pass
| 3 | 1 | 11 | 1 | 10 | 0 | 4 | 0.15 | 1 | 1 | 1 | 0 | 2 | 1 | 2 | 2 | 27 | 4 | 20 | 11 | 17 | 3 | 17 | 11 | 14 | 7 | 1 | 6 | 8 |
623 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/menu.py
|
tree.menu.Breadcrumb
|
class Breadcrumb(object):
"""
This class provides some tools to create and render tree structure breadcrumb in according to nodes' structure
created for your application.
It takes some arguments:
- request: simply http request
- leaf: the the leaf of breadcrumb (it's hidden in menu string)
- upy_context: it contains informations about current page and node
- view_hidden: if True then hidden nodes will be show
- g11n_depth: check g11n_depth in contrib.g11n.models documentation
"""
def __init__(self, request, leaf, upy_context, view_hidden=False):
self.request = request
self.leaf = leaf
self.upy_context = upy_context
self.view_hidden = view_hidden
def __do_menu(self, menu_as, show_leaf, current_linkable, class_current, chars="", render=True):
nodes = self.leaf.get_ancestors()[1:]
list_nodes = list(nodes)
if show_leaf:
list_nodes.append(self.leaf)
list_nodes = prepare_nodes(list_nodes, self.request)
if not render:
return list_nodes
menutpl = render_to_string('tpl/breadcrumb_%s.tpl.html' % menu_as,
{'NODE': self.upy_context['NODE'], 'nodes': list_nodes, 'chars': chars,
'current_linkable': current_linkable,
'class_current': class_current,
'view_hidden': self.view_hidden}, context_instance=RequestContext(self.request))
return mark_safe(menutpl)
def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"):
"""
It returns breadcrumb as ul
"""
return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"):
"""
It returns breadcrumb as p
"""
return self.__do_menu("as_p", show_leaf, current_linkable, class_current)
def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"):
"""
It returns breadcrumb as string
"""
return self.__do_menu("as_string", show_leaf, current_linkable, class_current, chars)
def as_tree(self):
"""
It returns a menu not cached as tree
"""
return self.__do_menu("", render=False)
|
class Breadcrumb(object):
'''
This class provides some tools to create and render tree structure breadcrumb in according to nodes' structure
created for your application.
It takes some arguments:
- request: simply http request
- leaf: the the leaf of breadcrumb (it's hidden in menu string)
- upy_context: it contains informations about current page and node
- view_hidden: if True then hidden nodes will be show
- g11n_depth: check g11n_depth in contrib.g11n.models documentation
'''
def __init__(self, request, leaf, upy_context, view_hidden=False):
pass
def __do_menu(self, menu_as, show_leaf, current_linkable, class_current, chars="", render=True):
pass
def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"):
'''
It returns breadcrumb as ul
'''
pass
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"):
'''
It returns breadcrumb as p
'''
pass
def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"):
'''
It returns breadcrumb as string
'''
pass
def as_tree(self):
'''
It returns a menu not cached as tree
'''
pass
| 7 | 5 | 7 | 1 | 5 | 2 | 1 | 0.79 | 1 | 1 | 0 | 0 | 6 | 4 | 6 | 6 | 60 | 10 | 28 | 14 | 21 | 22 | 24 | 14 | 17 | 3 | 1 | 1 | 8 |
624 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/conf.py
|
tree.conf.TreeConf
|
class TreeConf(AppConf):
STATIC_URL = u'/static/'
USE_GLOBAL_TEMPLATES_DIR = True
DISALLOW_ALL_ROBOTS = True
JQUERY_LIB = u"{}{}".format(
getattr(settings, u'STATIC_URL', u'/static/'),
u"tree/js/jquery-2.1.0.min.js"
)
JQUERYUI_LIB = u"{}{}".format(
getattr(settings, u'STATIC_URL', u'/static/'),
u"tree/js/jquery-ui-1.10.4.custom.min.js"
)
JQUERYUI_CSSLIB = u"{}{}".format(
getattr(settings, u'STATIC_URL', u'/static/'),
u"tree/css/smoothness/jquery-ui-1.10.4.custom.min.css"
)
def configure_static_url(self, value):
if not getattr(settings, 'STATIC_URL', None):
self._meta.holder.STATIC_URL = value
return value
return getattr(settings, 'STATIC_URL')
def configure_use_global_templates_dir(self, value):
res = getattr(settings, 'USE_GLOBAL_TEMPLATES_DIR', None)
if not res:
self._meta.holder.USE_GLOBAL_TEMPLATES_DIR = value
res = value
if res and not os.path.exists(u"{}/{}".format(os.getcwd(), 'templates')):
os.mkdir(u"{}/{}".format(os.getcwd(), 'templates'))
if res:
list_dirs = ['templates', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')]
list_dirs.extend(
list([u"templates/{}".format(tdir) for tdir in os.listdir(u"{}/{}".format(os.getcwd(), 'templates'))])
)
if hasattr(settings, 'TEMPLATE_DIRS'):
t_dirs = list(getattr(settings, 'TEMPLATE_DIRS', []))
t_dirs.extend(list_dirs)
self._meta.holder.TEMPLATE_DIRS = t_dirs
else:
self._meta.holder.TEMPLATE_DIRS = list_dirs
return res
def configure_disallow_all_robots(self, value):
if not getattr(settings, 'DISALLOW_ALL_ROBOTS', None):
self._meta.holder.DISALLOW_ALL_ROBOTS = value
return value
return getattr(settings, 'DISALLOW_ALL_ROBOTS')
def configure_jquery_lib(self, value):
if not getattr(settings, 'JQUERY_LIB', None):
self._meta.holder.JQUERY_LIB = value
return value
return getattr(settings, 'JQUERY_LIB')
def configure_jqueryui_lib(self, value):
if not getattr(settings, 'JQUERYUI_LIB', None):
self._meta.holder.JQUERYUI_LIB = value
return value
return getattr(settings, 'JQUERYUI_LIB')
def configure_jqueryui_csslib(self, value):
if not getattr(settings, 'JQUERYUI_CSSLIB', None):
self._meta.holder.JQUERYUI_CSSLIB = value
return value
return getattr(settings, 'JQUERYUI_CSSLIB')
def configure(self):
if not getattr(settings, 'MIDDLEWARE_CLASSES', None):
self._meta.holder.MIDDLEWARE_CLASSES = ['tree.middleware.upy_context.SetUpyContextMiddleware']
else:
middleware = list(getattr(settings, 'MIDDLEWARE_CLASSES', []))
middleware.append('tree.middleware.upy_context.SetUpyContextMiddleware')
self._meta.holder.MIDDLEWARE_CLASSES = middleware
if not getattr(settings, 'TEMPLATE_CONTEXT_PROCESSORS', None):
self._meta.holder.TEMPLATE_CONTEXT_PROCESSORS = ['tree.template_context.context_processors.set_meta']
else:
middleware = list(getattr(settings, 'TEMPLATE_CONTEXT_PROCESSORS', []))
middleware.append('tree.template_context.context_processors.set_meta')
self._meta.holder.TEMPLATE_CONTEXT_PROCESSORS = middleware
return self.configured_data
|
class TreeConf(AppConf):
def configure_static_url(self, value):
pass
def configure_use_global_templates_dir(self, value):
pass
def configure_disallow_all_robots(self, value):
pass
def configure_jquery_lib(self, value):
pass
def configure_jqueryui_lib(self, value):
pass
def configure_jqueryui_csslib(self, value):
pass
def configure_static_url(self, value):
pass
| 8 | 0 | 8 | 0 | 8 | 0 | 3 | 0 | 1 | 1 | 0 | 0 | 7 | 0 | 7 | 7 | 81 | 7 | 74 | 18 | 66 | 0 | 60 | 18 | 52 | 5 | 1 | 2 | 18 |
625 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/admin.py
|
tree.admin.PageAdminForm
|
class PageAdminForm(forms.ModelForm):
"""
Admin's Page form. It cleans regex field
"""
def clean_regex(self):
regex = self.cleaned_data['regex']
match_list = re.findall(r"\<(.*?)\>", regex)
for word in match_list:
if match_list.count(word) > 1:
raise forms.ValidationError(
_("Thera are some variables in regex with the same name. It's not permitted."))
return regex
class Meta:
model = Page
exclude = ()
static_vars = forms.RegexField(
required=False, widget=forms.Textarea(attrs={"cols": '80', "rows": '4'}),
regex='^(\{((?:"\w+"|\'\w+\'):(?:"\w+"|\'\w+\'),?\s?)+\})*$',
help_text=_(
u"""Set the dictionary of static parameters of the page in a regular format:
{\"param1\":\"value1\", \"param2\":\"value2\"}."""
)
)
|
class PageAdminForm(forms.ModelForm):
'''
Admin's Page form. It cleans regex field
'''
def clean_regex(self):
pass
class Meta:
| 3 | 1 | 9 | 1 | 8 | 0 | 3 | 0.15 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 27 | 4 | 20 | 9 | 17 | 3 | 12 | 9 | 9 | 3 | 1 | 2 | 3 |
626 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/admin.py
|
tree.admin.NodeForm
|
class NodeForm(forms.ModelForm):
"""
Admin's form for Node model. It cleans slug, parent and page fields
"""
class Meta:
model = Node
exclude = ()
def clean(self):
cleaned_data = super(NodeForm, self).clean()
page = cleaned_data['page']
parent = cleaned_data['parent']
slug = None
if self.instance == parent:
raise forms.ValidationError(_("A node may not be made a child of itself."))
if parent:
slug = parent.slug
if page:
if slug:
slug += "/%s" % page.slug
else:
slug = page.slug
basenode = parent.get_root()
if page: # check the slug validity only if this is a page node with its own slug
for node in basenode.get_descendants(include_self=False):
if slug == node.slug and node.pk != self.instance.pk:
raise forms.ValidationError(_(
"You cannot use the same slug (/{0}) in two different nodes of the same structure".format(
slug)))
if node.page and node.page == page and node.pk != self.instance.pk:
raise forms.ValidationError(_("You can use page only in one node of the same structure"))
return cleaned_data
|
class NodeForm(forms.ModelForm):
'''
Admin's form for Node model. It cleans slug, parent and page fields
'''
class Meta:
def clean(self):
pass
| 3 | 1 | 24 | 0 | 24 | 1 | 9 | 0.14 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 33 | 2 | 28 | 11 | 25 | 4 | 25 | 11 | 22 | 9 | 1 | 4 | 9 |
627 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/admin.py
|
tree.admin.NodeAdmin
|
class NodeAdmin(TreeEditor):
"""
This is the option class for Node Admin
"""
def page_info(self):
"""
It's renders an html to show through jQuery with page informations
"""
html = render_to_string("page_info.html", {'node': self, 'STATIC_URL': settings.STATIC_URL})
return html
page_info.short_description = _(u"Info page")
page_info.allow_tags = True
list_display = ('pk', 'name', 'page', page_info, 'presentation_type', 'hide_in_navigation', 'is_index')
list_per_page = 900 #we should have all objects on one page
list_editable = ('name',)
fieldsets = (('', {'fields': (('page', 'name', 'parent',), ('is_index', 'hide_in_navigation', 'hide_in_url',),
('value_regex', 'show_if_logged', 'groups'),), }),
(_('Sitemap configuration'), {'fields': (('changefreq', 'priority'),), }),
(_('Robots configuration'), {'fields': (('robots', 'disallow'),), }),)
form = NodeForm
actions = ['hide_selected', 'protect_selected']
save_on_top = True
def parent_id(self, obj):
return obj.parent and obj.parent.id or '0'
def hide_selected(self, request, queryset):
"""
It marks as hidden all selected nodes
"""
queryset.update(hide_in_navigation=True)
hide_selected.short_description = _("Mark selected nodes as hidden")
def protect_selected(self, request, queryset):
"""
It marks as protected all selected nodes
"""
queryset.update(protected=True)
protect_selected.short_description = _("Mark selected nodes as protected")
class Meta:
ordering = ['tree_id', 'lft']
model = Node
class Media:
css = {"all": ("{}tree/css/page_info.css".format(settings.STATIC_URL),)}
js = (settings.JQUERY_LIB,
'{}tree/js/treenode.js'.format(settings.STATIC_URL),)
|
class NodeAdmin(TreeEditor):
'''
This is the option class for Node Admin
'''
def page_info(self):
'''
It's renders an html to show through jQuery with page informations
'''
pass
def parent_id(self, obj):
pass
def hide_selected(self, request, queryset):
'''
It marks as hidden all selected nodes
'''
pass
def protect_selected(self, request, queryset):
'''
It marks as protected all selected nodes
'''
pass
class Meta:
class Media:
| 7 | 4 | 5 | 0 | 2 | 2 | 1 | 0.42 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 54 | 11 | 31 | 19 | 24 | 13 | 27 | 19 | 20 | 1 | 1 | 0 | 4 |
628 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.TemplateAdminForm.Meta
|
class Meta:
model = Template
exclude = ()
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
629 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.ViewAdmin.Media
|
class Media:
js = (settings.JQUERY_LIB,
'{}tree/js/view.js'.format(settings.STATIC_URL),)
|
class Media:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
630 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.ViewAdminForm.Meta
|
class Meta:
model = View
exclude = ()
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
631 |
20tab/twentytab-tree
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20tab_twentytab-tree/tree/admin.py
|
tree.admin.ViewAdmin.Meta
|
class Meta:
model = View
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
632 |
20tab/twentytab-tree
|
20tab_twentytab-tree/tree/menu.py
|
tree.menu.Menu
|
class Menu(object):
"""
This class provides some tools to create and render tree structure menu in according to nodes' structure
created for your application.
It takes some arguments:
- request: simply http request
- root: the root of menu (it's hidden in menu string)
- upy_context: it contains informations about current page and node
- menu_depth: it's depth level for menu introspection
- view_hidden: if True then hidden nodes will be shown
- g11n_depth: check g11n_depth in contrib.g11n.models documentation
"""
def __init__(self, request, root, upy_context, menu_depth=0, view_hidden=False):
self.request = request
self.upy_context = upy_context
self.root = root
self.menu_depth = menu_depth
self.view_hidden = view_hidden
def __do_menu(self, menu_as, current_linkable=False, class_current="",
chars="", before_1="", after_1="", before_all="",
after_all="", render=True):
nodes = self.root.get_descendants()
list_nodes = prepare_nodes(list(nodes), self.request)
if not render:
return list_nodes
if self.menu_depth != 0:
relative_depth = self.menu_depth + self.root.level
else:
relative_depth = 0
return render_to_string('tpl/menu_%s.tpl.html' % menu_as,
{'NODE': self.upy_context['NODE'], 'nodes': list_nodes, 'chars': chars,
'current_linkable': current_linkable,
'menu_depth': relative_depth, 'class_current': class_current,
'view_hidden': self.view_hidden, 'before_1': before_1,
'after_1': after_1, 'before_all': before_all, 'after_all': after_all,
}, context_instance=RequestContext(self.request))
def as_ul(self, current_linkable=False, class_current="active_link",
before_1="", after_1="", before_all="", after_all=""):
"""
It returns menu as ul
"""
return self.__do_menu("as_ul", current_linkable, class_current,
before_1=before_1, after_1=after_1, before_all=before_all, after_all=after_all)
def as_p(self, current_linkable=False, class_current="active_link"):
"""
It returns menu as p
"""
return self.__do_menu("as_p", current_linkable, class_current)
def as_string(self, chars, current_linkable=False, class_current="active_link"):
"""
It returns menu as string
"""
return self.__do_menu("as_string", current_linkable, class_current, chars)
def as_tree(self):
"""
It returns a menu not cached as tree
"""
return self.__do_menu("", render=False)
|
class Menu(object):
'''
This class provides some tools to create and render tree structure menu in according to nodes' structure
created for your application.
It takes some arguments:
- request: simply http request
- root: the root of menu (it's hidden in menu string)
- upy_context: it contains informations about current page and node
- menu_depth: it's depth level for menu introspection
- view_hidden: if True then hidden nodes will be shown
- g11n_depth: check g11n_depth in contrib.g11n.models documentation
'''
def __init__(self, request, root, upy_context, menu_depth=0, view_hidden=False):
pass
def __do_menu(self, menu_as, current_linkable=False, class_current="",
chars="", before_1="", after_1="", before_all="",
after_all="", render=True):
pass
def as_ul(self, current_linkable=False, class_current="active_link",
before_1="", after_1="", before_all="", after_all=""):
'''
It returns menu as ul
'''
pass
def as_p(self, current_linkable=False, class_current="active_link"):
'''
It returns menu as p
'''
pass
def as_string(self, chars, current_linkable=False, class_current="active_link"):
'''
It returns menu as string
'''
pass
def as_tree(self):
'''
It returns a menu not cached as tree
'''
pass
| 7 | 5 | 8 | 1 | 6 | 2 | 1 | 0.66 | 1 | 1 | 0 | 0 | 6 | 5 | 6 | 6 | 67 | 9 | 35 | 18 | 25 | 23 | 24 | 15 | 17 | 3 | 1 | 1 | 8 |
633 |
20tab/twentytab-treeeditor
|
20tab_twentytab-treeeditor/treeeditor/conf.py
|
treeeditor.conf.TreeEditorConf
|
class TreeEditorConf(AppConf):
STATIC_URL = u'/static/'
TREE_EDITOR_INCLUDE_ANCESTORS = False
TREE_EDITOR_OBJECT_PERMISSIONS = False
JQUERY_LIB = u"{}{}".format(u'/static/', u"treeeditor/js/jquery-2.1.0.min.js")
JQUERYUI_LIB = u"{}{}".format(u'/static/', u"treeeditor/js/jquery-ui-1.10.4.custom.min.js")
JQUERYUI_CSSLIB = u"{}{}".format(u'/static/', u"treeeditor/css/smoothness/jquery-ui-1.10.4.custom.min.css")
def configure_static_url(self, value):
if not getattr(settings, 'STATIC_URL', None):
self._meta.holder.STATIC_URL = value
return value
return getattr(settings, 'STATIC_URL')
def configure_tree_editor_include_ancestors(self, value):
if not getattr(settings, 'TREE_EDITOR_INCLUDE_ANCESTORS', None):
self._meta.holder.TREE_EDITOR_INCLUDE_ANCESTORS = value
return value
return getattr(settings, 'TREE_EDITOR_INCLUDE_ANCESTORS')
def configure_tree_editor_object_permissions(self, value):
if not hasattr(settings, 'TREE_EDITOR_OBJECT_PERMISSIONS'):
self._meta.holder.TREE_EDITOR_OBJECT_PERMISSIONS = value
return value
return getattr(settings, 'TREE_EDITOR_OBJECT_PERMISSIONS')
def configure_jquery_lib(self, value):
if not getattr(settings, 'JQUERY_LIB', None):
self._meta.holder.JQUERY_LIB = value
return value
return getattr(settings, 'JQUERY_LIB')
def configure_jqueryui_lib(self, value):
if not getattr(settings, 'JQUERYUI_LIB', None):
self._meta.holder.JQUERYUI_LIB = value
return value
return getattr(settings, 'JQUERYUI_LIB')
def configure_jqueryui_csslib(self, value):
if not getattr(settings, 'JQUERYUI_CSSLIB', None):
self._meta.holder.JQUERYUI_CSSLIB = value
return value
return getattr(settings, 'JQUERYUI_CSSLIB')
|
class TreeEditorConf(AppConf):
def configure_static_url(self, value):
pass
def configure_tree_editor_include_ancestors(self, value):
pass
def configure_tree_editor_object_permissions(self, value):
pass
def configure_jquery_lib(self, value):
pass
def configure_jqueryui_lib(self, value):
pass
def configure_jqueryui_csslib(self, value):
pass
| 7 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 6 | 0 | 6 | 6 | 43 | 6 | 37 | 13 | 30 | 0 | 37 | 13 | 30 | 2 | 1 | 1 | 12 |
634 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/admin.py
|
twentytab.admin.ButtonForm
|
class ButtonForm(object):
"""
It defines a button that you can locate near the history button in change_form.html as a form
"""
def __init__(self, name, submit_value, form_action, input_dict, form_method="post", css_class=None):
"""
Use it to create a ButtonableForm. It takes following parameters:
'name' is the form's name,
'submit_value' is the button's value,
'form_action' is the form's action,
'form_method' is the form's method,
'css_class' is the class selector
"""
self.name = name
self.submit_value = submit_value
self.form_action = form_action
self.form_method = form_method
self.input_dict = input_dict # {'name':'value',}
self.css_class = css_class
|
class ButtonForm(object):
'''
It defines a button that you can locate near the history button in change_form.html as a form
'''
def __init__(self, name, submit_value, form_action, input_dict, form_method="post", css_class=None):
'''
Use it to create a ButtonableForm. It takes following parameters:
'name' is the form's name,
'submit_value' is the button's value,
'form_action' is the form's action,
'form_method' is the form's method,
'css_class' is the class selector
'''
pass
| 2 | 2 | 15 | 0 | 7 | 9 | 1 | 1.5 | 1 | 0 | 0 | 0 | 1 | 6 | 1 | 1 | 20 | 1 | 8 | 8 | 6 | 12 | 8 | 8 | 6 | 1 | 1 | 0 | 1 |
635 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/admin.py
|
twentytab.admin.ButtonLink
|
class ButtonLink(object):
"""
It defines a button that you can locate near the history button in change_form.html as a link
"""
def __init__(self, short_description, link, css_id=None, css_class=None):
"""
Use it to create a ButtonableLink. It takes following parameters:
'short_description' is what you want display in this link,
'link' is the value of this link,
'css_id' is the id selector,
'css_class' is the class selector
"""
self.short_description = short_description
self.link = link
self.css_id = css_id
self.css_class = css_class
|
class ButtonLink(object):
'''
It defines a button that you can locate near the history button in change_form.html as a link
'''
def __init__(self, short_description, link, css_id=None, css_class=None):
'''
Use it to create a ButtonableLink. It takes following parameters:
'short_description' is what you want display in this link,
'link' is the value of this link,
'css_id' is the id selector,
'css_class' is the class selector
'''
pass
| 2 | 2 | 12 | 0 | 5 | 7 | 1 | 1.67 | 1 | 0 | 0 | 0 | 1 | 4 | 1 | 1 | 17 | 1 | 6 | 6 | 4 | 10 | 6 | 6 | 4 | 1 | 1 | 0 | 1 |
636 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/admin.py
|
twentytab.admin.ButtonableModelAdmin
|
class ButtonableModelAdmin(admin.ModelAdmin):
"""
Use this admin only if you want apply custom button on the change_form template in admin panel.
"""
buttons_link = []
buttons_form = []
def add_view(self, request, form_url='', extra_context={}):
extra_context['buttons_link'] = self.buttons_link
extra_context['buttons_form'] = self.buttons_form
extra_context['button_object_id'] = ''
return super(ButtonableModelAdmin, self).add_view(request, form_url, extra_context)
def change_view(self, request, object_id, form_url='', extra_context={}):
"""
It adds ButtonLinks and ButtonForms to extra_context used in the change_form template
"""
extra_context['buttons_link'] = self.buttons_link
extra_context['buttons_form'] = self.buttons_form
extra_context['button_object_id'] = object_id
return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
|
class ButtonableModelAdmin(admin.ModelAdmin):
'''
Use this admin only if you want apply custom button on the change_form template in admin panel.
'''
def add_view(self, request, form_url='', extra_context={}):
pass
def change_view(self, request, object_id, form_url='', extra_context={}):
'''
It adds ButtonLinks and ButtonForms to extra_context used in the change_form template
'''
pass
| 3 | 2 | 7 | 0 | 5 | 2 | 1 | 0.46 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 21 | 2 | 13 | 5 | 10 | 6 | 13 | 5 | 10 | 1 | 1 | 0 | 2 |
637 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/admin.py
|
twentytab.admin.HiddenModelAdmin
|
class HiddenModelAdmin(admin.ModelAdmin):
def get_model_perms(self, *args, **kwargs):
perms = admin.ModelAdmin.get_model_perms(self, *args, **kwargs)
perms['list_hide'] = True
return perms
|
class HiddenModelAdmin(admin.ModelAdmin):
def get_model_perms(self, *args, **kwargs):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 0 | 5 | 3 | 3 | 0 | 5 | 3 | 3 | 1 | 1 | 0 | 1 |
638 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/forms.py
|
twentytab.forms.NullTrueField
|
class NullTrueField(forms.NullBooleanField):
"""
A field whose valid values are True and False as None. Invalid values are
cleaned to None.
"""
widget = NullCheckboxWidget
|
class NullTrueField(forms.NullBooleanField):
'''
A field whose valid values are True and False as None. Invalid values are
cleaned to None.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | 0 | 2 | 2 | 1 | 4 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
639 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/fields.py
|
twentytab.fields.CountryField
|
class CountryField(models.CharField):
"""
Is a CharField with the complete list of countries as choices.
"""
def __init__(self, *args, **kwargs):
kwargs.setdefault(u'max_length', 2)
kwargs.setdefault(u'choices', COUNTRIES)
super(CountryField, self).__init__(*args, **kwargs)
def get_internal_type(self):
"""
Returns internal type of this field: CharField as string
"""
return "CharField"
|
class CountryField(models.CharField):
'''
Is a CharField with the complete list of countries as choices.
'''
def __init__(self, *args, **kwargs):
pass
def get_internal_type(self):
'''
Returns internal type of this field: CharField as string
'''
pass
| 3 | 2 | 5 | 1 | 3 | 2 | 1 | 0.86 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 16 | 3 | 7 | 3 | 4 | 6 | 7 | 3 | 4 | 1 | 1 | 0 | 2 |
640 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/fields.py
|
twentytab.fields.NullTrueField
|
class NullTrueField(models.NullBooleanField):
def from_db_value(self, value, expression, connection, context):
return value == True
def to_python(self, value):
if value is True:
return value
return False
def get_prep_value(self, value):
if value is None or value is False:
return None
return True
def formfield(self, **kwargs):
defaults = {
'form_class': forms.NullTrueField,
'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text}
defaults.update(kwargs)
return super(NullTrueField, self).formfield(**defaults)
|
class NullTrueField(models.NullBooleanField):
def from_db_value(self, value, expression, connection, context):
pass
def to_python(self, value):
pass
def get_prep_value(self, value):
pass
def formfield(self, **kwargs):
pass
| 5 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 4 | 23 | 4 | 19 | 6 | 14 | 0 | 15 | 6 | 10 | 2 | 1 | 1 | 6 |
641 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/widgets.py
|
twentytab.widgets.CountrySelect
|
class CountrySelect(forms.Select):
allow_multiple_selected = False
def render(self, name, value, attrs=None, choices=()):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [format_html('<select{0}>', flatatt(final_attrs))]
options = self.render_options(choices, [value])
if options:
output.append(options)
output.append('</select>')
return mark_safe('\n'.join(output))
def render_options(self, choices, selected_choices):
# Normalize to strings.
selected_choices = set(force_text(v) for v in selected_choices)
output = []
for option_value, option_label in chain(self.choices, choices):
if isinstance(option_label, (list, tuple)):
opt_val = ""
for el in CONTINENTS:
if option_value == u"{}".format(el[1]):
opt_val = el[0]
output.append(format_html('<optgroup label="{0}" class="{1}">',
force_text(option_value), force_text(opt_val)))
for option in option_label:
output.append(self.render_option(selected_choices, *option))
output.append('</optgroup>')
else:
output.append(self.render_option(selected_choices, option_value, option_label))
return '\n'.join(output)
|
class CountrySelect(forms.Select):
def render(self, name, value, attrs=None, choices=()):
pass
def render_options(self, choices, selected_choices):
pass
| 3 | 0 | 14 | 1 | 13 | 1 | 5 | 0.04 | 1 | 4 | 0 | 0 | 2 | 0 | 2 | 2 | 32 | 3 | 28 | 12 | 25 | 1 | 27 | 12 | 24 | 6 | 1 | 4 | 9 |
642 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/widgets.py
|
twentytab.widgets.Div
|
class Div(Widget):
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
return format_html('<div{0}>\r\n{1}</div>',
flatatt(final_attrs),
force_text(value))
|
class Div(Widget):
def render(self, name, value, attrs=None):
pass
| 2 | 0 | 7 | 0 | 7 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 1 | 8 | 3 | 6 | 0 | 6 | 3 | 4 | 2 | 1 | 1 | 2 |
643 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/widgets.py
|
twentytab.widgets.NullCheckboxWidget
|
class NullCheckboxWidget(forms.CheckboxInput):
def render(self, name, value, attrs=None):
final_attrs = self.build_attrs(base_attrs=attrs, extra_attrs={'type': 'checkbox', 'name': name})
try:
result = self.check_test(value)
except: # Silently catch exceptions
result = False
if result:
final_attrs['checked'] = 'checked'
if not (value is True or value is False or value is None or value == ''):
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_text(value)
return mark_safe(u'<input%s />' % flatatt(final_attrs))
def value_from_datadict(self, data, files, name):
if name not in data:
# A missing value means False because HTML form submission does not
# send results for unselected checkboxes.
return False
value = data.get(name)
# Translate true and false strings to boolean values.
values = {'on': True, 'false': False}
if isinstance(value, str):
value = values.get(value.lower(), value)
return value
def _has_changed(self, initial, data):
# Sometimes data or initial could be None or u'' which should be the
# same thing as False.
return bool(initial) != bool(data)
|
class NullCheckboxWidget(forms.CheckboxInput):
def render(self, name, value, attrs=None):
pass
def value_from_datadict(self, data, files, name):
pass
def _has_changed(self, initial, data):
pass
| 4 | 0 | 9 | 0 | 7 | 2 | 3 | 0.32 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 3 | 31 | 3 | 22 | 8 | 18 | 7 | 22 | 8 | 18 | 4 | 1 | 1 | 8 |
644 |
20tab/twentytab-utils
|
20tab_twentytab-utils/twentytab/fields.py
|
twentytab.fields.ContinentCountryField
|
class ContinentCountryField(models.CharField):
"""
Is a CharField with the complete list of countries as choices.
"""
def __init__(self, *args, **kwargs):
kwargs.setdefault(u'max_length', 2)
kwargs.setdefault(u'choices', CONTINENT_COUNTRIES)
super(ContinentCountryField, self).__init__(*args, **kwargs)
def get_internal_type(self):
"""
Returns internal type of this field: CharField as string
"""
return "CharField"
|
class ContinentCountryField(models.CharField):
'''
Is a CharField with the complete list of countries as choices.
'''
def __init__(self, *args, **kwargs):
pass
def get_internal_type(self):
'''
Returns internal type of this field: CharField as string
'''
pass
| 3 | 2 | 5 | 1 | 3 | 2 | 1 | 0.86 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 16 | 3 | 7 | 3 | 4 | 6 | 7 | 3 | 4 | 1 | 1 | 0 | 2 |
645 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Number
|
class Number(Validator):
"""Number/float validator"""
value_type = float
tag = "num"
constraints = [con.Min, con.Max]
def _is_valid(self, value):
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
class Number(Validator):
'''Number/float validator'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.17 | 1 | 3 | 0 | 0 | 1 | 0 | 1 | 13 | 9 | 2 | 6 | 5 | 4 | 1 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
646 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Null
|
class Null(Validator):
"""Validates null"""
value_type = None
tag = "null"
def _is_valid(self, value):
return value is None
|
class Null(Validator):
'''Validates null'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 13 | 8 | 2 | 5 | 4 | 3 | 1 | 5 | 4 | 3 | 1 | 2 | 0 | 1 |
647 |
23andMe/Yamale
|
23andMe_Yamale/yamale/yamale_error.py
|
yamale.yamale_error.YamaleError
|
class YamaleError(ValueError):
def __init__(self, results):
super(YamaleError, self).__init__("\n".join([str(x) for x in list(filter(lambda x: not x.isValid(), results))]))
self.message = self.args[0]
self.results = results
|
class YamaleError(ValueError):
def __init__(self, results):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 4 | 0 | 0 | 1 | 2 | 1 | 12 | 5 | 0 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 4 | 0 | 1 |
648 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.LengthMin
|
class LengthMin(Constraint):
keywords = {"min": int}
fail = "Length of %s is less than %s"
def _is_valid(self, value):
return self.min <= len(value)
def _fail(self, value):
return self.fail % (value, self.min)
|
class LengthMin(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 7 | 9 | 2 | 7 | 5 | 4 | 0 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
649 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.Max
|
class Max(Constraint):
fail = "%s is greater than %s"
def __init__(self, value_type, kwargs):
self.keywords = {"max": value_type}
super(Max, self).__init__(value_type, kwargs)
def _is_valid(self, value):
return self.max >= value
def _fail(self, value):
return self.fail % (value, self.max)
|
class Max(Constraint):
def __init__(self, value_type, kwargs):
pass
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 8 | 12 | 3 | 9 | 6 | 5 | 0 | 9 | 6 | 5 | 1 | 2 | 0 | 3 |
650 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.Min
|
class Min(Constraint):
fail = "%s is less than %s"
def __init__(self, value_type, kwargs):
self.keywords = {"min": value_type}
super(Min, self).__init__(value_type, kwargs)
def _is_valid(self, value):
return self.min <= value
def _fail(self, value):
return self.fail % (value, self.min)
|
class Min(Constraint):
def __init__(self, value_type, kwargs):
pass
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 8 | 12 | 3 | 9 | 6 | 5 | 0 | 9 | 6 | 5 | 1 | 2 | 0 | 3 |
651 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.StringEndsWith
|
class StringEndsWith(Constraint):
keywords = {"ends_with": str, "ignore_case": bool}
fail = "%s does not end with %s"
def _is_valid(self, value):
# Check if the function has only been called due to ignore_case
if self.ends_with is not None:
if self.ignore_case is not None:
if not self.ignore_case:
return value.endswith(self.ends_with)
else:
length = len(self.ends_with)
if length <= len(value):
return value[-length:].casefold() == self.ends_with.casefold()
else:
return False
else:
return value.endswith(self.ends_with)
else:
return True
def _fail(self, value):
return self.fail % (value, self.ends_with)
|
class StringEndsWith(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 9 | 0 | 9 | 1 | 3 | 0.05 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 7 | 23 | 2 | 20 | 6 | 17 | 1 | 16 | 6 | 13 | 5 | 2 | 4 | 6 |
652 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.StringEquals
|
class StringEquals(Constraint):
keywords = {"equals": str, "ignore_case": bool}
fail = "%s does not equal %s"
def _is_valid(self, value):
# Check if the function has only been called due to ignore_case
if self.equals is not None:
if self.ignore_case is not None:
if not self.ignore_case:
return value == self.equals
else:
return value.casefold() == self.equals.casefold()
else:
return value == self.equals
else:
return True
def _fail(self, value):
return self.fail % (value, self.equals)
|
class StringEquals(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 7 | 0 | 7 | 1 | 3 | 0.06 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 7 | 19 | 2 | 16 | 5 | 13 | 1 | 13 | 5 | 10 | 4 | 2 | 3 | 5 |
653 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.StringMatches
|
class StringMatches(Constraint):
keywords = {"matches": str}
fail = "%s is not a regex match."
_regex_flags = {"ignore_case": re.I, "multiline": re.M, "dotall": re.S}
def __init__(self, value_type, kwargs):
self._flags = 0
for k, v in util.get_iter(self._regex_flags):
self._flags |= v if kwargs.pop(k, False) else 0
super(StringMatches, self).__init__(value_type, kwargs)
def _is_valid(self, value):
if self.matches is not None:
regex = re.compile(self.matches, self._flags)
return regex.match(value)
else:
return True
def _fail(self, value):
return self.fail % (value)
|
class StringMatches(Constraint):
def __init__(self, value_type, kwargs):
pass
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 4 | 0 | 5 | 0 | 4 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 8 | 22 | 5 | 17 | 10 | 13 | 0 | 16 | 10 | 12 | 3 | 2 | 1 | 6 |
654 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.StringStartsWith
|
class StringStartsWith(Constraint):
keywords = {"starts_with": str, "ignore_case": bool}
fail = "%s does not start with %s"
def _is_valid(self, value):
# Check if the function has only been called due to ignore_case
if self.starts_with is not None:
if self.ignore_case is not None:
if not self.ignore_case:
return value.startswith(self.starts_with)
else:
length = len(self.starts_with)
if length <= len(value):
return value[:length].casefold() == self.starts_with.casefold()
else:
return False
else:
return value.startswith(self.starts_with)
else:
return True
def _fail(self, value):
return self.fail % (value, self.starts_with)
|
class StringStartsWith(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 9 | 0 | 9 | 1 | 3 | 0.05 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 7 | 23 | 2 | 20 | 6 | 17 | 1 | 16 | 6 | 13 | 5 | 2 | 4 | 6 |
655 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Any
|
class Any(Validator):
"""Any of several types validator"""
tag = "any"
def __init__(self, *args, **kwargs):
self.validators = [val for val in args if isinstance(val, Validator)]
super(Any, self).__init__(*args, **kwargs)
def _is_valid(self, value):
return True
|
class Any(Validator):
'''Any of several types validator'''
def __init__(self, *args, **kwargs):
pass
def _is_valid(self, value):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.14 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 14 | 11 | 3 | 7 | 5 | 4 | 1 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
656 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Boolean
|
class Boolean(Validator):
"""Boolean validator"""
tag = "bool"
def _is_valid(self, value):
return isinstance(value, bool)
|
class Boolean(Validator):
'''Boolean validator'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.25 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 13 | 7 | 2 | 4 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
657 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Day
|
class Day(Validator):
"""Day validator. Format: YYYY-MM-DD"""
value_type = date
tag = "day"
constraints = [con.Min, con.Max]
def _is_valid(self, value):
return isinstance(value, date)
|
class Day(Validator):
'''Day validator. Format: YYYY-MM-DD'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.17 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 13 | 9 | 2 | 6 | 5 | 4 | 1 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
658 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Enum
|
class Enum(Validator):
"""Enum validator"""
tag = "enum"
def __init__(self, *args, **kwargs):
super(Enum, self).__init__(*args, **kwargs)
self.enums = args
def _is_valid(self, value):
return value in self.enums
def fail(self, value):
return "'%s' not in %s" % (value, self.enums)
|
class Enum(Validator):
'''Enum validator'''
def __init__(self, *args, **kwargs):
pass
def _is_valid(self, value):
pass
def fail(self, value):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.11 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 15 | 14 | 4 | 9 | 6 | 5 | 1 | 9 | 6 | 5 | 1 | 2 | 0 | 3 |
659 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Include
|
class Include(Validator):
"""Include validator"""
tag = "include"
def __init__(self, *args, **kwargs):
self.include_name = args[0]
self.strict = kwargs.pop("strict", None)
super(Include, self).__init__(*args, **kwargs)
def _is_valid(self, value):
return True
def get_name(self):
return self.include_name
|
class Include(Validator):
'''Include validator'''
def __init__(self, *args, **kwargs):
pass
def _is_valid(self, value):
pass
def get_name(self):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.1 | 1 | 1 | 0 | 0 | 3 | 2 | 3 | 15 | 15 | 4 | 10 | 7 | 6 | 1 | 10 | 7 | 6 | 1 | 2 | 0 | 3 |
660 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Integer
|
class Integer(Validator):
"""Integer validator"""
value_type = int
tag = "int"
constraints = [con.Min, con.Max]
def _is_valid(self, value):
return isinstance(value, int) and not isinstance(value, bool)
|
class Integer(Validator):
'''Integer validator'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.17 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 13 | 9 | 2 | 6 | 5 | 4 | 1 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
661 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Ip
|
class Ip(Validator):
"""IP address validator"""
tag = "ip"
constraints = [con.IpVersion]
def _is_valid(self, value):
return self.ip_address(value)
def ip_address(self, value):
try:
ipaddress.ip_interface(util.to_unicode(value))
except ValueError:
return False
return True
|
class Ip(Validator):
'''IP address validator'''
def _is_valid(self, value):
pass
def ip_address(self, value):
pass
| 3 | 1 | 4 | 0 | 4 | 0 | 2 | 0.09 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 14 | 15 | 3 | 11 | 5 | 8 | 1 | 11 | 5 | 8 | 2 | 2 | 1 | 3 |
662 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.List
|
class List(Validator):
"""List validator"""
tag = "list"
constraints = [con.LengthMin, con.LengthMax]
def __init__(self, *args, **kwargs):
super(List, self).__init__(*args, **kwargs)
self.validators = [val for val in args if isinstance(val, Validator)]
def _is_valid(self, value):
return isinstance(value, Sequence) and not util.isstr(value)
|
class List(Validator):
'''List validator'''
def __init__(self, *args, **kwargs):
pass
def _is_valid(self, value):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.13 | 1 | 2 | 0 | 0 | 2 | 1 | 2 | 14 | 12 | 3 | 8 | 6 | 5 | 1 | 8 | 6 | 5 | 1 | 2 | 0 | 2 |
663 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Mac
|
class Mac(Regex):
"""MAC address validator"""
tag = "mac"
def __init__(self, *args, **kwargs):
super(Mac, self).__init__(*args, **kwargs)
self.regexes = [
re.compile(r"[0-9a-fA-F]{2}([-:]?)[0-9a-fA-F]{2}(\1[0-9a-fA-F]{2}){4}$"),
re.compile(r"[0-9a-fA-F]{4}([-:]?)[0-9a-fA-F]{4}(\1[0-9a-fA-F]{4})$"),
]
|
class Mac(Regex):
'''MAC address validator'''
def __init__(self, *args, **kwargs):
pass
| 2 | 1 | 6 | 0 | 6 | 0 | 1 | 0.13 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 16 | 11 | 2 | 8 | 4 | 6 | 1 | 5 | 4 | 3 | 1 | 3 | 0 | 1 |
664 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Map
|
class Map(Validator):
"""Map and dict validator"""
tag = "map"
constraints = [con.LengthMin, con.LengthMax, con.Key]
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
self.validators = [val for val in args if isinstance(val, Validator)]
def _is_valid(self, value):
return isinstance(value, Mapping)
|
class Map(Validator):
'''Map and dict validator'''
def __init__(self, *args, **kwargs):
pass
def _is_valid(self, value):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.13 | 1 | 2 | 0 | 0 | 2 | 1 | 2 | 14 | 12 | 3 | 8 | 6 | 5 | 1 | 8 | 6 | 5 | 1 | 2 | 0 | 2 |
665 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.LengthMax
|
class LengthMax(Constraint):
keywords = {"max": int}
fail = "Length of %s is greater than %s"
def _is_valid(self, value):
return self.max >= len(value)
def _fail(self, value):
return self.fail % (value, self.max)
|
class LengthMax(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 7 | 9 | 2 | 7 | 5 | 4 | 0 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
666 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.Key
|
class Key(Constraint):
keywords = {"key": Validator}
fail = "Key error - %s"
def _is_valid(self, value):
for k in value.keys():
if self.key.validate(k) != []:
return False
return True
def _fail(self, value):
error_list = []
for k in value.keys():
error_list.extend(self.key.validate(k))
return [self.fail % (e) for e in error_list]
|
class Key(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 5 | 0 | 5 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 7 | 15 | 2 | 13 | 8 | 10 | 0 | 13 | 8 | 10 | 3 | 2 | 2 | 5 |
667 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.IpVersion
|
class IpVersion(Constraint):
keywords = {"version": int}
fail = "IP version of %s is not %s"
def _is_valid(self, value):
try:
ip = ipaddress.ip_interface(to_unicode(value))
except ValueError:
return False
return self.version == ip.version
def _fail(self, value):
return self.fail % (value, self.version)
|
class IpVersion(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 7 | 13 | 2 | 11 | 6 | 8 | 0 | 11 | 6 | 8 | 2 | 2 | 1 | 3 |
668 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.Constraint
|
class Constraint(object):
keywords = {} # Keywords and types accepted by this constraint
is_active = False
def __init__(self, value_type, kwargs):
self._parseKwargs(kwargs)
def _parseKwargs(self, kwargs):
for kwarg, kwtype in self.keywords.items():
value = self.get_kwarg(kwargs, kwarg, kwtype)
setattr(self, kwarg, value)
def get_kwarg(self, kwargs, key, kwtype):
try:
value = kwargs[key]
except KeyError:
return None
# Activate this constraint
self.is_active = True
if isinstance(value, kwtype):
# value already correct type, return
return value
try: # Try to convert value
# Is this value one of the datetime types?
if kwtype == datetime.date:
time = datetime.datetime.strptime(value, "%Y-%m-%d")
return datetime.date(time.year, time.month, time.day)
if kwtype == datetime.datetime:
return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
return kwtype(value)
except (TypeError, ValueError):
raise SyntaxError("%s is not a %s" % (key, kwtype))
def is_valid(self, value):
if not self.is_active:
return None
if not self._is_valid(value):
return self._fail(value)
return None
def _fail(self, value):
return "'%s' violates %s." % (value, self.__class__.__name__)
|
class Constraint(object):
def __init__(self, value_type, kwargs):
pass
def _parseKwargs(self, kwargs):
pass
def get_kwarg(self, kwargs, key, kwtype):
pass
def is_valid(self, value):
pass
def _fail(self, value):
pass
| 6 | 0 | 8 | 1 | 6 | 1 | 3 | 0.15 | 1 | 6 | 0 | 11 | 5 | 0 | 5 | 5 | 49 | 12 | 34 | 12 | 28 | 5 | 34 | 12 | 28 | 6 | 1 | 2 | 13 |
669 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Timestamp
|
class Timestamp(Validator):
"""Timestamp validator. Format: YYYY-MM-DD HH:MM:SS"""
value_type = datetime
tag = "timestamp"
constraints = [con.Min, con.Max]
def _is_valid(self, value):
return isinstance(value, datetime)
|
class Timestamp(Validator):
'''Timestamp validator. Format: YYYY-MM-DD HH:MM:SS'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.17 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 13 | 9 | 2 | 6 | 5 | 4 | 1 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
670 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Subset
|
class Subset(Validator):
"""Subset of several types validator"""
tag = "subset"
def __init__(self, *args, **kwargs):
super(Subset, self).__init__(*args, **kwargs)
self._allow_empty_set = bool(kwargs.pop("allow_empty", False))
self.validators = [val for val in args if isinstance(val, Validator)]
if not self.validators:
raise ValueError("'%s' requires at least one validator!" % self.tag)
def _is_valid(self, value):
return self.can_be_none or value is not None
def fail(self, value):
# Called in case `_is_valid` returns False
return "'%s' may not be an empty set." % self.get_name()
@property
def is_optional(self):
return self._allow_empty_set
@property
def can_be_none(self):
return self._allow_empty_set
|
class Subset(Validator):
'''Subset of several types validator'''
def __init__(self, *args, **kwargs):
pass
def _is_valid(self, value):
pass
def fail(self, value):
pass
@property
def is_optional(self):
pass
@property
def can_be_none(self):
pass
| 8 | 1 | 3 | 0 | 3 | 0 | 1 | 0.11 | 1 | 3 | 0 | 0 | 5 | 2 | 5 | 17 | 26 | 6 | 18 | 11 | 10 | 2 | 16 | 9 | 10 | 2 | 2 | 1 | 6 |
671 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.String
|
class String(Validator):
"""String validator"""
tag = "str"
constraints = [
con.LengthMin,
con.LengthMax,
con.CharacterExclude,
con.StringEquals,
con.StringStartsWith,
con.StringEndsWith,
con.StringMatches,
]
def _is_valid(self, value):
return util.isstr(value)
|
class String(Validator):
'''String validator'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.08 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 13 | 16 | 2 | 13 | 4 | 11 | 1 | 5 | 4 | 3 | 1 | 2 | 0 | 1 |
672 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.SemVer
|
class SemVer(Regex):
"""Semantic Versioning (semver.org) validator"""
tag = "semver"
def __init__(self, *args, **kwargs):
super(SemVer, self).__init__(*args, **kwargs)
self.regexes = [
# https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
re.compile(
r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"
),
]
|
class SemVer(Regex):
'''Semantic Versioning (semver.org) validator'''
def __init__(self, *args, **kwargs):
pass
| 2 | 1 | 8 | 0 | 7 | 1 | 1 | 0.22 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 16 | 13 | 2 | 9 | 4 | 7 | 2 | 5 | 4 | 3 | 1 | 3 | 0 | 1 |
673 |
23andMe/Yamale
|
23andMe_Yamale/yamale/schema/datapath.py
|
yamale.schema.datapath.DataPath
|
class DataPath(object):
def __init__(self, *path):
self._path = path
def __add__(self, other):
dp = DataPath()
dp._path = self._path + other._path
return dp
def __str__(self):
return ".".join(map(str, (self._path)))
def __repr__(self):
return "DataPath({})".format(repr(self._path))
|
class DataPath(object):
def __init__(self, *path):
pass
def __add__(self, other):
pass
def __str__(self):
pass
def __repr__(self):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 4 | 1 | 4 | 4 | 14 | 3 | 11 | 7 | 6 | 0 | 11 | 7 | 6 | 1 | 1 | 0 | 4 |
674 |
23andMe/Yamale
|
23andMe_Yamale/yamale/schema/schema.py
|
yamale.schema.schema.FatalValidationError
|
class FatalValidationError(Exception):
def __init__(self, error):
super().__init__()
self.error = error
|
class FatalValidationError(Exception):
def __init__(self, error):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 11 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 3 | 0 | 1 |
675 |
23andMe/Yamale
|
23andMe_Yamale/yamale/schema/schema.py
|
yamale.schema.schema.Schema
|
class Schema(object):
"""
Makes a Schema object from a schema dict.
Still acts like a dict.
"""
def __init__(self, schema_dict, name="", validators=None, includes=None):
self.validators = validators or val.DefaultValidators
self.dict = schema_dict
self.name = name
self._schema = self._process_schema(DataPath(), schema_dict, self.validators)
# if this schema is included it shares the includes with the top level
# schema
self.includes = {} if includes is None else includes
def add_include(self, type_dict):
for include_name, custom_type in type_dict.items():
t = Schema(custom_type, name=include_name, validators=self.validators, includes=self.includes)
self.includes[include_name] = t
def _process_schema(self, path, schema_data, validators):
"""
Go through a schema and construct validators.
"""
if util.is_map(schema_data) or util.is_list(schema_data):
for key, data in util.get_iter(schema_data):
schema_data[key] = self._process_schema(path + DataPath(key), data, validators)
else:
schema_data = self._parse_schema_item(path, schema_data, validators)
return schema_data
def _parse_schema_item(self, path, expression, validators):
try:
return syntax.parse(expression, validators)
except SyntaxError as e:
# Tack on some more context and rethrow.
error = str(e) + " at node '%s'" % str(path)
raise SyntaxError(error)
def validate(self, data, data_name, strict):
path = DataPath()
try:
errors = self._validate(self._schema, data, path, strict)
except FatalValidationError as e:
errors = [e.error]
return ValidationResult(data_name, self.name, errors)
def _validate_item(self, validator, data, path, strict, key):
"""
Fetch item from data at the position key and validate with validator.
Returns an array of errors.
"""
errors = []
path = path + DataPath(key)
try: # Pull value out of data. Data can be a map or a list/sequence
data_item = data[key]
except (KeyError, IndexError): # Oops, that field didn't exist.
# Optional? Who cares.
if isinstance(validator, val.Validator) and validator.is_optional:
return errors
# SHUT DOWN EVERYTHING
errors.append("%s: Required field missing" % path)
return errors
return self._validate(validator, data_item, path, strict)
def _validate(self, validator, data, path, strict):
"""
Validate data with validator.
Special handling of non-primitive validators.
Returns an array of errors.
"""
if util.is_list(validator) or util.is_map(validator):
return self._validate_static_map_list(validator, data, path, strict)
errors = []
# Optional field with optional value? Who cares.
if data is None and validator.is_optional and validator.can_be_none:
return errors
errors += self._validate_primitive(validator, data, path)
if errors:
return errors
if isinstance(validator, val.Include):
errors += self._validate_include(validator, data, path, strict)
elif isinstance(validator, (val.Map, val.List)):
errors += self._validate_map_list(validator, data, path, strict)
elif isinstance(validator, val.Any):
errors += self._validate_any(validator, data, path, strict)
elif isinstance(validator, val.Subset):
errors += self._validate_subset(validator, data, path, strict)
return errors
def _validate_static_map_list(self, validator, data, path, strict):
if util.is_map(validator) and not util.is_map(data):
return ["%s : '%s' is not a map" % (path, data)]
if util.is_list(validator) and not util.is_list(data):
return ["%s : '%s' is not a list" % (path, data)]
errors = []
if strict:
data_keys = set(util.get_keys(data))
validator_keys = set(util.get_keys(validator))
for key in data_keys - validator_keys:
error_path = path + DataPath(key)
errors += ["%s: Unexpected element" % error_path]
for key, sub_validator in util.get_iter(validator):
errors += self._validate_item(sub_validator, data, path, strict, key)
return errors
def _validate_map_list(self, validator, data, path, strict):
errors = []
if not validator.validators:
return errors # No validators, user just wanted a map.
for key in util.get_keys(data):
sub_errors = []
for v in validator.validators:
err = self._validate_item(v, data, path, strict, key)
if err:
sub_errors.append(err)
if len(sub_errors) == len(validator.validators):
# All validators failed, add to errors
for err in sub_errors:
errors += err
return errors
def _validate_include(self, validator, data, path, strict):
include_schema = self.includes.get(validator.include_name)
if not include_schema:
raise FatalValidationError("Include '%s' has not been defined." % validator.include_name)
strict = strict if validator.strict is None else validator.strict
return include_schema._validate(include_schema._schema, data, path, strict)
def _validate_any(self, validator, data, path, strict):
if not validator.validators:
return []
errors = []
sub_errors = []
for v in validator.validators:
err = self._validate(v, data, path, strict)
if err:
sub_errors.append(err)
if len(sub_errors) == len(validator.validators):
# All validators failed, add to errors
for err in sub_errors:
errors += err
return errors
def _validate_subset(self, validator, data, path, strict):
def _internal_validate(internal_data):
sub_errors = []
for v in validator.validators:
err = self._validate(v, internal_data, path, strict)
if not err:
break
sub_errors += err
else:
return sub_errors
return []
if not validator.validators:
return []
errors = []
if util.is_map(data):
for k, v in data.items():
errors += _internal_validate({k: v})
elif util.is_list(data):
for k in data:
errors += _internal_validate(k)
else:
errors += _internal_validate(data)
return errors
def _validate_primitive(self, validator, data, path):
errors = validator.validate(data)
for i, error in enumerate(errors):
errors[i] = ("%s: " % path) + error
return errors
|
class Schema(object):
'''
Makes a Schema object from a schema dict.
Still acts like a dict.
'''
def __init__(self, schema_dict, name="", validators=None, includes=None):
pass
def add_include(self, type_dict):
pass
def _process_schema(self, path, schema_data, validators):
'''
Go through a schema and construct validators.
'''
pass
def _parse_schema_item(self, path, expression, validators):
pass
def validate(self, data, data_name, strict):
pass
def _validate_item(self, validator, data, path, strict, key):
'''
Fetch item from data at the position key and validate with validator.
Returns an array of errors.
'''
pass
def _validate_item(self, validator, data, path, strict, key):
'''
Validate data with validator.
Special handling of non-primitive validators.
Returns an array of errors.
'''
pass
def _validate_static_map_list(self, validator, data, path, strict):
pass
def _validate_map_list(self, validator, data, path, strict):
pass
def _validate_include(self, validator, data, path, strict):
pass
def _validate_any(self, validator, data, path, strict):
pass
def _validate_subset(self, validator, data, path, strict):
pass
def _internal_validate(internal_data):
pass
def _validate_primitive(self, validator, data, path):
pass
| 15 | 4 | 14 | 2 | 10 | 2 | 4 | 0.2 | 1 | 9 | 3 | 0 | 13 | 5 | 13 | 13 | 200 | 40 | 136 | 54 | 121 | 27 | 130 | 52 | 115 | 8 | 1 | 3 | 55 |
676 |
23andMe/Yamale
|
23andMe_Yamale/yamale/schema/validationresults.py
|
yamale.schema.validationresults.Result
|
class Result(object):
def __init__(self, errors):
self.errors = errors
def __str__(self):
return "\n".join(self.errors)
def isValid(self):
return len(self.errors) == 0
|
class Result(object):
def __init__(self, errors):
pass
def __str__(self):
pass
def isValid(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 3 | 1 | 3 | 3 | 9 | 2 | 7 | 5 | 3 | 0 | 7 | 5 | 3 | 1 | 1 | 0 | 3 |
677 |
23andMe/Yamale
|
23andMe_Yamale/yamale/yamale_testcase.py
|
yamale.yamale_testcase.YamaleTestCase
|
class YamaleTestCase(TestCase):
"""TestCase for easily validating YAML in your own tests.
`schema`: String of path to the schema file to use. One schema file per test case.
`yaml`: String or list of yaml files to validate. Accepts globs.
`base_dir`: String path to prepend to all other paths. This is optional.
"""
schema = None
yaml = None
base_dir = None
def validate(self, validators=None):
schema = self.schema
yaml = self.yaml
base_dir = self.base_dir
if schema is None:
return
if not isinstance(yaml, list):
yaml = [yaml]
if base_dir is not None:
schema = os.path.join(base_dir, schema)
yaml = {os.path.join(base_dir, y) for y in yaml}
# Run yaml through glob and flatten list
yaml = set(itertools.chain(*map(glob.glob, yaml)))
# Remove schema from set of data files
yaml = yaml - {schema}
yamale_schema = yamale.make_schema(schema, validators=validators)
yamale_data = itertools.chain(*map(yamale.make_data, yaml))
for result in yamale.validate(yamale_schema, yamale_data):
if not result.isValid():
raise ValueError(result)
return True
|
class YamaleTestCase(TestCase):
'''TestCase for easily validating YAML in your own tests.
`schema`: String of path to the schema file to use. One schema file per test case.
`yaml`: String or list of yaml files to validate. Accepts globs.
`base_dir`: String path to prepend to all other paths. This is optional.
'''
def validate(self, validators=None):
pass
| 2 | 1 | 28 | 7 | 19 | 2 | 6 | 0.3 | 1 | 5 | 0 | 0 | 1 | 0 | 1 | 73 | 39 | 9 | 23 | 11 | 21 | 7 | 23 | 11 | 21 | 6 | 2 | 2 | 6 |
678 |
23andMe/Yamale
|
23andMe_Yamale/yamale/schema/validationresults.py
|
yamale.schema.validationresults.ValidationResult
|
class ValidationResult(Result):
def __init__(self, data, schema, errors):
super(ValidationResult, self).__init__(errors)
self.data = data
self.schema = schema
def __str__(self):
if self.isValid():
error_str = "'%s' is Valid" % self.data
else:
head_line_bits = ["Error validating data"]
if self.data:
head_line_bits.append("'{}'".format(self.data))
if self.schema:
head_line_bits.append("with schema '{}'".format(self.schema))
head_line = " ".join(head_line_bits)
head_line += "\n\t"
error_str = head_line + "\n\t".join(self.errors)
return error_str
|
class ValidationResult(Result):
def __init__(self, data, schema, errors):
pass
def __str__(self):
pass
| 3 | 0 | 9 | 0 | 9 | 0 | 3 | 0 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 5 | 19 | 1 | 18 | 8 | 15 | 0 | 17 | 8 | 14 | 4 | 2 | 2 | 5 |
679 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.TestAllYaml
|
class TestAllYaml(YamaleTestCase):
base_dir = data_folder
schema = "meta_test_fixtures/schema.yaml"
yaml = "meta_test_fixtures/data1.yaml"
def runTest(self):
self.assertTrue(self.validate())
|
class TestAllYaml(YamaleTestCase):
def runTest(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 6 | 5 | 4 | 0 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
680 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.TestBadRequiredYaml
|
class TestBadRequiredYaml(YamaleTestCase):
base_dir = data_folder
schema = "meta_test_fixtures/schema_required_bad.yaml"
yaml = "meta_test_fixtures/data_required_bad.yaml"
def runTest(self):
self.assertRaises(ValueError, self.validate)
|
class TestBadRequiredYaml(YamaleTestCase):
def runTest(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 6 | 5 | 4 | 0 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
681 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.TestBadYaml
|
class TestBadYaml(YamaleTestCase):
base_dir = data_folder
schema = "meta_test_fixtures/schema_bad.yaml"
yaml = "meta_test_fixtures/data*.yaml"
def runTest(self):
self.assertRaises(ValueError, self.validate)
|
class TestBadYaml(YamaleTestCase):
def runTest(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 6 | 5 | 4 | 0 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
682 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.TestCustomValidator
|
class TestCustomValidator(YamaleTestCase):
base_dir = data_folder
schema = "meta_test_fixtures/schema_custom.yaml"
yaml = "meta_test_fixtures/data_custom.yaml"
def runTest(self):
validators = DefaultValidators.copy()
validators["card"] = Card
self.assertTrue(self.validate(validators))
|
class TestCustomValidator(YamaleTestCase):
def runTest(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 9 | 1 | 8 | 6 | 6 | 0 | 8 | 6 | 6 | 1 | 1 | 0 | 1 |
683 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.TestCustomValidatorWithIncludes
|
class TestCustomValidatorWithIncludes(YamaleTestCase):
base_dir = data_folder
schema = "meta_test_fixtures/schema_custom_with_include.yaml"
yaml = "meta_test_fixtures/data_custom_with_include.yaml"
def runTest(self):
validators = DefaultValidators.copy()
validators["card"] = Card
self.assertTrue(self.validate(validators))
|
class TestCustomValidatorWithIncludes(YamaleTestCase):
def runTest(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 9 | 1 | 8 | 6 | 6 | 0 | 8 | 6 | 6 | 1 | 1 | 0 | 1 |
684 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.TestGoodRequiredYaml
|
class TestGoodRequiredYaml(YamaleTestCase):
base_dir = data_folder
schema = "meta_test_fixtures/schema_required_good.yaml"
yaml = "meta_test_fixtures/data_required_good.yaml"
def runTest(self):
self.assertTrue(self.validate())
|
class TestGoodRequiredYaml(YamaleTestCase):
def runTest(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 6 | 5 | 4 | 0 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
685 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.TestMapYaml
|
class TestMapYaml(YamaleTestCase):
base_dir = data_folder
schema = "meta_test_fixtures/schema.yaml"
yaml = [
"meta_test_fixtures/data1.yaml",
"meta_test_fixtures/some_data.yaml",
# Make sure schema doesn't validate itself
"meta_test_fixtures/schema.yaml",
]
def runTest(self):
self.assertTrue(self.validate())
|
class TestMapYaml(YamaleTestCase):
def runTest(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0.1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 12 | 1 | 10 | 5 | 8 | 1 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
686 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/validators.py
|
yamale.validators.validators.Regex
|
class Regex(Validator):
"""Regular expression validator"""
tag = "regex"
_regex_flags = {"ignore_case": re.I, "multiline": re.M, "dotall": re.S}
def __init__(self, *args, **kwargs):
self.regex_name = kwargs.pop("name", None)
flags = 0
for k, v in util.get_iter(self._regex_flags):
flags |= v if kwargs.pop(k, False) else 0
self.regexes = [re.compile(arg, flags) for arg in args if util.isstr(arg)]
super(Regex, self).__init__(*args, **kwargs)
def _is_valid(self, value):
return util.isstr(value) and any(r.match(value) for r in self.regexes)
def get_name(self):
return self.regex_name or self.tag + " match"
|
class Regex(Validator):
'''Regular expression validator'''
def __init__(self, *args, **kwargs):
pass
def _is_valid(self, value):
pass
def get_name(self):
pass
| 4 | 1 | 4 | 1 | 4 | 0 | 2 | 0.07 | 1 | 1 | 0 | 2 | 3 | 2 | 3 | 15 | 21 | 6 | 14 | 10 | 10 | 1 | 14 | 10 | 10 | 3 | 2 | 1 | 5 |
687 |
23andMe/Yamale
|
23andMe_Yamale/yamale/tests/test_meta_test.py
|
yamale.tests.test_meta_test.Card
|
class Card(Validator):
"""Custom validator for testing purpose"""
tag = "card"
card_regex = re.compile(r"^(10|[2-9JQKA])[SHDC]$")
def _is_valid(self, value):
return re.match(self.card_regex, value)
|
class Card(Validator):
'''Custom validator for testing purpose'''
def _is_valid(self, value):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 13 | 8 | 2 | 5 | 4 | 3 | 1 | 5 | 4 | 3 | 1 | 2 | 0 | 1 |
688 |
23andMe/Yamale
|
23andMe_Yamale/yamale/validators/constraints.py
|
yamale.validators.constraints.CharacterExclude
|
class CharacterExclude(Constraint):
keywords = {"exclude": str, "ignore_case": bool}
fail = "'%s' contains excluded character '%s'"
def _is_valid(self, value):
# Check if the function has only been called due to ignore_case
if self.exclude is not None:
for char in self.exclude:
if self.ignore_case is not None:
if not self.ignore_case:
if char in value:
self._failed_char = char
return False
else:
if char.casefold() in value.casefold():
self._failed_char = char
return False
else:
if char in value:
self._failed_char = char
return False
return True
else:
return True
def _fail(self, value):
return self.fail % (value, self._failed_char)
|
class CharacterExclude(Constraint):
def _is_valid(self, value):
pass
def _fail(self, value):
pass
| 3 | 0 | 11 | 0 | 11 | 1 | 5 | 0.04 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 7 | 27 | 2 | 24 | 7 | 21 | 1 | 21 | 7 | 18 | 8 | 2 | 5 | 9 |
689 |
23andMe/Yamale
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/23andMe_Yamale/yamale/syntax/tests/test_parser.py
|
yamale.syntax.tests.test_parser.test_custom_type.my_validator
|
class my_validator(Validator):
pass
|
class my_validator(Validator):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
690 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/tests/test_functional.py
|
seqseek.tests.test_functional.TestDataDirectory
|
class TestDataDirectory(TestCase):
TEST_DATA_DIR = os.path.join('seqseek', 'tests', 'test_chromosomes')
def setUp(self):
os.environ[DATA_DIR_VARIABLE] = TestChromosome.TEST_DATA_DIR
def test_get_data_directory(self):
data_dir = get_data_directory()
self.assertEqual(TestChromosome.TEST_DATA_DIR, data_dir)
def test_make_data_directory(self):
new_dir = os.path.join(TestChromosome.TEST_DATA_DIR, "test")
self.assertFalse(os.path.isdir(new_dir))
os.environ[DATA_DIR_VARIABLE] = new_dir
get_data_directory()
self.assertTrue(os.path.isdir(new_dir))
os.rmdir(new_dir)
|
class TestDataDirectory(TestCase):
def setUp(self):
pass
def test_get_data_directory(self):
pass
def test_make_data_directory(self):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 75 | 18 | 4 | 14 | 7 | 10 | 0 | 14 | 7 | 10 | 1 | 2 | 0 | 3 |
691 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/chromosome.py
|
seqseek.chromosome.Chromosome
|
class Chromosome(object):
ASSEMBLY_CHROMOSOMES = {
BUILD37: BUILD37_ACCESSIONS,
BUILD38: BUILD38_ACCESSIONS
}
def __init__(self, chromosome_name, assembly=BUILD37, loop=False, RCRS_N_remove=True):
"""
Usage:
Chromosome('1').sequence(0, 100)
returns the first 100 nucleotides of chromosome 1
The default assembly is Homo_sapiens.GRCh37
You may also use Build 38:
from seqseek import BUILD38
Chromosome('1', BUILD38).sequence(0, 100)
"""
self.name = str(chromosome_name)
self.assembly = assembly
self.loop = loop
self.RCRS_N_remove = RCRS_N_remove
self.validate_assembly()
self.validate_name()
self.validate_loop()
if self.name in ACCESSION_LENGTHS:
# allow loading by accession
self.accession = self.name
else:
# allow loading by name
self.accession = self.ASSEMBLY_CHROMOSOMES[assembly][self.name]
self.length = ACCESSION_LENGTHS[self.accession]
def validate_assembly(self):
if self.assembly not in (BUILD37, BUILD38):
raise ValueError(
'Sorry, the only supported assemblies are {} and {}'.format(
BUILD37, BUILD38))
def validate_name(self):
if self.name not in ACCESSION_LENGTHS:
if self.name not in self.ASSEMBLY_CHROMOSOMES[self.assembly]:
raise ValueError(
"{name} is not a valid chromosome name or accession".format(
name=self.name))
def validate_loop(self):
if self.loop and self.name not in MITOCHONDRIA_NAMES:
raise ValueError('Loop may only be specified for the mitochondria.')
def validate_coordinates(self, start, end):
if end < 0:
raise ValueError('end must be a positive number')
elif (start < 0 and not self.loop) or end < 0:
raise ValueError("Start and end must be positive integers for this chromosome")
if end < start:
raise ValueError("Start position cannot be greater than end position")
if start > self.length or (end > self.length and not self.loop):
raise ValueError('Coordinates out of bounds. Chr {} has {} bases.'.format(
self.name, self.length))
if self.loop and end - start > self.length:
raise TooManyLoops()
@classmethod
def sorted_chromosome_length_tuples(cls, assembly):
# TODO: simplify
name_to_accession = cls.ASSEMBLY_CHROMOSOMES[assembly]
chromosome_length_tuples = []
for name, accession in name_to_accession.items():
if accession in ACCESSION_LENGTHS:
chromosome_length_tuples.append((name, ACCESSION_LENGTHS[accession]))
return sorted(chromosome_length_tuples,
key=lambda pair:
sorted_nicely(
ACCESSION_LENGTHS.keys()).index(name_to_accession[pair[0]]))
def filename(self):
return '{}.fa'.format(self.accession)
def path(self):
data_dir = get_data_directory()
return os.path.join(data_dir, self.filename())
def exists(self):
return os.path.exists(self.path())
def header(self):
with open(self.path()) as f:
return f.readline()
def read(self, start, length):
with open(self.path()) as fasta:
header = fasta.readline()
fasta.seek(start + len(header))
return fasta.read(length)
def sequence(self, start, end):
self.validate_coordinates(start, end)
if self.loop and end > self.length:
reads = [(start, self.length - start), (0, end - self.length)]
elif self.loop and start < 0:
reads = [(self.length + start, abs(start)), (0, end)]
else:
reads = [(start, end - start)]
if not self.exists():
build = '37' if self.assembly == BUILD37 else '38'
raise MissingDataError(
'{} does not exist. Please download on the command line with: '
'download_build_{}'.format(self.path(), build))
sequence = ''.join([self.read(*read) for read in reads])
# The rCRS mito contig contains an 'N' base at position 3107 to preserve legacy
# nucleotide numbering. We remove it because it is not part of the observed
# sequence. See http://www.mitomap.org/MITOMAP/HumanMitoSeq
if self.accession == RCRS_ACCESSION and self.RCRS_N_remove is True:
sequence = sequence.replace('N', '')
return sequence
|
class Chromosome(object):
def __init__(self, chromosome_name, assembly=BUILD37, loop=False, RCRS_N_remove=True):
'''
Usage:
Chromosome('1').sequence(0, 100)
returns the first 100 nucleotides of chromosome 1
The default assembly is Homo_sapiens.GRCh37
You may also use Build 38:
from seqseek import BUILD38
Chromosome('1', BUILD38).sequence(0, 100)
'''
pass
def validate_assembly(self):
pass
def validate_name(self):
pass
def validate_loop(self):
pass
def validate_coordinates(self, start, end):
pass
@classmethod
def sorted_chromosome_length_tuples(cls, assembly):
pass
def filename(self):
pass
def path(self):
pass
def exists(self):
pass
def header(self):
pass
def read(self, start, length):
pass
def sequence(self, start, end):
pass
| 14 | 1 | 9 | 1 | 7 | 1 | 2 | 0.17 | 1 | 4 | 2 | 0 | 11 | 6 | 12 | 12 | 127 | 25 | 87 | 31 | 73 | 15 | 69 | 28 | 56 | 6 | 1 | 2 | 29 |
692 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/downloader.py
|
seqseek.downloader.Downloader
|
class Downloader(object):
SUPPORTED_ASSEMBLIES = (BUILD37, BUILD38)
def __init__(self, assembly, data_dir=None, verbose=True):
self.assembly = assembly
self.data_dir = data_dir or get_data_directory()
self.verbose = verbose
self.validate_assembly()
self.log('Data directory: {}'.format(self.data_dir))
self.log('Host: {}'.format(URI))
def log(self, msg, force=False):
if self.verbose or force:
print(msg) # TODO: add a log handler
def validate_assembly(self):
if self.assembly not in self.SUPPORTED_ASSEMBLIES:
raise ValueError('%s is not one of the supported assemblies %s'.format(
self.assembly, self.SUPPORTED_ASSEMBLIES))
def get_missing_chromosomes(self):
missing_chromosomes = []
for name, length in Chromosome.sorted_chromosome_length_tuples(self.assembly):
chromosome = Chromosome(name, self.assembly)
filepath = chromosome.path()
if not chromosome.exists():
missing_chromosomes.append(name)
else:
expected_size = length + len(chromosome.header()) + 1
size = os.path.getsize(filepath)
if size != expected_size:
self.log('Removing mismatched chromosome %s' % name)
missing_chromosomes.append(name)
os.remove(filepath)
return missing_chromosomes
def download_chromosomes(self):
to_download = self.get_missing_chromosomes()
self.log("Downloading {} chromosomes".format(len(to_download)))
for name in to_download:
self.download_chromosome(name)
run_build_test_suite(self.assembly)
def download_chromosome(self, name):
chromosome = Chromosome(name, self.assembly)
path = chromosome.path()
directory = os.path.dirname(chromosome.path())
if not os.path.isdir(directory):
os.makedirs(directory)
self.log('Created directory {}'.format(directory), True)
uri = URI + chromosome.filename()
self.log(
'Downloading from {} to {}'.format(uri, path), True)
r = requests.get(uri, stream=True)
# TODO can we do this in fewer than 3 passes?
with open(path, 'wb') as fd:
for chunk in r.iter_content(chunk_size=1024):
fd.write(chunk)
with open(path, 'r') as f:
header = f.readline()
content = f.read().replace('\n', '')
with open(path, 'w') as f:
f.write(header)
f.write(content)
f.write('\n')
self.log('...Complete', True)
|
class Downloader(object):
def __init__(self, assembly, data_dir=None, verbose=True):
pass
def log(self, msg, force=False):
pass
def validate_assembly(self):
pass
def get_missing_chromosomes(self):
pass
def download_chromosomes(self):
pass
def download_chromosomes(self):
pass
| 7 | 0 | 12 | 3 | 10 | 0 | 2 | 0.03 | 1 | 2 | 1 | 0 | 6 | 3 | 6 | 6 | 82 | 22 | 59 | 29 | 52 | 2 | 56 | 27 | 49 | 4 | 1 | 3 | 14 |
693 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/exceptions.py
|
seqseek.exceptions.MissingDataError
|
class MissingDataError(Exception):
pass
|
class MissingDataError(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
694 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/exceptions.py
|
seqseek.exceptions.TooManyLoops
|
class TooManyLoops(Exception):
pass
|
class TooManyLoops(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
695 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/tests/build_specific_tests/build_37_tests.py
|
seqseek.tests.build_specific_tests.build_37_tests.TestBuild37
|
class TestBuild37(TestCase):
def test_file_names(self):
for accession in BUILD37_ACCESSIONS.values():
fasta = os.path.join(get_data_directory(), str(accession) + ".fa")
self.assertTrue(os.path.isfile(fasta), fasta)
# all test sequences were extracted from https://genome.ucsc.edu/ using the
# chromosome browser tool
def test_chr_start_sequences(self):
exclude = ('MT', '17' , 'chr6_cox_hap2', 'chr6_apd_hap1', 'chr6_ssto_hap7',
'chr6_mcf_hap5', 'chr6_qbl_hap6', 'chr6_mann_hap4', 'chr6_dbb_hap3',
'chr17_ctg5_hap1', 'chr4_ctg9_hap1', 'RSRS')
test_str = "N" * 20
for name in BUILD37_ACCESSIONS.keys():
# these chromosomes do not have telomeres
if name in exclude:
continue
seq = Chromosome(name).sequence(0, 20)
self.assertEqual(seq, test_str, name)
def test_chr1_sequence(self):
expected_seq = "AATCTAAAAAACTGTCAGAT"
seq = Chromosome(1).sequence(243400000, 243400020)
self.assertEqual(expected_seq.upper(), seq)
def test_chr2_sequence(self):
expected_seq = "tgtccacgcgcggatgtcgt"
seq = Chromosome(2).sequence(237513040, 237513060)
self.assertEqual(expected_seq.upper(), seq)
def test_chr3_sequence(self):
expected_seq = "ctctttcgcccaggctggag"
seq = Chromosome(3).sequence(190352536, 190352556)
self.assertEqual(expected_seq.upper(), seq)
def test_chr4_sequence(self):
expected_seq = "ttggagccaaggtctcactc"
seq = Chromosome(4).sequence(184622015, 184622035)
self.assertEqual(expected_seq.upper(), seq)
def test_chr5_sequence(self):
expected_seq = "CTTTACTCCACTCATATTCT"
seq = Chromosome(5).sequence(158879589, 158879609)
self.assertEqual(expected_seq, seq)
def test_chr6_sequence(self):
expected_seq = "AGGTGGTAGCCCAGTGGTGC"
seq = Chromosome(6).sequence(158882594, 158882614)
self.assertEqual(expected_seq, seq)
def test_chr7_sequence(self):
expected_seq = "CTTGCTCTCATCCTCCGGGT"
seq = Chromosome(7).sequence(158896447, 158896467)
self.assertEqual(expected_seq, seq)
def test_chr8_sequence(self):
expected_seq = "CTGTCTCCACTGCAGGGCTC"
seq = Chromosome(8).sequence(139508913, 139508933)
self.assertEqual(expected_seq, seq)
def test_chr9_sequence(self):
expected_seq = "GAGGAGAACATTTGCCTGCA"
seq = Chromosome(9).sequence(140705912, 140705932)
self.assertEqual(expected_seq, seq)
def test_chr10_sequence(self):
expected_seq = "TCTGCAGGGGGCGGAGGAAA"
seq = Chromosome(10).sequence(121086020, 121086040)
self.assertEqual(expected_seq, seq)
def test_chr11_sequence(self):
expected_seq = "CTGAGGGTGGCGCTCTCCCC"
seq = Chromosome(11).sequence(132812820, 132812840)
self.assertEqual(expected_seq, seq)
def test_chr12_sequence(self):
expected_seq = "CCTCATGCCCAGTTCTACGT"
seq = Chromosome(12).sequence(132824462, 132824482)
self.assertEqual(expected_seq, seq)
def test_chr13_sequence(self):
expected_seq = "GAAAAGAATTCAAAGAACAC"
seq = Chromosome(13).sequence(113086756, 113086776)
self.assertEqual(expected_seq, seq)
def test_chr14_sequence(self):
expected_seq = "GCAACGGGGTGGTCATCCAC"
seq = Chromosome(14).sequence(105204712, 105204732)
self.assertEqual(expected_seq, seq)
def test_chr15_sequence(self):
expected_seq = "ttcaatcactgatacccttt"
seq = Chromosome(15).sequence(99921491, 99921511)
self.assertEqual(expected_seq.upper(), seq)
def test_chr16_sequence(self):
expected_seq = "CTTTCAGCACAGGGCTGTGA"
seq = Chromosome(16).sequence(89862313, 89862333)
self.assertEqual(expected_seq, seq)
def test_chr17_sequence(self):
expected_seq = "TGGAGCTGGAGCCACAGGTC"
seq = Chromosome(17).sequence(80014178, 80014198)
self.assertEqual(expected_seq, seq)
def test_chr18_sequence(self):
expected_seq = "CGAACACTTCGTTGTCCTCT"
seq = Chromosome(18).sequence(74778253, 74778273)
self.assertEqual(expected_seq, seq)
def test_chr19_sequence(self):
expected_seq = "GGCTGGTTAAACTCGGGGTC"
seq = Chromosome(19).sequence(55798374, 55798394)
self.assertEqual(expected_seq, seq)
def test_chr20_sequence(self):
expected_seq = "CTGCCCAAGTGCTCCTGGAG"
seq = Chromosome(20).sequence(55803284, 55803304)
self.assertEqual(expected_seq, seq)
def test_chr21_sequence(self):
expected_seq = "GGCTGGTGTGGCACATGATG"
seq = Chromosome(21).sequence(46074515, 46074535)
self.assertEqual(expected_seq, seq)
def test_chr22_sequence(self):
expected_seq = "AGACGCCGCCCCTGTTCATG"
seq = Chromosome(22).sequence(50552076, 50552096)
self.assertEqual(expected_seq, seq)
def test_chrX_sequence(self):
expected_seq = "GCAAGCAGCAGGATGGGGCC"
seq = Chromosome("X").sequence(152811545, 152811565)
self.assertEqual(expected_seq, seq)
def test_chrY_sequence(self):
expected_seq = "CTGAACGTGCTGAGTTACAG"
seq = Chromosome("Y").sequence(25325643, 25325663)
self.assertEqual(expected_seq, seq)
def test_chrMT_sequence(self):
expected_seq = "ATTGTACGGTACCATAAATA"
seq = Chromosome("MT").sequence(16121, 16141)
self.assertEqual(expected_seq, seq)
def test_chr6_cox_hap2(self):
accession = BUILD37_ACCESSIONS['chr6_cox_hap2']
max_length = ACCESSION_LENGTHS[accession]
expected_seq = "GATCCTGAGTGGGTGAGTGG"
seq = Chromosome("chr6_cox_hap2").sequence(3065395, 3065415)
self.assertEqual(expected_seq, seq)
expected_seq = "TATTCTTGCCAATAT"
seq = Chromosome("chr6_cox_hap2").sequence(200, 215).upper()
self.assertEqual(expected_seq, seq)
expected_seq = "TCTGGCCTGGGAGTC"
seq = Chromosome("chr6_cox_hap2").sequence(0, 15).upper()
self.assertEqual(expected_seq, seq)
expected = "tc"
seq = Chromosome('chr6_cox_hap2').sequence(4795369, max_length)
self.assertEqual(expected.upper(), seq)
def test_chr6_apd_hap1(self):
accession = BUILD37_ACCESSIONS['chr6_apd_hap1']
max_length = ACCESSION_LENGTHS[accession]
expected = "GAATTCAGCTCGCCGACGGC"
seq = Chromosome('chr6_apd_hap1').sequence(0, 20)
self.assertEqual(expected, seq)
expected = "ACAATTAGAAATACTAGGAG"
seq = Chromosome('chr6_apd_hap1').sequence(3000, 3020)
self.assertEqual(expected, seq)
expected = "cacT"
seq = Chromosome('chr6_apd_hap1').sequence(max_length - 4, max_length)
self.assertEqual(expected.upper(), seq)
def test_chr6_ssto_hap7(self):
accession = BUILD37_ACCESSIONS['chr6_ssto_hap7']
max_length = ACCESSION_LENGTHS[accession]
expected = "GGCCAGGTTTTGTGAATTCT"
seq = Chromosome('chr6_ssto_hap7').sequence(3000, 3020)
self.assertEqual(expected.upper(), seq)
expected = "ggcc"
seq = Chromosome('chr6_ssto_hap7').sequence(max_length - 4, max_length)
self.assertEqual(expected.upper(), seq)
def test_chr6_mcf_hap5(self):
expected = "ACAATTAGAAATACTAGGAG"
seq = Chromosome('chr6_mcf_hap5').sequence(3000, 3020)
self.assertEqual(expected, seq)
def test_chr6_qbl_hap6(self):
accession = BUILD37_ACCESSIONS['chr6_qbl_hap6']
max_length = ACCESSION_LENGTHS[accession]
expected = "ACAATTAGAAATACTAGGAG"
seq = Chromosome('chr6_qbl_hap6').sequence(3000, 3020)
self.assertEqual(expected, seq)
expected = "ggcc"
seq = Chromosome('chr6_qbl_hap6').sequence(max_length - 4, max_length)
self.assertEqual(expected.upper(), seq)
def test_chr6_mann_hap4(self):
expected = "ACAATTAGAAATACTAGGAG"
seq = Chromosome('chr6_mann_hap4').sequence(3000, 3020)
self.assertEqual(expected, seq)
def test_chr6_dbb_hap3(self):
expected = "ACAATTAGAAATACTAGGAG"
seq = Chromosome('chr6_dbb_hap3').sequence(3000, 3020)
self.assertEqual(expected, seq)
def test_chr17_ctg5_hap1(self):
expected = "TTTTGGCTACAATAATTCTT"
seq = Chromosome('chr17_ctg5_hap1').sequence(3000, 3020)
self.assertEqual(expected, seq)
def test_looped_mito(self):
mito_accession = BUILD37_ACCESSIONS['MT']
mito_length = ACCESSION_LENGTHS[mito_accession]
expected = 'CATCACGATGGATCACAGGT'
seq = Chromosome('MT', loop=True).sequence(mito_length - 10, mito_length + 10)
self.assertEqual(expected, seq)
seq = Chromosome('MT', loop=True).sequence(-10, 10)
self.assertEqual(expected, seq)
def test_mito_N(self):
"""
From mitomap:
*3107del is maintained in this revised sequence with the gap
represented by an 'N'. THIS ALLOWS HISTORICAL NUCLEOTIDE NUMBERING TO
BE MAINTAINED.
We remove this 'N' base since it is only present to preserve numbering and is
not actually part of the observed sequence.
"""
self.assertEqual('', Chromosome('MT').sequence(3106, 3107))
def test_RSRS(self):
expected = 'GGAC'
seq = Chromosome('NC_001807.4').sequence(750, 754)
self.assertEqual(expected, seq)
|
class TestBuild37(TestCase):
def test_file_names(self):
pass
def test_chr_start_sequences(self):
pass
def test_chr1_sequence(self):
pass
def test_chr2_sequence(self):
pass
def test_chr3_sequence(self):
pass
def test_chr4_sequence(self):
pass
def test_chr5_sequence(self):
pass
def test_chr6_sequence(self):
pass
def test_chr7_sequence(self):
pass
def test_chr8_sequence(self):
pass
def test_chr9_sequence(self):
pass
def test_chr10_sequence(self):
pass
def test_chr11_sequence(self):
pass
def test_chr12_sequence(self):
pass
def test_chr13_sequence(self):
pass
def test_chr14_sequence(self):
pass
def test_chr15_sequence(self):
pass
def test_chr16_sequence(self):
pass
def test_chr17_sequence(self):
pass
def test_chr18_sequence(self):
pass
def test_chr19_sequence(self):
pass
def test_chr20_sequence(self):
pass
def test_chr21_sequence(self):
pass
def test_chr22_sequence(self):
pass
def test_chrX_sequence(self):
pass
def test_chrY_sequence(self):
pass
def test_chrMT_sequence(self):
pass
def test_chr6_cox_hap2(self):
pass
def test_chr6_apd_hap1(self):
pass
def test_chr6_ssto_hap7(self):
pass
def test_chr6_mcf_hap5(self):
pass
def test_chr6_qbl_hap6(self):
pass
def test_chr6_mann_hap4(self):
pass
def test_chr6_dbb_hap3(self):
pass
def test_chr17_ctg5_hap1(self):
pass
def test_looped_mito(self):
pass
def test_mito_N(self):
'''
From mitomap:
*3107del is maintained in this revised sequence with the gap
represented by an 'N'. THIS ALLOWS HISTORICAL NUCLEOTIDE NUMBERING TO
BE MAINTAINED.
We remove this 'N' base since it is only present to preserve numbering and is
not actually part of the observed sequence.
'''
pass
def test_RSRS(self):
pass
| 39 | 1 | 6 | 0 | 5 | 0 | 1 | 0.06 | 1 | 2 | 1 | 0 | 38 | 0 | 38 | 110 | 254 | 53 | 190 | 126 | 151 | 11 | 188 | 126 | 149 | 3 | 2 | 2 | 41 |
696 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/tests/build_specific_tests/build_38_tests.py
|
seqseek.tests.build_specific_tests.build_38_tests.TestBuild38
|
class TestBuild38(TestCase):
def test_file_names(self):
for accession in BUILD38_ACCESSIONS.values():
fasta = os.path.join(get_data_directory(), str(accession) + ".fa")
self.assertTrue(os.path.isfile(fasta), fasta)
# all test sequences were extracted from https://genome.ucsc.edu/ using the
# chromosome browser tool
def test_chr_start_sequences(self):
test_str = "N" * 20
for name in BUILD38_ACCESSIONS.keys():
# these chromosomes do not have telomeres
if name in ('MT', 'RSRS', '17'):
continue
seq = Chromosome(name, assembly=BUILD38).sequence(0, 20)
self.assertEqual(seq, test_str)
def test_chr1_sequence(self):
expected_seq = "ACAGGAAAAAGATAGCATTC"
seq = Chromosome(1, assembly=BUILD38).sequence(243415701, 243415721)
self.assertEqual(expected_seq, seq)
def test_chr2_sequence(self):
expected_seq = "GCTGGGCCTGAACTGATATC"
seq = Chromosome(2, assembly=BUILD38).sequence(237518537, 237518557)
self.assertEqual(expected_seq, seq)
def test_chr3_sequence(self):
expected_seq = "GCTGAAGTCATCGATGTGAG"
seq = Chromosome(3, assembly=BUILD38).sequence(175256410, 175256430)
self.assertEqual(expected_seq, seq)
def test_chr4_sequence(self):
expected_seq = "CTGtttctgaccacagcctc"
seq = Chromosome(4, assembly=BUILD38).sequence(184624738, 184624758)
self.assertEqual(expected_seq.upper(), seq)
def test_chr5_sequence(self):
expected_seq = "CTGTCAATTATCACTGGATC"
seq = Chromosome(5, assembly=BUILD38).sequence(159073395, 159073415)
self.assertEqual(expected_seq, seq)
def test_chr6_sequence(self):
expected_seq = "GATGCACGCTGCTGTTTTAT"
seq = Chromosome(6, assembly=BUILD38).sequence(155144605, 155144625)
self.assertEqual(expected_seq, seq)
def test_chr7_sequence(self):
expected_seq = "GAGCTGGTGGGGAGTAACCC"
seq = Chromosome(7, assembly=BUILD38).sequence(154446213, 154446233)
self.assertEqual(expected_seq, seq)
def test_chr8_sequence(self):
expected_seq = "atcgtggcgtgttctgcagg"
seq = Chromosome(8, assembly=BUILD38).sequence(132447200, 132447220)
self.assertEqual(expected_seq.upper(), seq)
def test_chr9_sequence(self):
expected_seq = "GAACCCTCTCATCGTCAAGG"
seq = Chromosome(9, assembly=BUILD38).sequence(132410447, 132410467)
self.assertEqual(expected_seq, seq)
def test_chr10_sequence(self):
expected_seq = "TTCAGGTTCCTTTGCAGCTC"
seq = Chromosome(10, assembly=BUILD38).sequence(122849420, 122849440)
self.assertEqual(expected_seq, seq)
def test_chr11_sequence(self):
expected_seq = "TTTTTAAATGAGTATCCTGG"
seq = Chromosome(11, assembly=BUILD38).sequence(122850195, 122850215)
self.assertEqual(expected_seq, seq)
def test_chr12_sequence(self):
expected_seq = "CATCCCCAGTTTCCCGCGGG"
seq = Chromosome(12, assembly=BUILD38).sequence(122850834, 122850854)
self.assertEqual(expected_seq, seq)
def test_chr13_sequence(self):
expected_seq = "CCCCCCGAAAAGGGCAAAGG"
seq = Chromosome(13, assembly=BUILD38).sequence(113089709, 113089729)
self.assertEqual(expected_seq, seq)
def test_chr14_sequence(self):
expected_seq = "CCCATGTAGTCCAGGTCAGA"
seq = Chromosome(14, assembly=BUILD38).sequence(100353686, 100353706)
self.assertEqual(expected_seq, seq)
def test_chr15_sequence(self):
expected_seq = "attaaaatcatccaatttcc"
seq = Chromosome(15, assembly=BUILD38).sequence(86987986, 86988006)
self.assertEqual(expected_seq.upper(), seq)
def test_chr16_sequence(self):
expected_seq = "TTTCAAGCCACAGTCGAGGA"
seq = Chromosome(16, assembly=BUILD38).sequence(83670789, 83670809)
self.assertEqual(expected_seq, seq)
def test_chr17_sequence(self):
expected_seq = "aaacatcatctctaccaaaa"
seq = Chromosome(17, assembly=BUILD38).sequence(80014178, 80014198)
self.assertEqual(expected_seq.upper(), seq)
def test_chr18_sequence(self):
expected_seq = "TGCAAAGAGAAATCCTTgga"
seq = Chromosome(18, assembly=BUILD38).sequence(67834418, 67834438)
self.assertEqual(expected_seq.upper(), seq)
def test_chr19_sequence(self):
expected_seq = "CTGGGCTGCAGAATCGCTGG"
seq = Chromosome(19, assembly=BUILD38).sequence(45500047, 45500067)
self.assertEqual(expected_seq, seq)
def test_chr20_sequence(self):
expected_seq = "ATGAGATGGACCAAACGCCC"
seq = Chromosome(20, assembly=BUILD38).sequence(59743106, 59743126)
self.assertEqual(expected_seq, seq)
def test_chr21_sequence(self):
expected_seq = "GGCCCCCCCGGACCACCAGG"
seq = Chromosome(21, assembly=BUILD38).sequence(45497642, 45497662)
self.assertEqual(expected_seq, seq)
def test_chr22_sequence(self):
expected_seq = "CTTTTCATTAACTGGATAAA"
seq = Chromosome(22, assembly=BUILD38).sequence(43711474, 43711494)
self.assertEqual(expected_seq, seq)
def test_chrX_sequence(self):
expected_seq = "GGACAACACCtgttaggggc"
seq = Chromosome("X", assembly=BUILD38).sequence(152811545, 152811565)
self.assertEqual(expected_seq.upper(), seq)
def test_chrY_sequence(self):
expected_seq = "CAGACCTTCTGCAGTGCACC"
seq = Chromosome("Y", assembly=BUILD38).sequence(25325643, 25325663)
self.assertEqual(expected_seq, seq)
def test_chrMT_sequence(self):
expected_seq = "ATTGTACGGTACCATAAATA"
seq = Chromosome("MT", assembly=BUILD38).sequence(16121, 16141)
self.assertEqual(expected_seq, seq)
def test_looped_mito(self):
mito_accession = BUILD38_ACCESSIONS['MT']
mito_length = ACCESSION_LENGTHS[mito_accession]
expected = 'CATCACGATGGATCACAGGT'
seq = Chromosome('MT', BUILD38, loop=True).sequence(mito_length - 10, mito_length + 10)
self.assertEqual(expected, seq)
seq = Chromosome('MT', BUILD38, loop=True).sequence(-10, 10)
self.assertEqual(expected, seq)
def test_mito_N(self):
"""
From mitomap:
*3107del is maintained in this revised sequence with the gap
represented by an 'N'. THIS ALLOWS HISTORICAL NUCLEOTIDE NUMBERING TO
BE MAINTAINED.
We remove this 'N' base since it is only present to preserve numbering and is
not actually part of the observed sequence.
"""
self.assertEqual('', Chromosome('MT').sequence(3106, 3107))
def test_RSRS(self):
expected = 'GGAC'
seq = Chromosome('NC_001807.4').sequence(750, 754)
self.assertEqual(expected, seq)
|
class TestBuild38(TestCase):
def test_file_names(self):
pass
def test_chr_start_sequences(self):
pass
def test_chr1_sequence(self):
pass
def test_chr2_sequence(self):
pass
def test_chr3_sequence(self):
pass
def test_chr4_sequence(self):
pass
def test_chr5_sequence(self):
pass
def test_chr6_sequence(self):
pass
def test_chr7_sequence(self):
pass
def test_chr8_sequence(self):
pass
def test_chr9_sequence(self):
pass
def test_chr10_sequence(self):
pass
def test_chr11_sequence(self):
pass
def test_chr12_sequence(self):
pass
def test_chr13_sequence(self):
pass
def test_chr14_sequence(self):
pass
def test_chr15_sequence(self):
pass
def test_chr16_sequence(self):
pass
def test_chr17_sequence(self):
pass
def test_chr18_sequence(self):
pass
def test_chr19_sequence(self):
pass
def test_chr20_sequence(self):
pass
def test_chr21_sequence(self):
pass
def test_chr22_sequence(self):
pass
def test_chrX_sequence(self):
pass
def test_chrY_sequence(self):
pass
def test_chrMT_sequence(self):
pass
def test_looped_mito(self):
pass
def test_mito_N(self):
'''
From mitomap:
*3107del is maintained in this revised sequence with the gap
represented by an 'N'. THIS ALLOWS HISTORICAL NUCLEOTIDE NUMBERING TO
BE MAINTAINED.
We remove this 'N' base since it is only present to preserve numbering and is
not actually part of the observed sequence.
'''
pass
def test_RSRS(self):
pass
| 31 | 1 | 5 | 0 | 4 | 0 | 1 | 0.09 | 1 | 2 | 1 | 0 | 30 | 0 | 30 | 102 | 171 | 34 | 126 | 92 | 95 | 11 | 126 | 92 | 95 | 3 | 2 | 2 | 33 |
697 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/tests/test_functional.py
|
seqseek.tests.test_functional.TestCLI
|
class TestCLI(TestCase):
def test_determine_start_end(self):
expected = (10000, 10100)
observed = determine_start_end('10000', '10100')
self.assertEqual(observed, expected)
observed = determine_start_end('10000', '+100')
self.assertEqual(observed, expected)
observed = determine_start_end('-100', '10100')
self.assertEqual(observed, expected)
def test_determine_start_end_cannot_both_relative(self):
with self.assertRaises(ValueError):
determine_start_end('-100', '+100')
def test_determine_start_end_non_integer(self):
with self.assertRaises(ValueError):
determine_start_end('foo', '10100')
with self.assertRaises(ValueError):
determine_start_end('10000', 'bar')
with self.assertRaises(ValueError):
determine_start_end('-foo', '10100')
with self.assertRaises(ValueError):
determine_start_end('10000', '+bar')
with self.assertRaises(ValueError):
determine_start_end('foo', 'bar')
|
class TestCLI(TestCase):
def test_determine_start_end(self):
pass
def test_determine_start_end_cannot_both_relative(self):
pass
def test_determine_start_end_non_integer(self):
pass
| 4 | 0 | 8 | 1 | 7 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 75 | 29 | 6 | 23 | 6 | 19 | 0 | 23 | 6 | 19 | 1 | 2 | 1 | 3 |
698 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/tests/test_functional.py
|
seqseek.tests.test_functional.TestInvalidQueries
|
class TestInvalidQueries(TestCase):
def test_invalid_chromosome_name(self):
with self.assertRaises(ValueError):
Chromosome(23).sequence(123456, 123457)
def test_missing_chromosome(self):
with self.assertRaises(MissingDataError):
Chromosome('18').sequence(0, 20)
def test_invalid_start_position(self):
with self.assertRaises(ValueError):
Chromosome(1).sequence(-1, 10)
def test_invalid_end_position(self):
with self.assertRaises(ValueError):
Chromosome(1).sequence(123457, 123456)
def test_out_of_range_start_position(self):
with self.assertRaises(ValueError):
Chromosome(1).sequence(249250623, 249250625)
def test_out_of_range_end_position(self):
with self.assertRaises(ValueError):
Chromosome(1).sequence(249250619, 249250622)
|
class TestInvalidQueries(TestCase):
def test_invalid_chromosome_name(self):
pass
def test_missing_chromosome(self):
pass
def test_invalid_start_position(self):
pass
def test_invalid_end_position(self):
pass
def test_out_of_range_start_position(self):
pass
def test_out_of_range_end_position(self):
pass
| 7 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 3 | 2 | 0 | 6 | 0 | 6 | 78 | 25 | 6 | 19 | 7 | 12 | 0 | 19 | 7 | 12 | 1 | 2 | 1 | 6 |
699 |
23andMe/seqseek
|
23andMe_seqseek/seqseek/tests/test_functional.py
|
seqseek.tests.test_functional.TestChromosome
|
class TestChromosome(TestCase):
TEST_DATA_DIR = os.path.join('seqseek', 'tests', 'test_chromosomes')
def setUp(self):
mt_accession = BUILD37_ACCESSIONS['MT']
self._mt_length = ACCESSION_LENGTHS[mt_accession]
os.environ[DATA_DIR_VARIABLE] = TestChromosome.TEST_DATA_DIR
ACCESSION_LENGTHS[mt_accession] = 20
def tearDown(self):
mt_accession = BUILD37_ACCESSIONS['MT']
ACCESSION_LENGTHS[mt_accession] = self._mt_length
def test_invalid_assembly(self):
with self.assertRaises(ValueError):
Chromosome('1', 'build_39')
def test_invalid_name(self):
with self.assertRaises(ValueError):
Chromosome('0', BUILD37)
def test_no_errors(self):
Chromosome('1').path()
Chromosome('1').sorted_chromosome_length_tuples(assembly=BUILD37)
Chromosome('1').filename()
def test_chr1_sequences(self):
expected_seq = 'GGGGCGGGAGGACGGGCCCG'
seq = Chromosome(1).sequence(0, 20)
self.assertEqual(seq, expected_seq)
self.assertEqual(len(seq), 20)
expected_seq = 'GGGAG'
seq = Chromosome(1).sequence(5, 10)
self.assertEqual(seq, expected_seq)
def test_chrMT_sequence(self):
expected_seq = 'GATCACAGGTCTTCACCCT'
seq = Chromosome('MT').sequence(0, 20)
self.assertEqual(seq, expected_seq)
self.assertEqual(len(seq), 19) # the N base was removed
expected_seq = 'CAGGT'
seq = Chromosome('MT').sequence(5, 10)
self.assertEqual(seq, expected_seq)
def test_rCRS_sequence_retain_N(self):
expected_seq = 'GATCACAGGTCTNTCACCCT'
seq = Chromosome('MT', RCRS_N_remove=False).sequence(0, 20)
self.assertEqual(seq, expected_seq)
self.assertTrue('N' in seq) # the N base was *not* removed
def test_mito_loop_end(self):
expected_seq = 'CTTCACCCTGATCACAGGT'
seq = Chromosome('MT', loop=True).sequence(10, 30)
self.assertEqual(seq, expected_seq)
seq = Chromosome('MT', loop=True).sequence(-10, 10)
self.assertEqual(seq, expected_seq)
def test_others_are_not_circular(self):
with self.assertRaises(ValueError):
Chromosome(1, loop=True).sequence(0, 1)
def test_too_many_loops(self):
"""should never return a sequence longer than the length of the contig"""
mt_accession = BUILD37_ACCESSIONS['MT']
mt_length = ACCESSION_LENGTHS[mt_accession]
Chromosome('MT', loop=True).sequence(0, mt_length)
with self.assertRaises(TooManyLoops):
Chromosome('MT', loop=True).sequence(0, mt_length + 1)
Chromosome('MT', loop=True).sequence(-1, mt_length - 1)
with self.assertRaises(TooManyLoops):
Chromosome('MT', loop=True).sequence(-1, mt_length)
def test_load_by_accession(self):
# mostly duped from test_chr1_sequences
expected_seq = 'GGGGCGGGAGGACGGGCCCG'
seq = Chromosome('NC_000001.10').sequence(0, 20)
self.assertEqual(seq, expected_seq)
self.assertEqual(len(seq), 20)
expected_seq = 'GGGAG'
seq = Chromosome('NC_000001.10').sequence(5, 10)
self.assertEqual(seq, expected_seq)
|
class TestChromosome(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_invalid_assembly(self):
pass
def test_invalid_name(self):
pass
def test_no_errors(self):
pass
def test_chr1_sequences(self):
pass
def test_chrMT_sequence(self):
pass
def test_rCRS_sequence_retain_N(self):
pass
def test_mito_loop_end(self):
pass
def test_others_are_not_circular(self):
pass
def test_too_many_loops(self):
'''should never return a sequence longer than the length of the contig'''
pass
def test_load_by_accession(self):
pass
| 13 | 1 | 6 | 0 | 5 | 0 | 1 | 0.06 | 1 | 3 | 2 | 0 | 12 | 1 | 12 | 84 | 85 | 16 | 67 | 29 | 54 | 4 | 67 | 29 | 54 | 1 | 2 | 1 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.