code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
minimum = self.minimum() or 0
maximum = self.maximum() or 100
return random.randint(minimum, maximum) | def random(self) | Returns a random value that fits this column's parameters.
:return: <variant> | 3.703325 | 4.041855 | 0.916244 |
try:
return projex.text.safe_eval(value)
except ValueError:
return 0 | def valueFromString(self, value, extra=None, db=None) | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
extra | <variant> | 10.508165 | 14.689383 | 0.715358 |
tree = ast.parse(codes)
patternFinder.visit(tree) | def findPatternsInFile(codes, patternFinder) | Find patterns of exceptions in a file.
@param codes: code of the file to check
@param patternFinder: a visitor for pattern checking and save results | 6.219279 | 7.652675 | 0.812693 |
finder = PatternFinder()
if os.path.isfile(pathToCheck):
with open(pathToCheck) as f:
findPatternsInFile(f.read(), finder)
else:
for path, dirs, files in os.walk(pathToCheck):
for file in files:
_, extname = os.path.splitext(file)
... | def findAllExceptions(pathToCheck) | Find patterns of exceptions in a file or folder.
@param patternFinder: a visitor for pattern checking and save results
@return: patterns of special functions and classes | 2.465837 | 2.303 | 1.070707 |
super(PatternFinder, self).generic_visit(nodeCall)
# Capture assignment like 'f = getattr(...)'.
if hasattr(nodeCall.func, "func"):
# In this case, the statement should be
# 'f = getattr(...)()'.
nodeCall = nodeCall.func
# Make sure the functi... | def visit_Call(self, nodeCall) | Be invoked when visiting a node of function call.
@param node: currently visiting node | 3.558293 | 3.66618 | 0.970572 |
if not node.file_stream:
# Failed to open the module
return
isFirstLineOfComment = True
isDocString = False
lines = node.stream().readlines()
for linenum, line in enumerate(lines):
if line.strip().startswith(b'"""'):
# ... | def visit_module(self, node) | A interface will be called when visiting a module.
@param node: node of current module | 4.000333 | 4.133211 | 0.967851 |
newq = self.copy()
newq.setOp(Query.Op.After)
newq.setValue(value)
return newq | def after(self, value) | Sets the operator type to Query.Op.After and sets the value to
the amount that this query should be lower than. This is functionally
the same as doing the lessThan operation, but is useful for visual
queries for things like dates.
:param value | <variant>
... | 7.075267 | 5.52901 | 1.279663 |
if not isinstance(other, (Query, QueryCompound)) or other.isNull():
return self.copy()
elif not self:
return other.copy()
else:
return orb.QueryCompound(self, other, op=orb.QueryCompound.Op.And) | def and_(self, other) | Creates a new compound query using the
<orb.QueryCompound.Op.And> type.
:param other <Query> || <orb.QueryCompound>
:return <orb.QueryCompound>
:sa __and__
:usage |>>> from orb import Query as Q
|>>>... | 6.642805 | 3.962938 | 1.676232 |
q = self.copy()
q.addFunction(Query.Function.AsString)
return q | def asString(self) | Returns this query with an AsString function added to it.
:return <Query> | 21.163622 | 7.940227 | 2.665367 |
newq = self.copy()
newq.setOp(Query.Op.Before)
newq.setValue(value)
return newq | def before(self, value) | Sets the operator type to Query.Op.Before and sets the value to
the amount that this query should be lower than. This is functionally
the same as doing the lessThan operation, but is useful for visual
queries for things like dates.
:param value | <variant>
... | 7.147413 | 5.413997 | 1.320173 |
newq = self.copy()
newq.setOp(Query.Op.Between)
newq.setValue((low, high))
return newq | def between(self, low, high) | Sets the operator type to Query.Op.Between and sets the
value to a tuple of the two inputted values.
:param low | <variant>
:param high | <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query ... | 7.682117 | 5.211131 | 1.474175 |
try:
schema = (self.__model or model).schema()
except AttributeError:
return None
else:
return schema.column(self.__column) | def column(self, model=None) | Returns the column instance for this query.
:return <orb.Column> | 6.055534 | 5.667805 | 1.068409 |
column = self.column(model=model)
if column:
yield column
check = self.__value
if not isinstance(check, (list, set, tuple)):
check = (check,)
for val in check:
if isinstance(val, (Query, QueryCompound)):
for col in va... | def columns(self, model=None) | Returns a generator that loops through the columns that are associated with this query.
:return <generator>(orb.Column) | 4.719015 | 4.182019 | 1.128406 |
newq = self.copy()
newq.setOp(Query.Op.Contains)
newq.setValue(value)
newq.setCaseSensitive(caseSensitive)
return newq | def contains(self, value, caseSensitive=False) | Sets the operator type to Query.Op.Contains and sets the
value to the inputted value. Use an astrix for wildcard
characters.
:param value <variant>
:param caseSensitive <bool>
:return self (useful for chaining)
... | 4.015392 | 3.400619 | 1.180783 |
options = {
'op': self.__op,
'caseSensitive': self.__caseSensitive,
'value': copy.copy(self.__value),
'inverted': self.__inverted,
'functions': copy.copy(self.__functions),
'math': copy.copy(self.__math)
}
return or... | def copy(self) | Returns a duplicate of this instance.
:return <Query> | 4.536397 | 4.755178 | 0.953991 |
newq = self.copy()
newq.setOp(Query.Op.DoesNotContain)
newq.setValue(value)
return newq | def doesNotContain(self, value) | Sets the operator type to Query.Op.DoesNotContain and sets the
value to the inputted value.
:param value <variant>
:return self (useful for chaining)
:usage |>>> from orb import Query as Q
|>>> query = Q('comments').do... | 5.458731 | 4.780829 | 1.141796 |
newq = self.copy()
newq.setOp(Query.Op.DoesNotMatch)
newq.setValue(value)
newq.setCaseSensitive(caseSensitive)
return newq | def doesNotMatch(self, value, caseSensitive=True) | Sets the operator type to Query.Op.DoesNotMatch and sets the \
value to the inputted value.
:param value <variant>
:return self (useful for chaining)
:usage |>>> from orb import Query as Q
|>>> query = Q('comments').do... | 3.713222 | 3.595033 | 1.032876 |
newq = self.copy()
newq.setOp(Query.Op.Endswith)
newq.setValue(value)
return newq | def endswith(self, value) | Sets the operator type to Query.Op.Endswith and sets \
the value to the inputted value. This method will only work on text \
based fields.
:param value <str>
:return <Query>
:usage |>>> from orb import Query as Q
... | 5.598679 | 4.846758 | 1.155139 |
model = self.__model or model
if not model:
raise orb.errors.QueryInvalid('Could not traverse: {0}'.format(self.__column))
schema = model.schema()
parts = self.__column.split('.')
# expand the current column
lookup = schema.column(parts[0], raise_=F... | def expand(self, model=None, ignoreFilter=False) | Expands any shortcuts that were created for this query. Shortcuts
provide the user access to joined methods using the '.' accessor to
access individual columns for referenced tables.
:param model | <orb.Model> || None
:usage |>>> from orb import Query as Q
... | 4.2307 | 4.147769 | 1.019994 |
newq = self.copy()
newq.setOp(Query.Op.Is)
newq.setValue(value)
return newq | def is_(self, value) | Sets the operator type to Query.Op.Is and sets the
value to the inputted value.
:param value <variant>
:return <Query>
:sa __eq__
:usage |>>> from orb import Query as Q
|>>> query = Q('test').is_(... | 6.305057 | 5.026241 | 1.254428 |
newq = self.copy()
newq.setOp(Query.Op.GreaterThan)
newq.setValue(value)
return newq | def greaterThan(self, value) | Sets the operator type to Query.Op.GreaterThan and sets the
value to the inputted value.
:param value <variant>
:return <Query>
:sa __gt__
:usage |>>> from orb import Query as Q
|>>> query = Q('te... | 6.002587 | 4.97402 | 1.206788 |
newq = self.copy()
newq.setOp(Query.Op.GreaterThanOrEqual)
newq.setValue(value)
return newq | def greaterThanOrEqual(self, value) | Sets the operator type to Query.Op.GreaterThanOrEqual and
sets the value to the inputted value.
:param value <variant>
:return <Query>
:sa __ge__
:usage |>>> from orb import Query as Q
|>>> query... | 5.634929 | 4.686213 | 1.202448 |
out = self.copy()
out.setInverted(not self.isInverted())
return out | def inverted(self) | Returns an inverted copy of this query.
:return <orb.Query> | 6.142176 | 7.380043 | 0.832268 |
newq = self.copy()
newq.setOp(Query.Op.IsNot)
newq.setValue(value)
return newq | def isNot(self, value) | Sets the operator type to Query.Op.IsNot and sets the
value to the inputted value.
:param value <variant>
:return <Query>
:sa __ne__
:usage |>>> from orb import Query as Q
|>>> query = Q('test').i... | 6.0592 | 4.908569 | 1.234413 |
newq = self.copy()
newq.setOp(Query.Op.IsIn)
if isinstance(value, orb.Collection):
newq.setValue(value)
elif not isinstance(value, (set, list, tuple)):
newq.setValue((value,))
else:
newq.setValue(tuple(value))
return newq | def in_(self, value) | Sets the operator type to Query.Op.IsIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query = Q('test').isIn([1,2])
|>>> p... | 4.329885 | 3.580163 | 1.20941 |
newq = self.copy()
newq.setOp(Query.Op.IsNotIn)
if isinstance(value, orb.Collection):
newq.setValue(value)
elif not isinstance(value, (set, list, tuple)):
newq.setValue((value,))
else:
newq.setValue(tuple(value))
return newq | def notIn(self, value) | Sets the operator type to Query.Op.IsNotIn and sets the value
to the inputted value.
:param value <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query = Q('test').not_in([1,2])
|... | 4.152804 | 3.556845 | 1.167553 |
newq = self.copy()
newq.setOp(Query.Op.LessThan)
newq.setValue(value)
return newq | def lessThan(self, value) | Sets the operator type to Query.Op.LessThan and sets the
value to the inputted value.
:param value <variant>
:return <Query>
:sa lessThan
:usage |>>> from orb import Query as Q
|>>> query = Q('tes... | 5.829792 | 4.6787 | 1.246028 |
newq = self.copy()
newq.setOp(Query.Op.LessThanOrEqual)
newq.setValue(value)
return newq | def lessThanOrEqual(self, value) | Sets the operator type to Query.Op.LessThanOrEqual and sets
the value to the inputted value.
:param value <variant>
:return <Query>
:sa lessThanOrEqual
:usage |>>> from orb import Query as Q
|>>>... | 5.472656 | 4.245271 | 1.289118 |
q = self.copy()
q.addFunction(Query.Function.Lower)
return q | def lower(self) | Returns a new query for this instance with Query.Function.Lower as
a function option.
:return <Query> | 19.630579 | 6.064641 | 3.236891 |
newq = self.copy()
newq.setOp(Query.Op.Matches)
newq.setValue(value)
newq.setCaseSensitive(caseSensitive)
return newq | def matches(self, value, caseSensitive=True) | Sets the operator type to Query.Op.Matches and sets \
the value to the inputted regex expression. This method will only work \
on text based fields.
:param value <str>
:return <Query>
:usage |>>> from orb import Query as Q
... | 3.856047 | 3.649867 | 1.05649 |
query = self.copy()
op = self.op()
query.setOp(self.NegatedOp.get(op, op))
query.setValue(self.value())
return query | def negated(self) | Negates the current state for this query.
:return <self> | 7.120473 | 6.677359 | 1.066361 |
if not isinstance(other, (Query, QueryCompound)) or other.isNull():
return self.copy()
elif not self:
return other.copy()
else:
return orb.QueryCompound(self, other, op=orb.QueryCompound.Op.Or) | def or_(self, other) | Creates a new compound query using the
<orb.QueryCompound.Op.Or> type.
:param other <Query> || <orb.QueryCompound>
:return <orb.QueryCompound>
:sa or_
:usage |>>> from orb import Query as Q
|>>> quer... | 6.751115 | 4.430194 | 1.523887 |
self.__value = projex.text.decoded(value) if isinstance(value, (str, unicode)) else value | def setValue(self, value) | Sets the value that will be used for this query instance.
:param value <variant> | 12.737418 | 18.705765 | 0.680935 |
newq = self.copy()
newq.setOp(Query.Op.Startswith)
newq.setValue(value)
return newq | def startswith(self, value) | Sets the operator type to Query.Op.Startswith and sets \
the value to the inputted value. This method will only work on text \
based fields.
:param value <str>
:return <Query>
:usage |>>> from orb import Query as Q
... | 5.517354 | 4.455631 | 1.238288 |
q = self.copy()
q.addFunction(Query.Function.Upper)
return q | def upper(self) | Returns this query with the Upper function added to its list.
:return <Query> | 19.720678 | 9.304398 | 2.119501 |
if jdata['type'] == 'compound':
queries = [orb.Query.fromJSON(jquery) for jquery in jdata['queries']]
out = orb.QueryCompound(*queries)
out.setOp(orb.QueryCompound.Op(jdata['op']))
return out
else:
if jdata.get('model'):
... | def fromJSON(jdata) | Creates a new Query object from the given JSON data.
:param jdata | <dict>
:return <orb.Query> || <orb.QueryCompound> | 2.991339 | 2.715077 | 1.101751 |
for query in self.__queries:
for column in query.columns(model=model):
yield column | def columns(self, model=None) | Returns any columns used within this query.
:return [<orb.Column>, ..] | 6.289529 | 5.127913 | 1.226528 |
queries = []
current_records = None
for query in self.__queries:
sub_q = query.expand(model)
if not sub_q:
continue
# chain together joins into sub-queries
if ((isinstance(sub_q, orb.Query) and isinstance(sub_q.value(), o... | def expand(self, model=None, ignoreFilter=False) | Expands any shortcuts that were created for this query. Shortcuts
provide the user access to joined methods using the '.' accessor to
access individual columns for referenced tables.
:param model | <orb.Model>
:usage |>>> from orb import Query as Q
|>>> #... | 3.511968 | 3.417322 | 1.027696 |
op = QueryCompound.Op.And if self.__op == QueryCompound.Op.Or else QueryCompound.Op.Or
return QueryCompound(*self.__queries, op=op) | def negated(self) | Negates this instance and returns it.
:return self | 7.002895 | 9.322021 | 0.751221 |
if not isinstance(other, (Query, QueryCompound)) or other.isNull():
return self.copy()
elif self.isNull():
return other.copy()
else:
# grow this if the operators are the same
if self.__op == QueryCompound.Op.And:
queries = ... | def or_(self, other) | Creates a new compound query using the
QueryCompound.Op.Or type.
:param other <Query> || <QueryCompound>
:return <QueryCompound>
:sa or_
:usage |>>> from orb import Query as Q
|>>> query = (Q('test') != 1).or_(Q('name') == 'Eric')
... | 4.313255 | 3.728662 | 1.156784 |
for query in self.__queries:
if isinstance(query, orb.Query):
yield query.model(model)
else:
for model in query.models(model):
yield model | def models(self, model=None) | Returns the tables that this query is referencing.
:return [ <subclass of Table>, .. ] | 4.793273 | 4.7282 | 1.013763 |
handlers = []
self.static_root = self.application.get_app_component(
).get_component_path()
if self.conf:
if 'maps' in self.conf:
if self.conf['maps'] is None:
logger.warning("Maps configuration is empty. Finish the"
... | def get_handlers(self) | Returns the handlers defined on the static_maps.yml file located
at the app config directory.
Returns: An array of static handlers to be added to the app. | 2.800141 | 2.717481 | 1.030418 |
if node.op != "%":
return
pattern = node.left.as_string()
# If the pattern's not a constant string, we don't know whether a
# dictionary or a tuple makes sense, so don't try to guess.
if not pattern.startswith("'") or pattern.startswith('"'):
retu... | def visit_binop(self, node) | Called when if a binary operation is found.
Only check for string formatting operations.
@param node: currently checking node | 5.67445 | 5.840691 | 0.971537 |
modulename = node.name.split(".")[-1]
if isTestModule(node.name) and self.moduleContainsTestCase(node):
self._checkTestModuleName(modulename, node) | def visit_module(self, node) | A interface will be called when visiting a module.
@param node: node of current module | 7.789801 | 9.128418 | 0.853357 |
if not node.is_method():
# We only check methods.
return
name = node.name
if isTestModule(node.root().name):
if name.startswith('test'):
if not name.startswith('test_'):
self.add_message('C9303', node=node)
... | def visit_functiondef(self, node) | A interface will be called when visiting a function or a method.
@param node: the current node | 3.281169 | 3.352535 | 0.978713 |
targetName = node.name
for sibling in node.parent.nodes_of_class(type(node)):
if sibling is node:
# We are on the same node in parent so we skip it.
continue
prefix = self._getCommonStart(targetName, sibling.name)
if not prefix... | def _getMethodNamePrefix(self, node) | Return the prefix of this method based on sibling methods.
@param node: the current node | 6.8716 | 7.098499 | 0.968036 |
prefix = []
for a, b in zip(left, right):
if a == b:
prefix.append(a)
else:
break
return ''.join(prefix) | def _getCommonStart(self, left, right) | Return the common prefix of the 2 strings.
@param left: one string
@param right: another string | 2.908491 | 2.812881 | 1.03399 |
config['manifest'] = manifest
config['model_mock'] = model_mock
IRC = IrcBot(config)
try:
IRC.start()
except KeyboardInterrupt:
pass | def listen(manifest, config, model_mock=False) | IRC listening process. | 4.351107 | 3.341975 | 1.301957 |
try:
user = self.get(username=username)
except User.DoesNotExist:
return None
if bcrypt.hashpw(password, user.pass_hash) == user.pass_hash:
return user
else:
return None | def get_user_by_password(self, username, password) | Given a username and a raw, unhashed password, get the corresponding
user, retuns None if no match is found. | 2.464018 | 2.469077 | 0.997951 |
class AuthenticatedOrRedirect(GiottoInputMiddleware):
def http(self, request):
if request.user:
return request
return Redirection(invocation)
def cmd(self, request):
if request.user:
return request
return Redirecti... | def AuthenticatedOrRedirect(invocation) | Middleware class factory that redirects if the user is not logged in.
Otherwise, nothing is effected. | 4.978444 | 4.896871 | 1.016658 |
if function is not None:
self.__query_filter = function
return function
def wrapper(func):
self.__query_filter = func
return func
return wrapper | def queryFilter(self, function=None) | Defines a decorator that can be used to filter
queries. It will assume the function being associated
with the decorator will take a query as an input and
return a modified query to use.
:usage
class MyModel(orb.Model):
objects = orb.ReverseLookup('Object')
... | 3.365009 | 4.92315 | 0.683507 |
class AuthProgram(Program):
pre_input_middleware = [AuthenticationMiddleware]
def register(username, password, password2):
result = basic_register(username, password, password2)
callback = kwargs.get('post_register_callback', None)
if callback:
user = U... | def create_auth_manifest(**kwargs) | Creates a basic authentication manifest for logging in, logging out and
registering new accounts. | 4.176065 | 4.141556 | 1.008333 |
def decorator(fn: 'Callable') -> 'Callable':
metadata = _ctypes_metadata(fn)
prototype = proto_factory(
metadata.restype, *metadata.argtypes,
use_errno=use_errno, use_last_error=use_last_error)
func_spec = (name_or_ordinal or fn.__name__, library)
return ... | def Function(
library: CDLL,
name_or_ordinal: 'Union[str, int, None]'=None,
proto_factory: ('Union[ctypes.CFUNCTYPE, ctypes.WINFUNCTYPE,'
' ctypes.PYFUNCTYPE]')=CFUNCTYPE,
use_errno: bool=False,
use_last_error: bool=False,
) -> 'Callable' | Decorator factory for creating callables for native functions.
Decorator factory for constructing relatively-nicely-looking callables that
call into existing native functions exposed from a dynamically-linkable
library.
:param library:
The library to look at
:param name_or_ordinal:
... | 4.091759 | 4.489655 | 0.911375 |
def _create_app_session():
cfg = ComponentConfig(self._realm, self._extra)
try:
session = make(cfg)
except Exception as e:
# the app component could not be created .. fatal
asyncio.get_event_loop().stop()
... | def run(self, make) | Run the application component.
:param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession`
when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
:type make: callable | 4.324249 | 3.738155 | 1.156787 |
if self._access is not None:
_logger.debug("Cleaning up")
pci_cleanup(self._access)
self._access = None | def close(self) | Release libpci resources. | 9.486222 | 6.108883 | 1.552857 |
buf = ctypes.create_string_buffer(1024)
_logger.debug("Performing the lookup on vendor %#06x", vendor_id)
flags = self._flags | pci_lookup_mode.PCI_LOOKUP_VENDOR
pci_lookup_name1(self._access, buf, ctypes.sizeof(buf), flags,
vendor_id)
return buf... | def lookup_vendor_name(self, vendor_id) | Lookup the name of a given vendor.
:param vendor_id:
PCI vendor identifier
:ptype vendor_id:
int
:returns:
Name of the PCI vendor.
.. note::
Lookup respects various flag properties that impact the behavior
in case the name can... | 6.422273 | 6.227367 | 1.031298 |
buf = ctypes.create_string_buffer(1024)
_logger.debug("Performing the lookup on vendor:device %#06x:%#06x",
vendor_id, device_id)
flags = self._flags | pci_lookup_mode.PCI_LOOKUP_DEVICE
pci_lookup_name2(self._access, buf, ctypes.sizeof(buf), flags,
... | def lookup_device_name(self, vendor_id, device_id) | Lookup the name of a given device.
:param vendor_id:
PCI vendor identifier
:ptype vendor_id:
int
:param device_id:
PCI device identifier
:ptype device_id:
int
:returns:
Name of the PCI device.
.. note::
... | 5.415819 | 5.535874 | 0.978313 |
buf = ctypes.create_string_buffer(1024)
_logger.debug("Performing the lookup on vendor:device "
"subvendor:subdevice %#06x:%#06x %#06x:%#06x",
vendor_id, device_id, subvendor_id, subdevice_id)
flags = self._flags | pci_lookup_mode.PCI_LOOKUP_S... | def lookup_subsystem_device_name(
self, vendor_id, device_id, subvendor_id, subdevice_id) | Lookup the name of a given subsystem device.
:param vendor_id:
PCI vendor identifier
:ptype vendor_id:
int
:param device_id:
PCI device identifier
:ptype device_id:
int
:param subvendor_id:
PCI subvendor identifier
... | 3.833414 | 3.79343 | 1.01054 |
try:
# use werkzeug if its there
from werkzeug.serving import run_simple
print("Using Werkzeug run_simple")
run_simple(ip, port, application, ssl_context=ssl, processes=processes, **kwargs)
return
except ImportError:
pass
# otherwise just use python's b... | def serve(ip, port, application, ssl=None, processes=1, **kwargs) | Serve a wsgi app (any wsgi app) through with either werkzeug's runserver
or the one that comes with python. Setting `processes` to anything other than 1
will prevent the debigger from working. | 2.626144 | 2.436583 | 1.077798 |
if not invocation.endswith('/'):
invocation += '/'
if not invocation.startswith('/'):
invocation = '/' + invocation
url = invocation
for arg in args:
url += str(arg) + "/"
if kwargs:
url = url[:-1]
url += "?" + urlencode(kwargs)
return url | def make_url(invocation, args=[], kwargs={}) | >>> make_url('some/path/program', ['arg1', 'arg2'], {'arg3': 4})
'/some/path/program/arg1/arg2?arg3=4' | 2.841625 | 2.940175 | 0.966482 |
class FakeRequest(object):
method = 'GET'
path = request.path
headers = request.headers
GET = request.GET
POST = request.POST
user = getattr(request, 'user', None)
cookies = request.cookies
is_xhr = request.is_xhr
return FakeRequest() | def make_duplicate_request(request) | Since werkzeug request objects are immutable, this is needed to create an
identical reuet object with immutable values so it can be retried after a
POST failure. | 3.179945 | 2.981375 | 1.066604 |
def application(environ, start_response):
try:
return app(environ, start_response)
except Exception as exc:
sio = StringIO()
traceback.print_exc(file=sio)
sio.seek(0)
response = Response(
status=500,
bo... | def fancy_error_template_middleware(app) | WGSI middleware for catching errors and rendering the error page. | 2.319037 | 2.267741 | 1.02262 |
import tornado.ioloop
from tornado.process import task_id
tid = task_id()
pid = os.getpid()
if tid is None:
logger.warning("main process (pid %s) caught signal: %s" %
(pid, sig))
else:
logger.warning("child %s (p... | def sig_handler(self, sig, _) | Handle the signal sent to the process
:param sig: Signal set to the process
:param _: Frame is not being used | 2.853511 | 2.97101 | 0.960451 |
utc_now = datetime.datetime.utcnow()
return self.valueFromString(utc_now.strftime(self.defaultFormat())) | def random(self) | Returns a random value that fits this column's parameters.
:return: <variant> | 9.486186 | 10.69744 | 0.886772 |
if db_value is None:
return None
elif isinstance(db_value, (str, unicode)):
return self.valueFromString(db_value, context=context)
else:
return super(AbstractDatetimeColumn, self).dbRestore(db_value, context=context) | def dbRestore(self, db_value, context=None) | Converts a stored database value to Python.
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant> | 2.89467 | 3.12787 | 0.925444 |
if py_value is None:
return None
return self.valueToString(py_value, context=context) | def dbStore(self, typ, py_value, context=None) | Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant> | 5.01949 | 6.536629 | 0.767902 |
if value in ('today', 'now'):
return datetime.date.today()
elif dateutil_parser:
return dateutil_parser.parse(value).date()
else:
time_struct = time.strptime(value, self.defaultFormat())
return datetime.date(time_struct.tm_year,
... | def valueFromString(self, value, context=None) | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str> | 3.041537 | 3.435078 | 0.885435 |
if isinstance(py_value, datetime.datetime):
# ensure we have some timezone information before converting to UTC time
if py_value.tzinfo is None:
# match the server information
tz = pytz.timezone(orb.system.settings().server_timezone)
... | def dbStore(self, typ, py_value) | Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:return: <variant> | 4.083593 | 3.785153 | 1.078845 |
value = super(DatetimeWithTimezoneColumn, self).restore(value, context)
if value in ('today', 'now'):
value = datetime.date.now()
if isinstance(value, datetime.datetime):
tz = pytz.timezone(context.timezone)
if tz is not None:
if va... | def restore(self, value, context=None) | Restores the value from a table cache for usage.
:param value | <variant>
context | <orb.Context> || None | 4.778589 | 4.932494 | 0.968798 |
if isinstance(value, datetime.datetime):
# ensure we have some timezone information before converting to UTC time
if value.tzinfo is None:
# match the server information
tz = pytz.timezone(orb.system.settings().server_timezone)
val... | def store(self, value, context=None) | Converts the value to one that is safe to store on a record within
the record values dictionary
:param value | <variant>
:return <variant> | 4.327302 | 4.619666 | 0.936713 |
if isinstance(db_value, datetime.timedelta):
hours, remain = divmod(db_value.seconds, 3600)
minutes, seconds = divmod(remain, 60)
return datetime.time(hours, minutes, seconds)
else:
return super(TimeColumn, self).dbRestore(db_value, context=contex... | def dbRestore(self, db_value, context=None) | Converts a stored database value to Python.
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant> | 2.246622 | 2.532677 | 0.887054 |
if value == 'now':
return datetime.datetime.now().time()
elif dateutil_parser:
return dateutil_parser.parse(value).time()
else:
time_struct = time.strptime(value, self.defaultFormat())
return datetime.time(time_struct.tm_hour,
... | def valueFromString(self, value, context=None) | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str> | 2.813273 | 3.042894 | 0.924538 |
if value in ('today', 'now'):
return datetime.datetime.utcnow()
elif dateutil_parser:
return dateutil_parser.parse(value)
else:
time_struct = time.strptime(value, self.defaultFormat())
return datetime.datetime(time_struct.tm_year,
... | def valueFromString(self, value, context=None) | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
extra | <variant> | 2.516402 | 2.669727 | 0.942569 |
if isinstance(db_value, (int, long, float)):
return datetime.datetime.fromtimestamp(db_value)
else:
return super(UTC_TimestampColumn, self).dbRestore(db_value, context=context) | def dbRestore(self, db_value, context=None) | Restores the value from a table cache for usage.
:param value | <variant>
context | <orb.Context> || None | 3.242786 | 4.448243 | 0.729004 |
if isinstance(py_value, datetime.datetime):
return time.mktime(py_value.timetuple())
else:
return super(UTC_TimestampColumn, self).dbStore(typ, py_value) | def dbStore(self, typ, py_value) | Converts the value to one that is safe to store on a record within
the record values dictionary
:param value | <variant>
:return <variant> | 3.194402 | 4.066048 | 0.785628 |
if value in ('today', 'now'):
return datetime.date.utcnow()
try:
return datetime.datetime.fromtimestamp(float(value))
except StandardError:
if dateutil_parser:
return dateutil_parser.parse(value)
else:
retu... | def valueFromString(self, value, context=None) | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str> | 4.459086 | 5.335335 | 0.835765 |
if user_agent:
b = reg_b.search(user_agent)
v = reg_v.search(user_agent[0:4])
return b or v
return False | def is_mobile(user_agent) | Checks if the user browser from the given user agent is mobile.
Args:
user_agent: A given user agent.
Returns: True if the browser from the user agent is mobile. | 5.126554 | 5.748178 | 0.891857 |
if not invocation.endswith('/'):
invocation += '/'
if not invocation.startswith('/'):
invocation = '/' + invocation
cmd = invocation
for arg in args:
cmd += str(arg) + "/"
rendered_kwargs = []
for k, v in kwargs.items():
rendered_kwargs.append("--%s=%s" % ... | def make_cmd_invocation(invocation, args, kwargs) | >>> make_cmd_invocation('path/program', ['arg1', 'arg2'], {'darg': 4})
['./giotto-cmd', '/path/program/arg1/arg2/', '--darg=4'] | 4.018065 | 2.996691 | 1.340834 |
arguments = self.request.argv[1:]
if not arguments[0].startswith('--'):
# first argument is the program name
arguments = arguments[1:]
return parse_kwargs(arguments) | def get_raw_data(self) | Parse the raw commandline arguments (from sys.argv) to a dictionary
that is understandable to the rest of the framework. | 8.008426 | 5.823181 | 1.375266 |
properties = {}
for key, value in self.raw_values.items():
if key in self.UnhashableOptions:
properties[key] = value
else:
properties[key] = copy.copy(value)
return Context(**properties) | def copy(self) | Returns a copy of this database option set.
:return <orb.Context> | 5.201621 | 4.35303 | 1.194943 |
if model and not self.columns:
schema = model.schema()
defaults = schema.columns(flags=orb.Column.Flags.AutoExpand).keys()
defaults += schema.collectors(flags=orb.Collector.Flags.AutoExpand).keys()
else:
defaults = []
expand = self.expand... | def expandtree(self, model=None) | Goes through the expand options associated with this context and
returns a trie of data.
:param model: subclass of <orb.Model> || None
:return: <dict> | 3.911674 | 3.725855 | 1.049873 |
check = self.raw_values.copy()
scope = check.pop('scope', {})
return len(check) == 0 and len(scope) == 0 | def isNull(self) | Returns whether or not this option set has been modified.
:return <bool> | 8.914934 | 9.713824 | 0.917757 |
# convert a context instance into a dictionary
if isinstance(other_context, orb.Context):
other_context = copy.copy(other_context.raw_values)
ignore = ('where', 'columns', 'scope')
inherit_kwds = {}
inherit_scope = {}
inherit_columns = []
inh... | def update(self, other_context) | Updates this lookup set with the inputted options.
:param other_context | <dict> || <orb.Context> | 2.158575 | 2.133847 | 1.011589 |
module_x = module.split('.')
cur_path = ''
for path in module_x:
cur_path = os.path.join(cur_path, path)
if not os.path.isdir(os.path.join(target, cur_path)):
os.mkdir(os.path.join(target, cur_path))
if not os.path.exists(os.path.join(target, cur_path, '__init__.py')... | def create_module(module, target) | Create a module directory structure into the target directory. | 1.955246 | 1.789504 | 1.092619 |
filename_x = filename.split('.')
if len(filename_x) > 1:
if filename_x[-1].strip() is not '':
return filename_x[-1]
return None | def get_file_extension(filename) | Return the extension if the filename has it. None if not.
:param filename: The filename.
:return: Extension or None. | 3.433568 | 3.771368 | 0.91043 |
mode = "w"
if binary:
mode = "wb"
with open(path, mode) as f:
f.write(data)
f.close() | def write(path, data, binary=False) | Writes a given data to a file located at the given path. | 2.344975 | 2.348561 | 0.998473 |
data = None
with open(path, 'r') as f:
data = f.read()
f.close()
return data | def read(path) | Reads a file located at the given path. | 2.685982 | 2.486075 | 1.080411 |
with open(path, 'a') as f:
os.utime(path, None)
f.close() | def touch(path) | Creates a file located at the given path. | 2.645701 | 3.164283 | 0.836114 |
return projex.text.nativestring(value).lower() == 'true' | def valueFromString(self, value, extra=None, db=None) | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
extra | <variant> | 18.224968 | 53.730492 | 0.339192 |
try:
from webhelpers.text import strip_tags
return strip_tags(py_value)
except ImportError:
warnings.warn('Unable to clean string column without webhelpers installed.')
return py_value | def clean(self, py_value) | Cleans the value before storing it.
:param: py_value : <str>
:return: <str> | 6.030815 | 6.674605 | 0.903546 |
if py_value is not None:
py_value = projex.text.decoded(py_value)
if self.cleaned():
py_value = self.clean(py_value)
if self.escaped():
py_value = self.escape(py_value)
return py_value
else:
return py... | def dbStore(self, typ, py_value) | Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:return: <variant> | 4.545657 | 4.502012 | 1.009695 |
# ensure this value is a string type
if isinstance(value, (str, unicode)):
value = projex.text.decoded(value)
return super(AbstractStringColumn, self).restore(value, context) | def restore(self, value, context=None) | Restores the value from a table cache for usage.
:param value | <variant>
context | <orb.Context> || None | 8.252934 | 10.086114 | 0.818247 |
if isinstance(value, (str, unicode)) and self.testFlag(self.Flags.Encrypted):
value = orb.system.security().encrypt(value)
return super(AbstractStringColumn, self).store(value, context=context) | def store(self, value, context=None) | Converts the value to one that is safe to store on a record within
the record values dictionary
:param value | <variant>
:return <variant> | 8.651228 | 8.898403 | 0.972223 |
super(StringColumn, self).loadJSON(jdata)
# load additional info
self.__maxLength = jdata.get('maxLength') or self.__maxLength | def loadJSON(self, jdata) | Loads JSON data for this column type.
:param jdata: <dict> | 8.503306 | 7.191008 | 1.182492 |
return '#' + random.randrange(256).encode('hex') + \
random.randrange(256).encode('hex') + random.randrange(256).encode('hex') | def random(self) | Returns a random value that fits this column's parameters.
:return: <variant> | 3.54196 | 4.212652 | 0.840791 |
if isinstance(value, (str, unicode)) and not re.match(self.__pattern, value):
raise orb.errors.ColumnValidationError(self, 'The email provided is not valid.')
else:
return super(EmailColumn, self).validate(value) | def validate(self, value) | Validates the value provided is a valid email address,
at least, on paper.
:param value: <str>
:return: <bool> | 5.589939 | 5.738043 | 0.974189 |
try:
import bleach
return bleach.clean(py_value, **self.__bleachOptions)
except ImportError:
warnings.warn('Unable to clean string column without webhelpers installed.')
return py_value | def clean(self, py_value) | Cleans the value before storing it.
:param: py_value : <str>
:return: <str> | 8.996087 | 9.232617 | 0.974381 |
rules = ['Passwords need to be at least {0} characters long'.format(self.__minlength)]
if self.__requireUppercase:
rules.append('have at least one uppercase letter')
if self.__requireLowercase:
rules.append('have at least one lowercase letter')
if self._... | def rules(self) | Returns the rules for this password based on the configured
options.
:return: <str> | 2.490621 | 2.487779 | 1.001142 |
if not isinstance(value, (str, unicode)):
raise orb.errors.ColumnValidationError(self, 'Invalid password.')
elif not self.__allowUnicode and value != projex.text.toAscii(value):
raise orb.errors.ColumnValidationError(self, 'Only ASCII characters are allowed for your pas... | def validate(self, value) | Ensures that the password follows the following criteria:
:param value: <str>
:return: True | 3.017404 | 3.115929 | 0.96838 |
try:
model = self.schema().model()
except AttributeError:
return os.urandom(self.__bits).encode('hex')
else:
while True:
token = os.urandom(self.__bits).encode('hex')
if model.select(where=orb.Query(self) == token).coun... | def generate(self) | Generates a new token for this column based on its bit length. This method
will not ensure uniqueness in the model itself, that should be checked against
the model records in the database first.
:return: <str> | 6.077804 | 4.500368 | 1.350513 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.