function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def __init__(self):
import tty, sys | tpainter/df_everywhere | [
13,
3,
13,
1,
1401129417
] |
def __init__(self):
import msvcrt | tpainter/df_everywhere | [
13,
3,
13,
1,
1401129417
] |
def __init__(self, config, stage_type, ar_globals):
"""The constructor"""
self.config = config
self.type = stage_type
self.LOG = ar_globals['LOG']
try:
self.url = config.get(self.type, 'url')
self.method = config.get(self.type, 'method')
self.server = ServerProxy(self.url)
except:
raise BadConfig, 'Bad config in xmlrpc backend'
self.LOG(E_ALWAYS, 'XmlRpc Backend (%s) at %s' % (self.type, self.url)) | sherpya/archiver | [
3,
2,
3,
1,
1251993966
] |
def __init__(self, parent=None):
QAbstractListModel.__init__(self, parent)
self.cards = Cards() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def _checkActive(self):
if not self.isActive():
raise CardModel.ModelNotActiveError, "Model is not active. Use open first." | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def close(self):
self.emit(SIGNAL('modelAboutToBeReset()'))
self.cards.close()
self.reset() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def isActive(self):
return self.cards.isOpen() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
else:
if self.cards.isOpen():
return self.cards.getCardsCount()
else:
return 0 | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def index(self, row, column, parent=QModelIndex()):
if row < 0 or column < 0 or not self.cards.isOpen():
return QModelIndex()
else:
# returns index with given card id
header = self.cards.getCardHeaders('', row, row + 1)
if len(header) == 1:
return self.createIndex(row, column, int(header[0][0]))
else:
return QModelIndex() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def data(self, index, role=Qt.DisplayRole):
self._checkIndex(index)
if role not in (Qt.DisplayRole, Qt.UserRole):
return QVariant()
card = self.cards.getCard(index.internalId())
if role == Qt.UserRole:
return card
else:
if index.column() == 0:
return QVariant('#%d %s' % (card.id, str(card.question).strip()))
elif index.column() == 1:
return QVariant('%s' % str(card.answer).strip())
elif index.column() == 2:
return QVariant('%s' % str(card.question_hint).strip())
elif index.column() == 3:
return QVariant('%s' % str(card.answer_hint).strip())
elif index.column() == 4:
return QVariant('%s' % str(card.score))
else:
return QVariant() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section == 0:
return QVariant("Question")
elif section == 1:
return QVariant("Answer")
elif section == 2:
return QVariant(tr("Question hint"))
elif section == 3:
return QVariant(tr("Answer hint"))
elif section == 4:
return QVariant(tr("Score"))
else:
return QVariant()
else:
return QVariant(str(section))
return QVariant() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def getNextIndex(self, index):
"""Returns next index after given or given if it's last."""
self._checkIndex(index)
if index.row() == self.rowCount() - 1:
return index
else:
return self.index(index.row() + 1, 0)
# get row after ? | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def addNewCard(self):
"""Adds a new empty card."""
self.emit(SIGNAL('modelAboutToBeReset()'))
rowid = self.cards.addCard(Card())
# TODO is it ok to return it here?
result = self.createIndex(self.cards.getCardsCount(), 0, rowid)
# cards.addCard(Card())
# TODO
# why these do not work ?
self.reset()
# self.emit(SIGNAL('modelReset()'))
#
return result | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def updateCard(self, index, question, answer):
self._checkIndex(index)
card = Card(index.internalId(), question, answer)
self.cards.updateCard(card)
# update data in the model
self.emit(SIGNAL('dataChanged(QModelIndex)'), index) | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def importQAFile(self, file, clean=True):
"""Import cards from given question&answer file.
@param file can be file name or file like object
"""
self.emit(SIGNAL('modelAboutToBeReset()'))
self._checkActive()
if isstring(file):
file = open(file, 'rt')
if clean:
self.cards.deleteAllCards()
prefix = ''
last_prefix = ''
card = Card()
for line in file.readlines():
if line.upper().startswith('Q:') or line.upper().startswith('A:'):
last_prefix = prefix
prefix = line[:2].upper()
line = line[3:]
# if new card then recreate
if prefix == 'Q:' and prefix != last_prefix:
if not card.isEmpty():
self.cards.addCard(card, False)
card = Card()
if line.strip() != '':
if prefix == 'Q:':
card.question += line
else: # prefix == a
card.answer += line
# add last card
if not card.isEmpty():
self.cards.addCard(card)
# TODO do it in a real transaction way
# in case of error do a rollback
self.cards.commit()
self.reset() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def __init__(self, parent=None):
QAbstractItemModel.__init__(self, parent)
self.cards = [] | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
else:
return len(self.cards) | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def index(self, row, column, parent=QModelIndex()):
if parent.isValid():
return QModelIndex()
else:
if row >= 0 and row < len(self.cards) and column == 0:
return self.createIndex(row, column, None)
else:
return QModelIndex() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def headerData(self, section, orientation, role=Qt.DisplayRole):
return QVariant(str(section))
# return QAbstractItemModel.headerData(self, section, orientation, role) | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def addCard(self, card):
self.emit(SIGNAL('modelAboutToBeReset()'))
self.cards.append(card)
self.reset() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def selectNextCard(self):
# take from the stack and put it on top
if len(self.cards) > 0:
self.emit(SIGNAL('modelAboutToBeReset()'))
result = self.cards[0]
self.cards = self.cards[1:]
self.cards.append(result)
self.reset()
return result
else:
return Card() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def scoreCard(self, card, score):
if score == DrillModel.Good:
log("Card: $card will be removed from drill.")
self.removeCard(card) | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def printCards(self):
print "Printing cards..."
sys.stdout.flush()
i = 0
for card in self.cards:
print "%d %s\n" % (i, str(card))
sys.stdout.flush()
i += 1
print "Done."
sys.stdout.flush() | afolmert/mentor | [
7,
3,
7,
1,
1208166911
] |
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['tata.to']
self.base_link = 'http://tata.to'
self.search_link = '/filme?suche=%s&type=alle'
self.ajax_link = '/ajax/stream/%s' | repotvsupertuga/tvsupertuga.repository | [
1,
8,
1,
4,
1493763534
] |
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'localtvshowtitle': localtvshowtitle,
'aliases': aliases, 'year': year}
url = urllib.urlencode(url)
return url
except:
return | repotvsupertuga/tvsupertuga.repository | [
1,
8,
1,
4,
1493763534
] |
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
ref = urlparse.urljoin(self.base_link, url)
url = urlparse.urljoin(self.base_link, self.ajax_link % re.findall('-(\w+)$', ref)[0])
headers = {'Referer': ref, 'User-Agent': client.randomagent()}
result = client.request(url, headers=headers, post='')
result = base64.decodestring(result)
result = json.loads(result).get('playinfo', [])
if isinstance(result, basestring):
result = result.replace('embed.html', 'index.m3u8')
base_url = re.sub('index\.m3u8\?token=[\w\-]+[^/$]*', '', result)
r = client.request(result, headers=headers)
r = [(i[0], i[1]) for i in
re.findall('#EXT-X-STREAM-INF:.*?RESOLUTION=\d+x(\d+)[^\n]+\n([^\n]+)', r, re.DOTALL) if i]
r = [(source_utils.label_to_quality(i[0]), i[1] + source_utils.append_headers(headers)) for i in r]
r = [{'quality': i[0], 'url': base_url + i[1]} for i in r]
for i in r: sources.append(
{'source': 'CDN', 'quality': i['quality'], 'language': 'de', 'url': i['url'], 'direct': True,
'debridonly': False})
elif result:
result = [i.get('link_mp4') for i in result]
result = [i for i in result if i]
for i in result:
try:
sources.append(
{'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'de',
'url': i, 'direct': True, 'debridonly': False})
except:
pass
return sources
except:
return | repotvsupertuga/tvsupertuga.repository | [
1,
8,
1,
4,
1493763534
] |
def __search_movie(self, imdb, year):
try:
query = urlparse.urljoin(self.base_link, self.search_link % imdb)
y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0']
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'container'})
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'ml-item-content'})
r = [(dom_parser.parse_dom(i, 'a', attrs={'class': 'ml-image'}, req='href'),
dom_parser.parse_dom(i, 'ul', attrs={'class': 'item-params'})) for i in r]
r = [(i[0][0].attrs['href'], re.findall('calendar.+?>.+?(\d{4})', ''.join([x.content for x in i[1]]))) for i
in r if i[0] and i[1]]
r = [(i[0], i[1][0] if len(i[1]) > 0 else '0') for i in r]
r = sorted(r, key=lambda i: int(i[1]), reverse=True) # with year > no year
r = [i[0] for i in r if i[1] in y][0]
return source_utils.strip_domain(r)
except:
return | repotvsupertuga/tvsupertuga.repository | [
1,
8,
1,
4,
1493763534
] |
def do_PUT(self):
print(self.path, flush=True)
content_encoding = self.headers['X-Endless-Content-Encoding']
print(content_encoding, flush=True)
content_length = int(self.headers['Content-Length'])
compressed_request_body = self.rfile.read(content_length)
decompressed_request_body = gzip.decompress(compressed_request_body)
print(len(decompressed_request_body), flush=True)
sys.stdout.buffer.write(decompressed_request_body)
sys.stdout.buffer.flush()
status_code_str = sys.stdin.readline()
status_code = int(status_code_str)
self.send_response(status_code)
self.end_headers() | endlessm/eos-event-recorder-daemon | [
4,
2,
4,
1,
1380568451
] |
def __init__(self):
SERVER_ADDRESS = ('localhost', 0)
super().__init__(SERVER_ADDRESS, PrintingHTTPRequestHandler) | endlessm/eos-event-recorder-daemon | [
4,
2,
4,
1,
1380568451
] |
def __repr__(self):
return '<factory>' | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def __init__(self, name):
self.name = name | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def __getitem__(self, params):
return self | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def __init__(self, default, default_factory, init, repr, hash, compare,
metadata):
self.name = None
self.type = None
self.default = default
self.default_factory = default_factory
self.init = init
self.repr = repr
self.hash = hash
self.compare = compare
self.metadata = (_EMPTY_METADATA
if metadata is None or len(metadata) == 0 else
types.MappingProxyType(metadata))
self._field_type = None | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def __set_name__(self, owner, name):
func = getattr(type(self.default), '__set_name__', None)
if func:
# There is a __set_name__ method on the descriptor, call
# it.
func(self.default, owner, name) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
self.init = init
self.repr = repr
self.eq = eq
self.order = order
self.unsafe_hash = unsafe_hash
self.frozen = frozen | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
hash=None, compare=True, metadata=None):
"""Return an object to identify dataclass fields.
default is the default value of the field. default_factory is a
0-argument function called to initialize a field's value. If init
is True, the field will be a parameter to the class's __init__()
function. If repr is True, the field will be included in the
object's repr(). If hash is True, the field will be included in
the object's hash(). If compare is True, the field will be used
in comparison functions. metadata, if specified, must be a
mapping which is stored but not otherwise examined by dataclass.
It is an error to specify both default and default_factory.
"""
if default is not MISSING and default_factory is not MISSING:
raise ValueError('cannot specify both default and default_factory')
return Field(default, default_factory, init, repr, hash, compare,
metadata) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _recursive_repr(user_function):
# Decorator to make a repr function return "..." for a recursive
# call.
repr_running = set()
@functools.wraps(user_function)
def wrapper(self):
key = id(self), _thread.get_ident()
if key in repr_running:
return '...'
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
return wrapper | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _field_assign(frozen, name, value, self_name):
# If we're a frozen class, then assign to our fields in __init__
# via object.__setattr__. Otherwise, just use a simple
# assignment.
#
# self_name is what "self" is called in this function: don't
# hard-code "self", since that might be a field name.
if frozen:
return f'__builtins__.object.__setattr__({self_name},{name!r},{value})'
return f'{self_name}.{name}={value}' | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _init_param(f):
# Return the __init__ parameter string for this field. For
# example, the equivalent of 'x:int=3' (except instead of 'int',
# reference a variable set to int, and instead of '3', reference a
# variable set to 3).
if f.default is MISSING and f.default_factory is MISSING:
# There's no default, and no default_factory, just output the
# variable name and type.
default = ''
elif f.default is not MISSING:
# There's a default, this will be the name that's used to look
# it up.
default = f'=_dflt_{f.name}'
elif f.default_factory is not MISSING:
# There's a factory function. Set a marker.
default = '=_HAS_DEFAULT_FACTORY'
return f'{f.name}:_type_{f.name}{default}' | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _repr_fn(fields):
fn = _create_fn('__repr__',
('self',),
['return self.__class__.__qualname__ + f"(' +
', '.join([f"{f.name}={{self.{f.name}!r}}"
for f in fields]) +
')"'])
return _recursive_repr(fn) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _cmp_fn(name, op, self_tuple, other_tuple):
# Create a comparison function. If the fields in the object are
# named 'x' and 'y', then self_tuple is the string
# '(self.x,self.y)' and other_tuple is the string
# '(other.x,other.y)'.
return _create_fn(name,
('self', 'other'),
[ 'if other.__class__ is self.__class__:',
f' return {self_tuple}{op}{other_tuple}',
'return NotImplemented']) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _is_classvar(a_type, typing):
# This test uses a typing internal class, but it's the best way to
# test if this is a ClassVar.
return (a_type is typing.ClassVar
or (type(a_type) is typing._GenericAlias
and a_type.__origin__ is typing.ClassVar)) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _is_type(annotation, cls, a_module, a_type, is_type_predicate):
# Given a type annotation string, does it refer to a_type in
# a_module? For example, when checking that annotation denotes a
# ClassVar, then a_module is typing, and a_type is
# typing.ClassVar.
# It's possible to look up a_module given a_type, but it involves
# looking in sys.modules (again!), and seems like a waste since
# the caller already knows a_module.
# - annotation is a string type annotation
# - cls is the class that this annotation was found in
# - a_module is the module we want to match
# - a_type is the type in that module we want to match
# - is_type_predicate is a function called with (obj, a_module)
# that determines if obj is of the desired type.
# Since this test does not do a local namespace lookup (and
# instead only a module (global) lookup), there are some things it
# gets wrong.
# With string annotations, cv0 will be detected as a ClassVar:
# CV = ClassVar
# @dataclass
# class C0:
# cv0: CV
# But in this example cv1 will not be detected as a ClassVar:
# @dataclass
# class C1:
# CV = ClassVar
# cv1: CV
# In C1, the code in this function (_is_type) will look up "CV" in
# the module and not find it, so it will not consider cv1 as a
# ClassVar. This is a fairly obscure corner case, and the best
# way to fix it would be to eval() the string "CV" with the
# correct global and local namespaces. However that would involve
# a eval() penalty for every single field of every dataclass
# that's defined. It was judged not worth it.
match = _MODULE_IDENTIFIER_RE.match(annotation)
if match:
ns = None
module_name = match.group(1)
if not module_name:
# No module name, assume the class's module did
# "from dataclasses import InitVar".
ns = sys.modules.get(cls.__module__).__dict__
else:
# Look up module_name in the class's module.
module = sys.modules.get(cls.__module__)
if module and module.__dict__.get(module_name) is a_module:
ns = sys.modules.get(a_type.__module__).__dict__
if ns and is_type_predicate(ns.get(match.group(2)), a_module):
return True
return False | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _set_new_attribute(cls, name, value):
# Never overwrites an existing attribute. Returns True if the
# attribute already exists.
if name in cls.__dict__:
return True
setattr(cls, name, value)
return False | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _hash_set_none(cls, fields):
return None | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _hash_exception(cls, fields):
# Raise an exception.
raise TypeError(f'Cannot overwrite attribute __hash__ '
f'in class {cls.__name__}') | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
# Now that dicts retain insertion order, there's no reason to use
# an ordered dict. I am leveraging that ordering here, because
# derived class fields overwrite base class fields, but the order
# is defined by the base class, which is found first.
fields = {}
setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,
unsafe_hash, frozen))
# Find our base classes in reverse MRO order, and exclude
# ourselves. In reversed order so that more derived classes
# override earlier field definitions in base classes. As long as
# we're iterating over them, see if any are frozen.
any_frozen_base = False
has_dataclass_bases = False
for b in cls.__mro__[-1:0:-1]:
# Only process classes that have been processed by our
# decorator. That is, they have a _FIELDS attribute.
base_fields = getattr(b, _FIELDS, None)
if base_fields:
has_dataclass_bases = True
for f in base_fields.values():
fields[f.name] = f
if getattr(b, _PARAMS).frozen:
any_frozen_base = True
# Annotations that are defined in this class (not in base
# classes). If __annotations__ isn't present, then this class
# adds no new annotations. We use this to compute fields that are
# added by this class.
#
# Fields are found from cls_annotations, which is guaranteed to be
# ordered. Default values are from class attributes, if a field
# has a default. If the default value is a Field(), then it
# contains additional info beyond (and possibly including) the
# actual default value. Pseudo-fields ClassVars and InitVars are
# included, despite the fact that they're not real fields. That's
# dealt with later.
cls_annotations = cls.__dict__.get('__annotations__', {})
# Now find fields in our class. While doing so, validate some
# things, and set the default values (as class attributes) where
# we can.
cls_fields = [_get_field(cls, name, type)
for name, type in cls_annotations.items()]
for f in cls_fields:
fields[f.name] = f
# If the class attribute (which is the default value for this
# field) exists and is of type 'Field', replace it with the
# real default. This is so that normal class introspection
# sees a real default value, not a Field.
if isinstance(getattr(cls, f.name, None), Field):
if f.default is MISSING:
# If there's no default, delete the class attribute.
# This happens if we specify field(repr=False), for
# example (that is, we specified a field object, but
# no default value). Also if we're using a default
# factory. The class attribute should not be set at
# all in the post-processed class.
delattr(cls, f.name)
else:
setattr(cls, f.name, f.default)
# Do we have any Field members that don't also have annotations?
for name, value in cls.__dict__.items():
if isinstance(value, Field) and not name in cls_annotations:
raise TypeError(f'{name!r} is a field but has no type annotation')
# Check rules that apply if we are derived from any dataclasses.
if has_dataclass_bases:
# Raise an exception if any of our bases are frozen, but we're not.
if any_frozen_base and not frozen:
raise TypeError('cannot inherit non-frozen dataclass from a '
'frozen one')
# Raise an exception if we're frozen, but none of our bases are.
if not any_frozen_base and frozen:
raise TypeError('cannot inherit frozen dataclass from a '
'non-frozen one')
# Remember all of the fields on our class (including bases). This
# also marks this class as being a dataclass.
setattr(cls, _FIELDS, fields)
# Was this class defined with an explicit __hash__? Note that if
# __eq__ is defined in this class, then python will automatically
# set __hash__ to None. This is a heuristic, as it's possible
# that such a __hash__ == None was not auto-generated, but it
# close enough.
class_hash = cls.__dict__.get('__hash__', MISSING)
has_explicit_hash = not (class_hash is MISSING or
(class_hash is None and '__eq__' in cls.__dict__))
# If we're generating ordering methods, we must be generating the
# eq methods.
if order and not eq:
raise ValueError('eq must be true if order is true')
if init:
# Does this class have a post-init function?
has_post_init = hasattr(cls, _POST_INIT_NAME)
# Include InitVars and regular fields (so, not ClassVars).
flds = [f for f in fields.values()
if f._field_type in (_FIELD, _FIELD_INITVAR)]
_set_new_attribute(cls, '__init__',
_init_fn(flds,
frozen,
has_post_init,
# The name to use for the "self"
# param in __init__. Use "self"
# if possible.
'__dataclass_self__' if 'self' in fields
else 'self',
))
# Get the fields as a list, and include only real fields. This is
# used in all of the following methods.
field_list = [f for f in fields.values() if f._field_type is _FIELD]
if repr:
flds = [f for f in field_list if f.repr]
_set_new_attribute(cls, '__repr__', _repr_fn(flds))
if eq:
# Create _eq__ method. There's no need for a __ne__ method,
# since python will call __eq__ and negate it.
flds = [f for f in field_list if f.compare]
self_tuple = _tuple_str('self', flds)
other_tuple = _tuple_str('other', flds)
_set_new_attribute(cls, '__eq__',
_cmp_fn('__eq__', '==',
self_tuple, other_tuple))
if order:
# Create and set the ordering methods.
flds = [f for f in field_list if f.compare]
self_tuple = _tuple_str('self', flds)
other_tuple = _tuple_str('other', flds)
for name, op in [('__lt__', '<'),
('__le__', '<='),
('__gt__', '>'),
('__ge__', '>='),
]:
if _set_new_attribute(cls, name,
_cmp_fn(name, op, self_tuple, other_tuple)):
raise TypeError(f'Cannot overwrite attribute {name} '
f'in class {cls.__name__}. Consider using '
'functools.total_ordering')
if frozen:
for fn in _frozen_get_del_attr(cls, field_list):
if _set_new_attribute(cls, fn.__name__, fn):
raise TypeError(f'Cannot overwrite attribute {fn.__name__} '
f'in class {cls.__name__}')
# Decide if/how we're going to create a hash function.
hash_action = _hash_action[bool(unsafe_hash),
bool(eq),
bool(frozen),
has_explicit_hash]
if hash_action:
# No need to call _set_new_attribute here, since by the time
# we're here the overwriting is unconditional.
cls.__hash__ = hash_action(cls, field_list)
if not getattr(cls, '__doc__'):
# Create a class doc-string.
cls.__doc__ = (cls.__name__ +
str(inspect.signature(cls)).replace(' -> None', ''))
return cls | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
unsafe_hash=False, frozen=False):
"""Returns the same class as was passed in, with dunder methods
added based on the fields defined in the class.
Examines PEP 526 __annotations__ to determine fields.
If init is true, an __init__() method is added to the class. If
repr is true, a __repr__() method is added. If order is true, rich
comparison dunder methods are added. If unsafe_hash is true, a
__hash__() method function is added. If frozen is true, fields may
not be assigned to after instance creation.
"""
def wrap(cls):
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
# See if we're being called as @dataclass or @dataclass().
if _cls is None:
# We're called with parens.
return wrap
# We're called as @dataclass without parens.
return wrap(_cls) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def _is_dataclass_instance(obj):
"""Returns True if obj is an instance of a dataclass."""
return not isinstance(obj, type) and hasattr(obj, _FIELDS) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def asdict(obj, *, dict_factory=dict):
"""Return the fields of a dataclass instance as a new dictionary mapping
field names to field values.
Example usage:
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert asdict(c) == {'x': 1, 'y': 2}
If given, 'dict_factory' will be used instead of built-in dict.
The function applies recursively to field values that are
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
if not _is_dataclass_instance(obj):
raise TypeError("asdict() should be called on dataclass instances")
return _asdict_inner(obj, dict_factory) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def astuple(obj, *, tuple_factory=tuple):
"""Return the fields of a dataclass instance as a new tuple of field values.
Example usage::
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert astuple(c) == (1, 2)
If given, 'tuple_factory' will be used instead of built-in tuple.
The function applies recursively to field values that are
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
if not _is_dataclass_instance(obj):
raise TypeError("astuple() should be called on dataclass instances")
return _astuple_inner(obj, tuple_factory) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
repr=True, eq=True, order=False, unsafe_hash=False,
frozen=False):
"""Return a new dynamically created dataclass.
The dataclass name will be 'cls_name'. 'fields' is an iterable
of either (name), (name, type) or (name, type, Field) objects. If type is
omitted, use the string 'typing.Any'. Field objects are created by
the equivalent of calling 'field(name, type [, Field-info])'.
C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
is equivalent to:
@dataclass
class C(Base):
x: 'typing.Any'
y: int
z: int = field(init=False)
For the bases and namespace parameters, see the builtin type() function.
The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
dataclass().
"""
if namespace is None:
namespace = {}
else:
# Copy namespace since we're going to mutate it.
namespace = namespace.copy()
# While we're looking through the field names, validate that they
# are identifiers, are not keywords, and not duplicates.
seen = set()
anns = {}
for item in fields:
if isinstance(item, str):
name = item
tp = 'typing.Any'
elif len(item) == 2:
name, tp, = item
elif len(item) == 3:
name, tp, spec = item
namespace[name] = spec
else:
raise TypeError(f'Invalid field: {item!r}')
if not isinstance(name, str) or not name.isidentifier():
raise TypeError(f'Field names must be valid identifers: {name!r}')
if keyword.iskeyword(name):
raise TypeError(f'Field names must not be keywords: {name!r}')
if name in seen:
raise TypeError(f'Field name duplicated: {name!r}')
seen.add(name)
anns[name] = tp
namespace['__annotations__'] = anns
# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
# of generic dataclassses.
cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
unsafe_hash=unsafe_hash, frozen=frozen) | FFMG/myoddweb.piger | [
16,
2,
16,
2,
1456065110
] |
def test_database_undefined(self):
with self.assertRaises(DatabaseUndefined):
validate_database(settings.DATABASES, settings.DEFAULT_DATABASE,
settings.DEBUG) | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def test_load_py_file_with_syntax_error(self):
with file('/tmp/settings_with_syntax_error.py', 'w') as temp_settings:
temp_settings.write('(')
self.assertRaises(InaccessibleSettings,
_load_py_file, 'settings_with_syntax_error', '/tmp') | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def test_load_py_settings_with_inaccessible_settings(self, mock):
self.assertRaises(InaccessibleSettings, load_py_settings) | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def test_load_py_settings_with_settings_d(self, mock_py, mock_listdir):
py_settings = load_py_settings(test_files_dir + '/settings.d/')
self.assertIn('SOCIAL_NETWORK_ENABLED', py_settings)
self.assertTrue(py_settings['SOCIAL_NETWORK_ENABLED'])
self.assertIn('EMAIL_PORT', py_settings)
self.assertEquals(py_settings['EMAIL_PORT'], 25)
self.assertIn('TEST', py_settings)
self.assertEquals(py_settings['TEST'], 'test') | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def test_load_colab_apps_without_plugins_d_directory(self, mock):
colab_apps = load_colab_apps()
self.assertIn('COLAB_APPS', colab_apps)
self.assertEquals(colab_apps['COLAB_APPS'], {}) | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def test_load_colab_apps_with_plugins_d_directory(self, os_getenv):
sys.path.insert(0, os_getenv.return_value)
colab_apps = load_colab_apps()
self.assertIn('gitlab', colab_apps['COLAB_APPS'])
self.assertIn('noosfero', colab_apps['COLAB_APPS'])
sys.path.remove(os_getenv.return_value)
self.assertNotIn(os_getenv.return_value, sys.path) | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def test_load_widgets_settings_without_settings(self, mock):
self.assertIsNone(load_widgets_settings()) | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def test_load_widgets_settings_without_settings_d(self, mock):
self.assertIsNone(load_widgets_settings()) | colab/colab | [
22,
22,
22,
14,
1373661047
] |
def __init__(self, plugin_administrator, config=None, recursive=True, timeout=300):
super().__init__(plugin_administrator, config=config, recursive=recursive, timeout=timeout, plugin_path=__file__) | fkie-cad/FACT_core | [
980,
203,
980,
61,
1505832491
] |
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError) | jeremiah-c-leary/vhdl-style-guide | [
129,
31,
129,
57,
1499106283
] |
def __new__(cls, startpage,
style=defaults["style"],
prefix=defaults["prefix"],
firstpagenum=defaults["firstpagenum"]):
if style not in styles:
raise ValueError("PageLabel style must be one of %s" % cls.styles())
return super().__new__(cls, int(startpage), style, str(prefix), int(firstpagenum)) | lovasoa/pagelabels-py | [
52,
10,
52,
2,
1456746991
] |
def from_pdf(cls, pagenum, opts):
"""Returns a new PageLabel using options from a pdfrw object"""
return cls(pagenum,
style=stylecodes.get(opts.S, defaults["style"]),
prefix=(opts.P and opts.P.decode() or defaults["prefix"]),
firstpagenum=(opts.St or defaults["firstpagenum"])) | lovasoa/pagelabels-py | [
52,
10,
52,
2,
1456746991
] |
def styles():
"""List of the allowed styles"""
return styles.keys() | lovasoa/pagelabels-py | [
52,
10,
52,
2,
1456746991
] |
def verifyCallback(connection, x509, errnum, errdepth, ok):
if not ok:
cslog.debug('invalid server cert: %s' % x509.get_subject())
return False
return True | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def getContext(self):
ctx = ssl.ClientContextFactory.getContext(self)
#TODO: replace VERIFY_NONE with VERIFY_PEER when we have
#a real server with a valid CA signed cert. If that doesn't
#work it'll be possible to use self-signed certs, if they're distributed,
#by placing the cert.pem file and location in the config and uncommenting
#the ctx.load_verify_locations line.
#As it stands this is using non-authenticated certs, meaning MITM exposed.
ctx.set_verify(SSL.VERIFY_NONE, verifyCallback)
#ctx.load_verify_locations("/path/to/cert.pem")
return ctx | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def __init__(self, host, port, json_callback=None, backout_callback=None,
usessl=False):
self.host = host
self.port = int(port)
#Callback fired on receiving response to send()
self.json_callback = json_callback
#Callback fired on receiving any response failure
self.backout_callback = backout_callback
if usessl:
self.proxy = Proxy('https://' + host + ":" + str(port) + "/",
ssl_ctx_factory=AltCtxFactory)
else:
self.proxy = Proxy('http://' + host + ":" + str(port) + "/") | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def error(self, errmsg):
"""error callback implies we must back out at this point.
Note that this includes stateless queries, as any malformed
or non-response must be interpreted as malicious.
"""
self.backout_callback(str(errmsg)) | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def send_poll_unsigned(self, method, callback, *args):
"""Stateless queries outside of a coinswap run use
this query method; no nonce, sessionid or signature needed.
"""
d = self.proxy.callRemote(method, *args)
d.addCallback(callback).addErrback(self.error) | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def __init__(self, wallet, testing_mode=False, carol_class=CoinSwapCarol,
fail_carol_state=None):
self.testing_mode = testing_mode
self.wallet = wallet
self.carol_class = carol_class
self.fail_carol_state = fail_carol_state
self.carols = {}
self.fee_policy = FeePolicy(cs_single().config)
self.update_status()
jsonrpc.JSONRPC.__init__(self) | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def refresh_carols(self):
"""Remove CoinSwapCarol instances that are flagged complete from
the running dict."""
to_remove = []
for k, v in self.carols.iteritems():
if v.completed:
to_remove.append(k)
for x in to_remove:
self.carols.pop(x, None)
cslog.info("Removed session: " + str(x) + " from tracking (finished).") | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def jsonrpc_status(self):
"""This can be polled at any time.
The call to get_balance_by_mixdepth does not involve sync,
so is not resource intensive.
"""
return self.update_status() | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def consume_nonce(self, nonce, sessionid):
if sessionid not in self.carols:
return False
return self.carols[sessionid].consume_nonce(nonce) | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def jsonrpc_coinswap(self, *paramlist):
"""To get round txjsonrpc's rather funky function naming trick,
we use 1 generic json rpc method and then read the real method as a field.
This allows us to handle generic features like signatures and nonces in
this function before deferring actual methods to sub-calls.
All calls use syntax:
sessionid, {noncesig dict}, method, *methodargs
"""
if len(paramlist) < 3:
return (False, "Wrong length of paramlist: " + str(len(paramlist)))
sessionid = paramlist[0]
if sessionid not in self.carols:
return (False, "Unrecognized sessionid: " + str(sessionid))
carol = self.carols[sessionid]
valid, errmsg = self.validate_sig_nonce(carol, paramlist[1:])
if not valid:
return (False, "Invalid message from Alice: " + errmsg)
return carol.get_rpc_response(paramlist[2], paramlist[3:]) | AdamISZ/CoinSwapCS | [
30,
14,
30,
19,
1493059952
] |
def __init__(self, name, *args, **kwargs):
"""
create QcFrame object.
name: name of the frame molecule
"""
# mandatory parameter
self._name = name
self._fragments = OrderedDict()
self._charge = 0
self._state = {} # 状態保持
self._cmds = self._get_default_cmds() # 外部コマンド
self._initialize()
self._prepare_work_dir()
self._load()
# cache data
self._cache = {}
if (len(args) > 0) and isinstance(args[0], QcFrame):
self._copy_constructor(args[0]) | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _copy_constructor(self, rhs):
self._name = rhs._name
self._fragments = copy.deepcopy(rhs._fragments)
self._charge = rhs._charge
self._state = copy.deepcopy(rhs._state)
self._cmds = copy.copy(rhs._cmds) | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _initialize(self, *args, **kwargs):
pass | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _load(self):
path = os.path.join(self.work_dir, "qcframe.mpac")
if os.path.exists(path):
logger.info("load the fragment state: {}".format(path))
state_dat = bridge.load_msgpack(path)
self.set_by_raw_data(state_dat)
else:
logger.debug("not found the state file") | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def get_raw_data(self):
return self.__getstate__() | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def __getstate__(self):
state = {}
state["name"] = self.name
tmp_frgs = []
for k, frg in self.fragments():
tmp_frgs.append((k, frg.get_raw_data()))
state["fragments"] = tmp_frgs
state["charge"] = self.charge
state["state"] = self._state
state["cmds"] = self._cmds
return state | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_pdfparam(self):
"""
pdfparamオブジェクトを返す
"""
pdfparam_path = os.path.abspath(
os.path.join(self.work_dir, self._pdfparam_filename)
)
if "pdfparam" not in self._cache:
if os.path.exists(pdfparam_path):
mpac_data = bridge.load_msgpack(pdfparam_path)
logger.debug("pdfparam({}) is loaded.".format(pdfparam_path))
self._cache["pdfparam"] = pdf.PdfParam(mpac_data)
else:
pdfsim = pdf.PdfSim()
self._cache["pdfparam"] = pdf.get_default_pdfparam()
logger.debug("use default pdfparam.")
else:
logger.debug("pdfparam is cached.")
return self._cache["pdfparam"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def set_db_filename(self, filename):
assert filename is not None
self._db_filename = str(filename)
logger.debug("set_db_filename: {}".format(self._db_filename)) | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def get_pdfarchive(self):
"""
pdfArchiveオブジェクトを返す
"""
logger.debug("get_pdfarchive db_path={}".format(self.db_path))
pdfarc = None
if self._cmds.get("archive", None) == "archive":
pdfarc = pdf.PdfArchive(self.db_path)
else:
pdfarc = pdf.PdfParam_H5(self.db_path)
return pdfarc | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def set_command_alias(self, cmd_alias_dict):
for k, v in cmd_alias_dict.items():
logger.debug("command update: {} -> {}".format(k, v))
self._cmds[k] = v | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_work_dir(self):
return self._work_dir | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_name(self):
return self._name | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _set_basisset(self, pdfparam):
for fragment_name, fragment in self.fragments():
fragment.set_basisset(pdfparam) | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_frame_molecule(self):
"""
モデリングされた分子構造をAtomGroupオブジェクトで返す
"""
if "frame_molecule" not in self._cache:
logger.info("create frame molecule coordinates.")
frame_molecule = bridge.AtomGroup()
for frg_name, frg in self._fragments.items():
logger.info(
"fragment name={name}: atoms={atoms}, elec={elec}, charge={charge}".format(
name=frg_name,
atoms=frg.get_number_of_all_atoms(),
elec=frg.sum_of_atomic_number(),
charge=frg.get_AtomGroup().charge,
)
)
frame_molecule[frg_name] = frg.get_AtomGroup()
self._cache["frame_molecule"] = frame_molecule
logger.info("")
return self._cache["frame_molecule"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_fragments_atom_ids(self):
fragments_atom_ids = []
for fragment_name, fragment in self.fragments():
fragment_atomgroup = fragment.get_AtomGroup()
fragment_atomgroup *= pdf.ANG2AU # angstrom -> a.u.
fragment_atom_list = fragment_atomgroup.get_atom_list()
atom_id_list = []
for atom in fragment_atom_list:
atom_id = int(self.pdfparam.find_atom_index(atom))
if atom_id == -1:
logger.critical("not found atom index: {}".format(str(atom)))
atom_id_list.append(atom_id)
fragments_atom_ids.append(atom_id_list)
return fragments_atom_ids | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _prepare_work_dir(self):
"""
カレントディレクトリ下に作業ディレクトリとなる
nameのディレクトリを作成する。
"""
# assert(len(self.name) > 0)
if len(self.name) == 0:
logger.critical("frame name is not defined.")
raise
self._work_dir = os.path.abspath(os.path.join(os.curdir, self.name))
if not os.path.exists(self.work_dir):
logger.info(
"{header} make work dir: {path}".format(
header=self.header, path=self.work_dir
)
)
os.mkdir(self.work_dir)
else:
logger.debug(
"{header} already exist: {path}".format(
header=self.header, path=self.work_dir
)
) | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def restore_cwd(self):
"""
self.cd_work_dir() 以前のディレクトリに戻す
"""
os.chdir(self._prev_dir)
logger.debug(
"{header} < (prev_dir: {path})".format(
header=self.header, path=self._prev_dir
)
) | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_charge(self):
return int(self._charge) | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def get_number_of_AOs(self):
"""
return the number of atomic orbitals.
"""
num_of_AOs = 0
for frg_name, frg in self.fragments():
num_of_AOs += frg.get_number_of_AOs()
return num_of_AOs | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_state_finished_guess_density(self):
self._state.setdefault("is_finished_guess_density", False)
return self._state["is_finished_guess_density"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_state_finished_guess_QCLO(self):
self._state.setdefault("is_finished_guess_QCLO", False)
return self._state["is_finished_guess_QCLO"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_state_finished_prescf(self):
self._state.setdefault("is_finished_prescf", False)
return self._state["is_finished_prescf"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_state_finished_scf(self):
self._state.setdefault("is_finished_scf", False)
return self._state["is_finished_scf"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_state_finished_force(self):
self._state.setdefault("is_finished_force", False)
return self._state["is_finished_force"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
def _get_state_finished_pickup_density_matrix(self):
self._state.setdefault("is_finished_pickup_density_matrix", False)
return self._state["is_finished_pickup_density_matrix"] | ProteinDF/QCLObot | [
4,
1,
4,
5,
1408759315
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.