id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
4,000
BetterWorks/django-anonymizer
anonymizer/base.py
DjangoFaker.lorem
def lorem(self, field=None, val=None): """ Returns lorem ipsum text. If val is provided, the lorem ipsum text will be the same length as the original text, and with the same pattern of line breaks. """ if val == '': return '' if val is not None: def generate(length): # Get lorem ipsum of a specific length. collect = "" while len(collect) < length: collect += ' %s' % self.faker.sentence() collect = collect[:length] return collect # We want to match the pattern of the text - linebreaks # in the same places. def source(): parts = val.split("\n") for i, p in enumerate(parts): # Replace each bit with lorem ipsum of the same length parts[i] = generate(len(p)) return "\n".join(parts) else: def source(): return ' '.join(self.faker.sentences()) return self.get_allowed_value(source, field)
python
def lorem(self, field=None, val=None): if val == '': return '' if val is not None: def generate(length): # Get lorem ipsum of a specific length. collect = "" while len(collect) < length: collect += ' %s' % self.faker.sentence() collect = collect[:length] return collect # We want to match the pattern of the text - linebreaks # in the same places. def source(): parts = val.split("\n") for i, p in enumerate(parts): # Replace each bit with lorem ipsum of the same length parts[i] = generate(len(p)) return "\n".join(parts) else: def source(): return ' '.join(self.faker.sentences()) return self.get_allowed_value(source, field)
[ "def", "lorem", "(", "self", ",", "field", "=", "None", ",", "val", "=", "None", ")", ":", "if", "val", "==", "''", ":", "return", "''", "if", "val", "is", "not", "None", ":", "def", "generate", "(", "length", ")", ":", "# Get lorem ipsum of a specific length.", "collect", "=", "\"\"", "while", "len", "(", "collect", ")", "<", "length", ":", "collect", "+=", "' %s'", "%", "self", ".", "faker", ".", "sentence", "(", ")", "collect", "=", "collect", "[", ":", "length", "]", "return", "collect", "# We want to match the pattern of the text - linebreaks", "# in the same places.", "def", "source", "(", ")", ":", "parts", "=", "val", ".", "split", "(", "\"\\n\"", ")", "for", "i", ",", "p", "in", "enumerate", "(", "parts", ")", ":", "# Replace each bit with lorem ipsum of the same length", "parts", "[", "i", "]", "=", "generate", "(", "len", "(", "p", ")", ")", "return", "\"\\n\"", ".", "join", "(", "parts", ")", "else", ":", "def", "source", "(", ")", ":", "return", "' '", ".", "join", "(", "self", ".", "faker", ".", "sentences", "(", ")", ")", "return", "self", ".", "get_allowed_value", "(", "source", ",", "field", ")" ]
Returns lorem ipsum text. If val is provided, the lorem ipsum text will be the same length as the original text, and with the same pattern of line breaks.
[ "Returns", "lorem", "ipsum", "text", ".", "If", "val", "is", "provided", "the", "lorem", "ipsum", "text", "will", "be", "the", "same", "length", "as", "the", "original", "text", "and", "with", "the", "same", "pattern", "of", "line", "breaks", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L152-L181
4,001
BetterWorks/django-anonymizer
anonymizer/base.py
DjangoFaker.unique_lorem
def unique_lorem(self, field=None, val=None): """ Returns lorem ipsum text guaranteed to be unique. First uses lorem function then adds a unique integer suffix. """ lorem_text = self.lorem(field, val) max_length = getattr(field, 'max_length', None) suffix_str = str(self.unique_suffixes[field]) unique_text = lorem_text + suffix_str if max_length is not None: # take the last max_length chars unique_text = unique_text[-max_length:] self.unique_suffixes[field] += 1 return unique_text
python
def unique_lorem(self, field=None, val=None): lorem_text = self.lorem(field, val) max_length = getattr(field, 'max_length', None) suffix_str = str(self.unique_suffixes[field]) unique_text = lorem_text + suffix_str if max_length is not None: # take the last max_length chars unique_text = unique_text[-max_length:] self.unique_suffixes[field] += 1 return unique_text
[ "def", "unique_lorem", "(", "self", ",", "field", "=", "None", ",", "val", "=", "None", ")", ":", "lorem_text", "=", "self", ".", "lorem", "(", "field", ",", "val", ")", "max_length", "=", "getattr", "(", "field", ",", "'max_length'", ",", "None", ")", "suffix_str", "=", "str", "(", "self", ".", "unique_suffixes", "[", "field", "]", ")", "unique_text", "=", "lorem_text", "+", "suffix_str", "if", "max_length", "is", "not", "None", ":", "# take the last max_length chars", "unique_text", "=", "unique_text", "[", "-", "max_length", ":", "]", "self", ".", "unique_suffixes", "[", "field", "]", "+=", "1", "return", "unique_text" ]
Returns lorem ipsum text guaranteed to be unique. First uses lorem function then adds a unique integer suffix.
[ "Returns", "lorem", "ipsum", "text", "guaranteed", "to", "be", "unique", ".", "First", "uses", "lorem", "function", "then", "adds", "a", "unique", "integer", "suffix", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L183-L197
4,002
BetterWorks/django-anonymizer
anonymizer/base.py
Anonymizer.alter_object
def alter_object(self, obj): """ Alters all the attributes in an individual object. If it returns False, the object will not be saved """ for attname, field, replacer in self.replacers: currentval = getattr(obj, attname) replacement = replacer(self, obj, field, currentval) setattr(obj, attname, replacement)
python
def alter_object(self, obj): for attname, field, replacer in self.replacers: currentval = getattr(obj, attname) replacement = replacer(self, obj, field, currentval) setattr(obj, attname, replacement)
[ "def", "alter_object", "(", "self", ",", "obj", ")", ":", "for", "attname", ",", "field", ",", "replacer", "in", "self", ".", "replacers", ":", "currentval", "=", "getattr", "(", "obj", ",", "attname", ")", "replacement", "=", "replacer", "(", "self", ",", "obj", ",", "field", ",", "currentval", ")", "setattr", "(", "obj", ",", "attname", ",", "replacement", ")" ]
Alters all the attributes in an individual object. If it returns False, the object will not be saved
[ "Alters", "all", "the", "attributes", "in", "an", "individual", "object", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L289-L298
4,003
BetterWorks/django-anonymizer
anonymizer/replacers.py
uuid
def uuid(anon, obj, field, val): """ Returns a random uuid string """ return anon.faker.uuid(field=field)
python
def uuid(anon, obj, field, val): return anon.faker.uuid(field=field)
[ "def", "uuid", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "uuid", "(", "field", "=", "field", ")" ]
Returns a random uuid string
[ "Returns", "a", "random", "uuid", "string" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L4-L8
4,004
BetterWorks/django-anonymizer
anonymizer/replacers.py
varchar
def varchar(anon, obj, field, val): """ Returns random data for a varchar field. """ return anon.faker.varchar(field=field)
python
def varchar(anon, obj, field, val): return anon.faker.varchar(field=field)
[ "def", "varchar", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "varchar", "(", "field", "=", "field", ")" ]
Returns random data for a varchar field.
[ "Returns", "random", "data", "for", "a", "varchar", "field", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L11-L15
4,005
BetterWorks/django-anonymizer
anonymizer/replacers.py
datetime
def datetime(anon, obj, field, val): """ Returns a random datetime """ return anon.faker.datetime(field=field)
python
def datetime(anon, obj, field, val): return anon.faker.datetime(field=field)
[ "def", "datetime", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "datetime", "(", "field", "=", "field", ")" ]
Returns a random datetime
[ "Returns", "a", "random", "datetime" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L53-L57
4,006
BetterWorks/django-anonymizer
anonymizer/replacers.py
date
def date(anon, obj, field, val): """ Returns a random date """ return anon.faker.date(field=field)
python
def date(anon, obj, field, val): return anon.faker.date(field=field)
[ "def", "date", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "date", "(", "field", "=", "field", ")" ]
Returns a random date
[ "Returns", "a", "random", "date" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L60-L64
4,007
BetterWorks/django-anonymizer
anonymizer/replacers.py
decimal
def decimal(anon, obj, field, val): """ Returns a random decimal """ return anon.faker.decimal(field=field)
python
def decimal(anon, obj, field, val): return anon.faker.decimal(field=field)
[ "def", "decimal", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "decimal", "(", "field", "=", "field", ")" ]
Returns a random decimal
[ "Returns", "a", "random", "decimal" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L67-L71
4,008
BetterWorks/django-anonymizer
anonymizer/replacers.py
country
def country(anon, obj, field, val): """ Returns a randomly selected country. """ return anon.faker.country(field=field)
python
def country(anon, obj, field, val): return anon.faker.country(field=field)
[ "def", "country", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "country", "(", "field", "=", "field", ")" ]
Returns a randomly selected country.
[ "Returns", "a", "randomly", "selected", "country", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L81-L85
4,009
BetterWorks/django-anonymizer
anonymizer/replacers.py
username
def username(anon, obj, field, val): """ Generates a random username """ return anon.faker.user_name(field=field)
python
def username(anon, obj, field, val): return anon.faker.user_name(field=field)
[ "def", "username", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "user_name", "(", "field", "=", "field", ")" ]
Generates a random username
[ "Generates", "a", "random", "username" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L88-L92
4,010
BetterWorks/django-anonymizer
anonymizer/replacers.py
first_name
def first_name(anon, obj, field, val): """ Returns a random first name """ return anon.faker.first_name(field=field)
python
def first_name(anon, obj, field, val): return anon.faker.first_name(field=field)
[ "def", "first_name", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "first_name", "(", "field", "=", "field", ")" ]
Returns a random first name
[ "Returns", "a", "random", "first", "name" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L95-L99
4,011
BetterWorks/django-anonymizer
anonymizer/replacers.py
last_name
def last_name(anon, obj, field, val): """ Returns a random second name """ return anon.faker.last_name(field=field)
python
def last_name(anon, obj, field, val): return anon.faker.last_name(field=field)
[ "def", "last_name", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "last_name", "(", "field", "=", "field", ")" ]
Returns a random second name
[ "Returns", "a", "random", "second", "name" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L102-L106
4,012
BetterWorks/django-anonymizer
anonymizer/replacers.py
email
def email(anon, obj, field, val): """ Generates a random email address. """ return anon.faker.email(field=field)
python
def email(anon, obj, field, val): return anon.faker.email(field=field)
[ "def", "email", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "email", "(", "field", "=", "field", ")" ]
Generates a random email address.
[ "Generates", "a", "random", "email", "address", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L116-L120
4,013
BetterWorks/django-anonymizer
anonymizer/replacers.py
similar_email
def similar_email(anon, obj, field, val): """ Generate a random email address using the same domain. """ return val if 'betterworks.com' in val else '@'.join([anon.faker.user_name(field=field), val.split('@')[-1]])
python
def similar_email(anon, obj, field, val): return val if 'betterworks.com' in val else '@'.join([anon.faker.user_name(field=field), val.split('@')[-1]])
[ "def", "similar_email", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "val", "if", "'betterworks.com'", "in", "val", "else", "'@'", ".", "join", "(", "[", "anon", ".", "faker", ".", "user_name", "(", "field", "=", "field", ")", ",", "val", ".", "split", "(", "'@'", ")", "[", "-", "1", "]", "]", ")" ]
Generate a random email address using the same domain.
[ "Generate", "a", "random", "email", "address", "using", "the", "same", "domain", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L123-L127
4,014
BetterWorks/django-anonymizer
anonymizer/replacers.py
full_address
def full_address(anon, obj, field, val): """ Generates a random full address, using newline characters between the lines. Resembles a US address """ return anon.faker.address(field=field)
python
def full_address(anon, obj, field, val): return anon.faker.address(field=field)
[ "def", "full_address", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "address", "(", "field", "=", "field", ")" ]
Generates a random full address, using newline characters between the lines. Resembles a US address
[ "Generates", "a", "random", "full", "address", "using", "newline", "characters", "between", "the", "lines", ".", "Resembles", "a", "US", "address" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L130-L135
4,015
BetterWorks/django-anonymizer
anonymizer/replacers.py
phonenumber
def phonenumber(anon, obj, field, val): """ Generates a random US-style phone number """ return anon.faker.phone_number(field=field)
python
def phonenumber(anon, obj, field, val): return anon.faker.phone_number(field=field)
[ "def", "phonenumber", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "phone_number", "(", "field", "=", "field", ")" ]
Generates a random US-style phone number
[ "Generates", "a", "random", "US", "-", "style", "phone", "number" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L138-L142
4,016
BetterWorks/django-anonymizer
anonymizer/replacers.py
street_address
def street_address(anon, obj, field, val): """ Generates a random street address - the first line of a full address """ return anon.faker.street_address(field=field)
python
def street_address(anon, obj, field, val): return anon.faker.street_address(field=field)
[ "def", "street_address", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "street_address", "(", "field", "=", "field", ")" ]
Generates a random street address - the first line of a full address
[ "Generates", "a", "random", "street", "address", "-", "the", "first", "line", "of", "a", "full", "address" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L145-L149
4,017
BetterWorks/django-anonymizer
anonymizer/replacers.py
state
def state(anon, obj, field, val): """ Returns a randomly selected US state code """ return anon.faker.state(field=field)
python
def state(anon, obj, field, val): return anon.faker.state(field=field)
[ "def", "state", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "state", "(", "field", "=", "field", ")" ]
Returns a randomly selected US state code
[ "Returns", "a", "randomly", "selected", "US", "state", "code" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L159-L163
4,018
BetterWorks/django-anonymizer
anonymizer/replacers.py
company
def company(anon, obj, field, val): """ Generates a random company name """ return anon.faker.company(field=field)
python
def company(anon, obj, field, val): return anon.faker.company(field=field)
[ "def", "company", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "company", "(", "field", "=", "field", ")" ]
Generates a random company name
[ "Generates", "a", "random", "company", "name" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L173-L177
4,019
BetterWorks/django-anonymizer
anonymizer/replacers.py
lorem
def lorem(anon, obj, field, val): """ Generates a paragraph of lorem ipsum text """ return ' '.join(anon.faker.sentences(field=field))
python
def lorem(anon, obj, field, val): return ' '.join(anon.faker.sentences(field=field))
[ "def", "lorem", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "' '", ".", "join", "(", "anon", ".", "faker", ".", "sentences", "(", "field", "=", "field", ")", ")" ]
Generates a paragraph of lorem ipsum text
[ "Generates", "a", "paragraph", "of", "lorem", "ipsum", "text" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L180-L184
4,020
BetterWorks/django-anonymizer
anonymizer/replacers.py
unique_lorem
def unique_lorem(anon, obj, field, val): """ Generates a unique paragraph of lorem ipsum text """ return anon.faker.unique_lorem(field=field)
python
def unique_lorem(anon, obj, field, val): return anon.faker.unique_lorem(field=field)
[ "def", "unique_lorem", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "unique_lorem", "(", "field", "=", "field", ")" ]
Generates a unique paragraph of lorem ipsum text
[ "Generates", "a", "unique", "paragraph", "of", "lorem", "ipsum", "text" ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L187-L191
4,021
BetterWorks/django-anonymizer
anonymizer/replacers.py
choice
def choice(anon, obj, field, val): """ Randomly chooses one of the choices set on the field. """ return anon.faker.choice(field=field)
python
def choice(anon, obj, field, val): return anon.faker.choice(field=field)
[ "def", "choice", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "choice", "(", "field", "=", "field", ")" ]
Randomly chooses one of the choices set on the field.
[ "Randomly", "chooses", "one", "of", "the", "choices", "set", "on", "the", "field", "." ]
2d25bb6e8b5e4230c58031c4b6d10cc536669b3e
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L217-L221
4,022
planetarypy/pvl
pvl/__init__.py
load
def load(stream, cls=PVLDecoder, strict=True, **kwargs): """Deserialize ``stream`` as a pvl module. :param stream: a ``.read()``-supporting file-like object containing a module. If ``stream`` is a string it will be treated as a filename :param cls: the decoder class used to deserialize the pvl module. You may use the default ``PVLDecoder`` class or provide a custom sublcass. :param **kwargs: the keyword arguments to pass to the decoder class. """ decoder = __create_decoder(cls, strict, **kwargs) if isinstance(stream, six.string_types): with open(stream, 'rb') as fp: return decoder.decode(fp) return decoder.decode(stream)
python
def load(stream, cls=PVLDecoder, strict=True, **kwargs): decoder = __create_decoder(cls, strict, **kwargs) if isinstance(stream, six.string_types): with open(stream, 'rb') as fp: return decoder.decode(fp) return decoder.decode(stream)
[ "def", "load", "(", "stream", ",", "cls", "=", "PVLDecoder", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "decoder", "=", "__create_decoder", "(", "cls", ",", "strict", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "stream", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "stream", ",", "'rb'", ")", "as", "fp", ":", "return", "decoder", ".", "decode", "(", "fp", ")", "return", "decoder", ".", "decode", "(", "stream", ")" ]
Deserialize ``stream`` as a pvl module. :param stream: a ``.read()``-supporting file-like object containing a module. If ``stream`` is a string it will be treated as a filename :param cls: the decoder class used to deserialize the pvl module. You may use the default ``PVLDecoder`` class or provide a custom sublcass. :param **kwargs: the keyword arguments to pass to the decoder class.
[ "Deserialize", "stream", "as", "a", "pvl", "module", "." ]
ed92b284c4208439b033d28c9c176534c0faac0e
https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L82-L97
4,023
planetarypy/pvl
pvl/__init__.py
loads
def loads(data, cls=PVLDecoder, strict=True, **kwargs): """Deserialize ``data`` as a pvl module. :param data: a pvl module as a byte or unicode string :param cls: the decoder class used to deserialize the pvl module. You may use the default ``PVLDecoder`` class or provide a custom sublcass. :param **kwargs: the keyword arguments to pass to the decoder class. """ decoder = __create_decoder(cls, strict, **kwargs) if not isinstance(data, bytes): data = data.encode('utf-8') return decoder.decode(data)
python
def loads(data, cls=PVLDecoder, strict=True, **kwargs): decoder = __create_decoder(cls, strict, **kwargs) if not isinstance(data, bytes): data = data.encode('utf-8') return decoder.decode(data)
[ "def", "loads", "(", "data", ",", "cls", "=", "PVLDecoder", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "decoder", "=", "__create_decoder", "(", "cls", ",", "strict", ",", "*", "*", "kwargs", ")", "if", "not", "isinstance", "(", "data", ",", "bytes", ")", ":", "data", "=", "data", ".", "encode", "(", "'utf-8'", ")", "return", "decoder", ".", "decode", "(", "data", ")" ]
Deserialize ``data`` as a pvl module. :param data: a pvl module as a byte or unicode string :param cls: the decoder class used to deserialize the pvl module. You may use the default ``PVLDecoder`` class or provide a custom sublcass. :param **kwargs: the keyword arguments to pass to the decoder class.
[ "Deserialize", "data", "as", "a", "pvl", "module", "." ]
ed92b284c4208439b033d28c9c176534c0faac0e
https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L100-L113
4,024
planetarypy/pvl
pvl/__init__.py
dump
def dump(module, stream, cls=PVLEncoder, **kwargs): """Serialize ``module`` as a pvl module to the provided ``stream``. :param module: a ```PVLModule``` or ```dict``` like object to serialize :param stream: a ``.write()``-supporting file-like object to serialize the module to. If ``stream`` is a string it will be treated as a filename :param cls: the encoder class used to serialize the pvl module. You may use the default ``PVLEncoder`` class or provided encoder formats such as the ```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may also provided a custom sublcass of ```PVLEncoder``` :param **kwargs: the keyword arguments to pass to the encoder class. """ if isinstance(stream, six.string_types): with open(stream, 'wb') as fp: return cls(**kwargs).encode(module, fp) cls(**kwargs).encode(module, stream)
python
def dump(module, stream, cls=PVLEncoder, **kwargs): if isinstance(stream, six.string_types): with open(stream, 'wb') as fp: return cls(**kwargs).encode(module, fp) cls(**kwargs).encode(module, stream)
[ "def", "dump", "(", "module", ",", "stream", ",", "cls", "=", "PVLEncoder", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "stream", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "stream", ",", "'wb'", ")", "as", "fp", ":", "return", "cls", "(", "*", "*", "kwargs", ")", ".", "encode", "(", "module", ",", "fp", ")", "cls", "(", "*", "*", "kwargs", ")", ".", "encode", "(", "module", ",", "stream", ")" ]
Serialize ``module`` as a pvl module to the provided ``stream``. :param module: a ```PVLModule``` or ```dict``` like object to serialize :param stream: a ``.write()``-supporting file-like object to serialize the module to. If ``stream`` is a string it will be treated as a filename :param cls: the encoder class used to serialize the pvl module. You may use the default ``PVLEncoder`` class or provided encoder formats such as the ```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may also provided a custom sublcass of ```PVLEncoder``` :param **kwargs: the keyword arguments to pass to the encoder class.
[ "Serialize", "module", "as", "a", "pvl", "module", "to", "the", "provided", "stream", "." ]
ed92b284c4208439b033d28c9c176534c0faac0e
https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L116-L134
4,025
planetarypy/pvl
pvl/__init__.py
dumps
def dumps(module, cls=PVLEncoder, **kwargs): """Serialize ``module`` as a pvl module formated byte string. :param module: a ```PVLModule``` or ```dict``` like object to serialize :param cls: the encoder class used to serialize the pvl module. You may use the default ``PVLEncoder`` class or provided encoder formats such as the ```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may also provided a custom sublcass of ```PVLEncoder``` :param **kwargs: the keyword arguments to pass to the encoder class. :returns: a byte string encoding of the pvl module """ stream = io.BytesIO() cls(**kwargs).encode(module, stream) return stream.getvalue()
python
def dumps(module, cls=PVLEncoder, **kwargs): stream = io.BytesIO() cls(**kwargs).encode(module, stream) return stream.getvalue()
[ "def", "dumps", "(", "module", ",", "cls", "=", "PVLEncoder", ",", "*", "*", "kwargs", ")", ":", "stream", "=", "io", ".", "BytesIO", "(", ")", "cls", "(", "*", "*", "kwargs", ")", ".", "encode", "(", "module", ",", "stream", ")", "return", "stream", ".", "getvalue", "(", ")" ]
Serialize ``module`` as a pvl module formated byte string. :param module: a ```PVLModule``` or ```dict``` like object to serialize :param cls: the encoder class used to serialize the pvl module. You may use the default ``PVLEncoder`` class or provided encoder formats such as the ```IsisCubeLabelEncoder``` and ```PDSLabelEncoder``` classes. You may also provided a custom sublcass of ```PVLEncoder``` :param **kwargs: the keyword arguments to pass to the encoder class. :returns: a byte string encoding of the pvl module
[ "Serialize", "module", "as", "a", "pvl", "module", "formated", "byte", "string", "." ]
ed92b284c4208439b033d28c9c176534c0faac0e
https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/__init__.py#L137-L153
4,026
pycampers/zproc
zproc/state/server.py
StateServer.run_dict_method
def run_dict_method(self, request): """Execute a method on the state ``dict`` and reply with the result.""" state_method_name, args, kwargs = ( request[Msgs.info], request[Msgs.args], request[Msgs.kwargs], ) # print(method_name, args, kwargs) with self.mutate_safely(): self.reply(getattr(self.state, state_method_name)(*args, **kwargs))
python
def run_dict_method(self, request): state_method_name, args, kwargs = ( request[Msgs.info], request[Msgs.args], request[Msgs.kwargs], ) # print(method_name, args, kwargs) with self.mutate_safely(): self.reply(getattr(self.state, state_method_name)(*args, **kwargs))
[ "def", "run_dict_method", "(", "self", ",", "request", ")", ":", "state_method_name", ",", "args", ",", "kwargs", "=", "(", "request", "[", "Msgs", ".", "info", "]", ",", "request", "[", "Msgs", ".", "args", "]", ",", "request", "[", "Msgs", ".", "kwargs", "]", ",", ")", "# print(method_name, args, kwargs)", "with", "self", ".", "mutate_safely", "(", ")", ":", "self", ".", "reply", "(", "getattr", "(", "self", ".", "state", ",", "state_method_name", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
Execute a method on the state ``dict`` and reply with the result.
[ "Execute", "a", "method", "on", "the", "state", "dict", "and", "reply", "with", "the", "result", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/server.py#L72-L81
4,027
pycampers/zproc
zproc/state/server.py
StateServer.run_fn_atomically
def run_fn_atomically(self, request): """Execute a function, atomically and reply with the result.""" fn = serializer.loads_fn(request[Msgs.info]) args, kwargs = request[Msgs.args], request[Msgs.kwargs] with self.mutate_safely(): self.reply(fn(self.state, *args, **kwargs))
python
def run_fn_atomically(self, request): fn = serializer.loads_fn(request[Msgs.info]) args, kwargs = request[Msgs.args], request[Msgs.kwargs] with self.mutate_safely(): self.reply(fn(self.state, *args, **kwargs))
[ "def", "run_fn_atomically", "(", "self", ",", "request", ")", ":", "fn", "=", "serializer", ".", "loads_fn", "(", "request", "[", "Msgs", ".", "info", "]", ")", "args", ",", "kwargs", "=", "request", "[", "Msgs", ".", "args", "]", ",", "request", "[", "Msgs", ".", "kwargs", "]", "with", "self", ".", "mutate_safely", "(", ")", ":", "self", ".", "reply", "(", "fn", "(", "self", ".", "state", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
Execute a function, atomically and reply with the result.
[ "Execute", "a", "function", "atomically", "and", "reply", "with", "the", "result", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/server.py#L83-L88
4,028
pycampers/zproc
zproc/util.py
clean_process_tree
def clean_process_tree(*signal_handler_args): """Stop all Processes in the current Process tree, recursively.""" parent = psutil.Process() procs = parent.children(recursive=True) if procs: print(f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...") for p in procs: with suppress(psutil.NoSuchProcess): p.terminate() _, alive = psutil.wait_procs(procs, timeout=0.5) # 0.5 seems to work for p in alive: with suppress(psutil.NoSuchProcess): p.kill() try: signum = signal_handler_args[0] except IndexError: pass else: os._exit(signum)
python
def clean_process_tree(*signal_handler_args): parent = psutil.Process() procs = parent.children(recursive=True) if procs: print(f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...") for p in procs: with suppress(psutil.NoSuchProcess): p.terminate() _, alive = psutil.wait_procs(procs, timeout=0.5) # 0.5 seems to work for p in alive: with suppress(psutil.NoSuchProcess): p.kill() try: signum = signal_handler_args[0] except IndexError: pass else: os._exit(signum)
[ "def", "clean_process_tree", "(", "*", "signal_handler_args", ")", ":", "parent", "=", "psutil", ".", "Process", "(", ")", "procs", "=", "parent", ".", "children", "(", "recursive", "=", "True", ")", "if", "procs", ":", "print", "(", "f\"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...\"", ")", "for", "p", "in", "procs", ":", "with", "suppress", "(", "psutil", ".", "NoSuchProcess", ")", ":", "p", ".", "terminate", "(", ")", "_", ",", "alive", "=", "psutil", ".", "wait_procs", "(", "procs", ",", "timeout", "=", "0.5", ")", "# 0.5 seems to work", "for", "p", "in", "alive", ":", "with", "suppress", "(", "psutil", ".", "NoSuchProcess", ")", ":", "p", ".", "kill", "(", ")", "try", ":", "signum", "=", "signal_handler_args", "[", "0", "]", "except", "IndexError", ":", "pass", "else", ":", "os", ".", "_exit", "(", "signum", ")" ]
Stop all Processes in the current Process tree, recursively.
[ "Stop", "all", "Processes", "in", "the", "current", "Process", "tree", "recursively", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/util.py#L109-L129
4,029
pycampers/zproc
zproc/util.py
strict_request_reply
def strict_request_reply(msg, send: Callable, recv: Callable): """ Ensures a strict req-reply loop, so that clients dont't receive out-of-order messages, if an exception occurs between request-reply. """ try: send(msg) except Exception: raise try: return recv() except Exception: with suppress(zmq.error.Again): recv() raise
python
def strict_request_reply(msg, send: Callable, recv: Callable): try: send(msg) except Exception: raise try: return recv() except Exception: with suppress(zmq.error.Again): recv() raise
[ "def", "strict_request_reply", "(", "msg", ",", "send", ":", "Callable", ",", "recv", ":", "Callable", ")", ":", "try", ":", "send", "(", "msg", ")", "except", "Exception", ":", "raise", "try", ":", "return", "recv", "(", ")", "except", "Exception", ":", "with", "suppress", "(", "zmq", ".", "error", ".", "Again", ")", ":", "recv", "(", ")", "raise" ]
Ensures a strict req-reply loop, so that clients dont't receive out-of-order messages, if an exception occurs between request-reply.
[ "Ensures", "a", "strict", "req", "-", "reply", "loop", "so", "that", "clients", "dont", "t", "receive", "out", "-", "of", "-", "order", "messages", "if", "an", "exception", "occurs", "between", "request", "-", "reply", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/util.py#L220-L235
4,030
pycampers/zproc
zproc/server/tools.py
start_server
def start_server( server_address: str = None, *, backend: Callable = multiprocessing.Process ) -> Tuple[multiprocessing.Process, str]: """ Start a new zproc server. :param server_address: .. include:: /api/snippets/server_address.rst :param backend: .. include:: /api/snippets/backend.rst :return: ` A `tuple``, containing a :py:class:`multiprocessing.Process` object for server and the server address. """ recv_conn, send_conn = multiprocessing.Pipe() server_process = backend(target=main, args=[server_address, send_conn]) server_process.start() try: with recv_conn: server_meta: ServerMeta = serializer.loads(recv_conn.recv_bytes()) except zmq.ZMQError as e: if e.errno == 98: raise ConnectionError( "Encountered - %s. Perhaps the server is already running?" % repr(e) ) if e.errno == 22: raise ValueError( "Encountered - %s. `server_address` must be a string containing a valid endpoint." % repr(e) ) raise return server_process, server_meta.state_router
python
def start_server( server_address: str = None, *, backend: Callable = multiprocessing.Process ) -> Tuple[multiprocessing.Process, str]: recv_conn, send_conn = multiprocessing.Pipe() server_process = backend(target=main, args=[server_address, send_conn]) server_process.start() try: with recv_conn: server_meta: ServerMeta = serializer.loads(recv_conn.recv_bytes()) except zmq.ZMQError as e: if e.errno == 98: raise ConnectionError( "Encountered - %s. Perhaps the server is already running?" % repr(e) ) if e.errno == 22: raise ValueError( "Encountered - %s. `server_address` must be a string containing a valid endpoint." % repr(e) ) raise return server_process, server_meta.state_router
[ "def", "start_server", "(", "server_address", ":", "str", "=", "None", ",", "*", ",", "backend", ":", "Callable", "=", "multiprocessing", ".", "Process", ")", "->", "Tuple", "[", "multiprocessing", ".", "Process", ",", "str", "]", ":", "recv_conn", ",", "send_conn", "=", "multiprocessing", ".", "Pipe", "(", ")", "server_process", "=", "backend", "(", "target", "=", "main", ",", "args", "=", "[", "server_address", ",", "send_conn", "]", ")", "server_process", ".", "start", "(", ")", "try", ":", "with", "recv_conn", ":", "server_meta", ":", "ServerMeta", "=", "serializer", ".", "loads", "(", "recv_conn", ".", "recv_bytes", "(", ")", ")", "except", "zmq", ".", "ZMQError", "as", "e", ":", "if", "e", ".", "errno", "==", "98", ":", "raise", "ConnectionError", "(", "\"Encountered - %s. Perhaps the server is already running?\"", "%", "repr", "(", "e", ")", ")", "if", "e", ".", "errno", "==", "22", ":", "raise", "ValueError", "(", "\"Encountered - %s. `server_address` must be a string containing a valid endpoint.\"", "%", "repr", "(", "e", ")", ")", "raise", "return", "server_process", ",", "server_meta", ".", "state_router" ]
Start a new zproc server. :param server_address: .. include:: /api/snippets/server_address.rst :param backend: .. include:: /api/snippets/backend.rst :return: ` A `tuple``, containing a :py:class:`multiprocessing.Process` object for server and the server address.
[ "Start", "a", "new", "zproc", "server", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/server/tools.py#L14-L49
4,031
pycampers/zproc
zproc/server/tools.py
ping
def ping( server_address: str, *, timeout: float = None, payload: Union[bytes] = None ) -> int: """ Ping the zproc server. This can be used to easily detect if a server is alive and running, with the aid of a suitable ``timeout``. :param server_address: .. include:: /api/snippets/server_address.rst :param timeout: The timeout in seconds. If this is set to ``None``, then it will block forever, until the zproc server replies. For all other values, it will wait for a reply, for that amount of time before returning with a :py:class:`TimeoutError`. By default it is set to ``None``. :param payload: payload that will be sent to the server. If it is set to None, then ``os.urandom(56)`` (56 random bytes) will be used. (No real reason for the ``56`` magic number.) :return: The zproc server's **pid**. """ if payload is None: payload = os.urandom(56) with util.create_zmq_ctx() as zmq_ctx: with zmq_ctx.socket(zmq.DEALER) as dealer_sock: dealer_sock.connect(server_address) if timeout is not None: dealer_sock.setsockopt(zmq.RCVTIMEO, int(timeout * 1000)) dealer_sock.send( serializer.dumps( {Msgs.cmd: Cmds.ping, Msgs.info: payload} ) ) try: recv_payload, pid = serializer.loads(dealer_sock.recv()) except zmq.error.Again: raise TimeoutError( "Timed-out waiting while for the ZProc server to respond." ) assert ( recv_payload == payload ), "Payload doesn't match! The server connection may be compromised, or unstable." return pid
python
def ping( server_address: str, *, timeout: float = None, payload: Union[bytes] = None ) -> int: if payload is None: payload = os.urandom(56) with util.create_zmq_ctx() as zmq_ctx: with zmq_ctx.socket(zmq.DEALER) as dealer_sock: dealer_sock.connect(server_address) if timeout is not None: dealer_sock.setsockopt(zmq.RCVTIMEO, int(timeout * 1000)) dealer_sock.send( serializer.dumps( {Msgs.cmd: Cmds.ping, Msgs.info: payload} ) ) try: recv_payload, pid = serializer.loads(dealer_sock.recv()) except zmq.error.Again: raise TimeoutError( "Timed-out waiting while for the ZProc server to respond." ) assert ( recv_payload == payload ), "Payload doesn't match! The server connection may be compromised, or unstable." return pid
[ "def", "ping", "(", "server_address", ":", "str", ",", "*", ",", "timeout", ":", "float", "=", "None", ",", "payload", ":", "Union", "[", "bytes", "]", "=", "None", ")", "->", "int", ":", "if", "payload", "is", "None", ":", "payload", "=", "os", ".", "urandom", "(", "56", ")", "with", "util", ".", "create_zmq_ctx", "(", ")", "as", "zmq_ctx", ":", "with", "zmq_ctx", ".", "socket", "(", "zmq", ".", "DEALER", ")", "as", "dealer_sock", ":", "dealer_sock", ".", "connect", "(", "server_address", ")", "if", "timeout", "is", "not", "None", ":", "dealer_sock", ".", "setsockopt", "(", "zmq", ".", "RCVTIMEO", ",", "int", "(", "timeout", "*", "1000", ")", ")", "dealer_sock", ".", "send", "(", "serializer", ".", "dumps", "(", "{", "Msgs", ".", "cmd", ":", "Cmds", ".", "ping", ",", "Msgs", ".", "info", ":", "payload", "}", ")", ")", "try", ":", "recv_payload", ",", "pid", "=", "serializer", ".", "loads", "(", "dealer_sock", ".", "recv", "(", ")", ")", "except", "zmq", ".", "error", ".", "Again", ":", "raise", "TimeoutError", "(", "\"Timed-out waiting while for the ZProc server to respond.\"", ")", "assert", "(", "recv_payload", "==", "payload", ")", ",", "\"Payload doesn't match! The server connection may be compromised, or unstable.\"", "return", "pid" ]
Ping the zproc server. This can be used to easily detect if a server is alive and running, with the aid of a suitable ``timeout``. :param server_address: .. include:: /api/snippets/server_address.rst :param timeout: The timeout in seconds. If this is set to ``None``, then it will block forever, until the zproc server replies. For all other values, it will wait for a reply, for that amount of time before returning with a :py:class:`TimeoutError`. By default it is set to ``None``. :param payload: payload that will be sent to the server. If it is set to None, then ``os.urandom(56)`` (56 random bytes) will be used. (No real reason for the ``56`` magic number.) :return: The zproc server's **pid**.
[ "Ping", "the", "zproc", "server", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/server/tools.py#L52-L107
4,032
pycampers/zproc
examples/cookie_eater.py
cookie_eater
def cookie_eater(ctx): """Eat cookies as they're baked.""" state = ctx.create_state() state["ready"] = True for _ in state.when_change("cookies"): eat_cookie(state)
python
def cookie_eater(ctx): state = ctx.create_state() state["ready"] = True for _ in state.when_change("cookies"): eat_cookie(state)
[ "def", "cookie_eater", "(", "ctx", ")", ":", "state", "=", "ctx", ".", "create_state", "(", ")", "state", "[", "\"ready\"", "]", "=", "True", "for", "_", "in", "state", ".", "when_change", "(", "\"cookies\"", ")", ":", "eat_cookie", "(", "state", ")" ]
Eat cookies as they're baked.
[ "Eat", "cookies", "as", "they", "re", "baked", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/examples/cookie_eater.py#L39-L45
4,033
pycampers/zproc
zproc/exceptions.py
signal_to_exception
def signal_to_exception(sig: signal.Signals) -> SignalException: """ Convert a ``signal.Signals`` to a ``SignalException``. This allows for natural, pythonic signal handing with the use of try-except blocks. .. code-block:: python import signal import zproc zproc.signal_to_exception(signals.SIGTERM) try: ... except zproc.SignalException as e: print("encountered:", e) finally: zproc.exception_to_signal(signals.SIGTERM) """ signal.signal(sig, _sig_exc_handler) return SignalException(sig)
python
def signal_to_exception(sig: signal.Signals) -> SignalException: signal.signal(sig, _sig_exc_handler) return SignalException(sig)
[ "def", "signal_to_exception", "(", "sig", ":", "signal", ".", "Signals", ")", "->", "SignalException", ":", "signal", ".", "signal", "(", "sig", ",", "_sig_exc_handler", ")", "return", "SignalException", "(", "sig", ")" ]
Convert a ``signal.Signals`` to a ``SignalException``. This allows for natural, pythonic signal handing with the use of try-except blocks. .. code-block:: python import signal import zproc zproc.signal_to_exception(signals.SIGTERM) try: ... except zproc.SignalException as e: print("encountered:", e) finally: zproc.exception_to_signal(signals.SIGTERM)
[ "Convert", "a", "signal", ".", "Signals", "to", "a", "SignalException", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/exceptions.py#L63-L83
4,034
pycampers/zproc
zproc/state/state.py
atomic
def atomic(fn: Callable) -> Callable: """ Wraps a function, to create an atomic operation out of it. This contract guarantees, that while an atomic ``fn`` is running - - No one, except the "callee" may access the state. - If an ``Exception`` occurs while the ``fn`` is running, the state remains unaffected. - | If a signal is sent to the "callee", the ``fn`` remains unaffected. | (The state is not left in an incoherent state.) .. note:: - The first argument to the wrapped function *must* be a :py:class:`State` object. - The wrapped ``fn`` receives a frozen version (snapshot) of state, which is a ``dict`` object, not a :py:class:`State` object. - It is not possible to call one atomic function from other. Please read :ref:`atomicity` for a detailed explanation. :param fn: The function to be wrapped, as an atomic function. :returns: A wrapper function. The wrapper function returns the value returned by the wrapped ``fn``. >>> import zproc >>> >>> @zproc.atomic ... def increment(snapshot): ... return snapshot['count'] + 1 ... >>> >>> ctx = zproc.Context() >>> state = ctx.create_state({'count': 0}) >>> >>> increment(state) 1 """ msg = { Msgs.cmd: Cmds.run_fn_atomically, Msgs.info: serializer.dumps_fn(fn), Msgs.args: (), Msgs.kwargs: {}, } @wraps(fn) def wrapper(state: State, *args, **kwargs): msg[Msgs.args] = args msg[Msgs.kwargs] = kwargs return state._s_request_reply(msg) return wrapper
python
def atomic(fn: Callable) -> Callable: msg = { Msgs.cmd: Cmds.run_fn_atomically, Msgs.info: serializer.dumps_fn(fn), Msgs.args: (), Msgs.kwargs: {}, } @wraps(fn) def wrapper(state: State, *args, **kwargs): msg[Msgs.args] = args msg[Msgs.kwargs] = kwargs return state._s_request_reply(msg) return wrapper
[ "def", "atomic", "(", "fn", ":", "Callable", ")", "->", "Callable", ":", "msg", "=", "{", "Msgs", ".", "cmd", ":", "Cmds", ".", "run_fn_atomically", ",", "Msgs", ".", "info", ":", "serializer", ".", "dumps_fn", "(", "fn", ")", ",", "Msgs", ".", "args", ":", "(", ")", ",", "Msgs", ".", "kwargs", ":", "{", "}", ",", "}", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "state", ":", "State", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "[", "Msgs", ".", "args", "]", "=", "args", "msg", "[", "Msgs", ".", "kwargs", "]", "=", "kwargs", "return", "state", ".", "_s_request_reply", "(", "msg", ")", "return", "wrapper" ]
Wraps a function, to create an atomic operation out of it. This contract guarantees, that while an atomic ``fn`` is running - - No one, except the "callee" may access the state. - If an ``Exception`` occurs while the ``fn`` is running, the state remains unaffected. - | If a signal is sent to the "callee", the ``fn`` remains unaffected. | (The state is not left in an incoherent state.) .. note:: - The first argument to the wrapped function *must* be a :py:class:`State` object. - The wrapped ``fn`` receives a frozen version (snapshot) of state, which is a ``dict`` object, not a :py:class:`State` object. - It is not possible to call one atomic function from other. Please read :ref:`atomicity` for a detailed explanation. :param fn: The function to be wrapped, as an atomic function. :returns: A wrapper function. The wrapper function returns the value returned by the wrapped ``fn``. >>> import zproc >>> >>> @zproc.atomic ... def increment(snapshot): ... return snapshot['count'] + 1 ... >>> >>> ctx = zproc.Context() >>> state = ctx.create_state({'count': 0}) >>> >>> increment(state) 1
[ "Wraps", "a", "function", "to", "create", "an", "atomic", "operation", "out", "of", "it", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L522-L575
4,035
pycampers/zproc
zproc/state/state.py
State.fork
def fork(self, server_address: str = None, *, namespace: str = None) -> "State": r""" "Forks" this State object. Takes the same args as the :py:class:`State` constructor, except that they automatically default to the values provided during the creation of this State object. If no args are provided to this function, then it shall create a new :py:class:`State` object that follows the exact same semantics as this one. This is preferred over ``copy()``\ -ing a :py:class:`State` object. Useful when one needs to access 2 or more namespaces from the same code. """ if server_address is None: server_address = self.server_address if namespace is None: namespace = self.namespace return self.__class__(server_address, namespace=namespace)
python
def fork(self, server_address: str = None, *, namespace: str = None) -> "State": r""" "Forks" this State object. Takes the same args as the :py:class:`State` constructor, except that they automatically default to the values provided during the creation of this State object. If no args are provided to this function, then it shall create a new :py:class:`State` object that follows the exact same semantics as this one. This is preferred over ``copy()``\ -ing a :py:class:`State` object. Useful when one needs to access 2 or more namespaces from the same code. """ if server_address is None: server_address = self.server_address if namespace is None: namespace = self.namespace return self.__class__(server_address, namespace=namespace)
[ "def", "fork", "(", "self", ",", "server_address", ":", "str", "=", "None", ",", "*", ",", "namespace", ":", "str", "=", "None", ")", "->", "\"State\"", ":", "if", "server_address", "is", "None", ":", "server_address", "=", "self", ".", "server_address", "if", "namespace", "is", "None", ":", "namespace", "=", "self", ".", "namespace", "return", "self", ".", "__class__", "(", "server_address", ",", "namespace", "=", "namespace", ")" ]
r""" "Forks" this State object. Takes the same args as the :py:class:`State` constructor, except that they automatically default to the values provided during the creation of this State object. If no args are provided to this function, then it shall create a new :py:class:`State` object that follows the exact same semantics as this one. This is preferred over ``copy()``\ -ing a :py:class:`State` object. Useful when one needs to access 2 or more namespaces from the same code.
[ "r", "Forks", "this", "State", "object", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L183-L203
4,036
pycampers/zproc
zproc/state/state.py
State.set
def set(self, value: dict): """ Set the state, completely over-writing the previous value. .. caution:: This kind of operation usually leads to a data race. Please take good care while using this. Use the :py:func:`atomic` deocrator if you're feeling anxious. """ self._s_request_reply({Msgs.cmd: Cmds.set_state, Msgs.info: value})
python
def set(self, value: dict): self._s_request_reply({Msgs.cmd: Cmds.set_state, Msgs.info: value})
[ "def", "set", "(", "self", ",", "value", ":", "dict", ")", ":", "self", ".", "_s_request_reply", "(", "{", "Msgs", ".", "cmd", ":", "Cmds", ".", "set_state", ",", "Msgs", ".", "info", ":", "value", "}", ")" ]
Set the state, completely over-writing the previous value. .. caution:: This kind of operation usually leads to a data race. Please take good care while using this. Use the :py:func:`atomic` deocrator if you're feeling anxious.
[ "Set", "the", "state", "completely", "over", "-", "writing", "the", "previous", "value", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L253-L265
4,037
pycampers/zproc
zproc/state/state.py
State.when_change_raw
def when_change_raw( self, *, live: bool = False, timeout: float = None, identical_okay: bool = False, start_time: bool = None, count: int = None, ) -> StateWatcher: """ A low-level hook that emits each and every state update. All other state watchers are built upon this only. .. include:: /api/state/get_raw_update.rst """ return StateWatcher( state=self, live=live, timeout=timeout, identical_okay=identical_okay, start_time=start_time, count=count, )
python
def when_change_raw( self, *, live: bool = False, timeout: float = None, identical_okay: bool = False, start_time: bool = None, count: int = None, ) -> StateWatcher: return StateWatcher( state=self, live=live, timeout=timeout, identical_okay=identical_okay, start_time=start_time, count=count, )
[ "def", "when_change_raw", "(", "self", ",", "*", ",", "live", ":", "bool", "=", "False", ",", "timeout", ":", "float", "=", "None", ",", "identical_okay", ":", "bool", "=", "False", ",", "start_time", ":", "bool", "=", "None", ",", "count", ":", "int", "=", "None", ",", ")", "->", "StateWatcher", ":", "return", "StateWatcher", "(", "state", "=", "self", ",", "live", "=", "live", ",", "timeout", "=", "timeout", ",", "identical_okay", "=", "identical_okay", ",", "start_time", "=", "start_time", ",", "count", "=", "count", ",", ")" ]
A low-level hook that emits each and every state update. All other state watchers are built upon this only. .. include:: /api/state/get_raw_update.rst
[ "A", "low", "-", "level", "hook", "that", "emits", "each", "and", "every", "state", "update", ".", "All", "other", "state", "watchers", "are", "built", "upon", "this", "only", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L305-L327
4,038
pycampers/zproc
zproc/state/state.py
State.when_change
def when_change( self, *keys: Hashable, exclude: bool = False, live: bool = False, timeout: float = None, identical_okay: bool = False, start_time: bool = None, count: int = None, ) -> StateWatcher: """ Block until a change is observed, and then return a copy of the state. .. include:: /api/state/get_when_change.rst """ if not keys: def callback(update: StateUpdate) -> dict: return update.after else: if identical_okay: raise ValueError( "Passing both `identical_okay` and `keys` is not possible. " "(Hint: Omit `keys`)" ) key_set = set(keys) def select(before, after): selected = {*before.keys(), *after.keys()} if exclude: return selected - key_set else: return selected & key_set def callback(update: StateUpdate) -> dict: before, after = update.before, update.after try: if not any(before[k] != after[k] for k in select(before, after)): raise _SkipStateUpdate except KeyError: # this indirectly implies that something has changed pass return update.after return StateWatcher( state=self, live=live, timeout=timeout, identical_okay=identical_okay, start_time=start_time, count=count, callback=callback, )
python
def when_change( self, *keys: Hashable, exclude: bool = False, live: bool = False, timeout: float = None, identical_okay: bool = False, start_time: bool = None, count: int = None, ) -> StateWatcher: if not keys: def callback(update: StateUpdate) -> dict: return update.after else: if identical_okay: raise ValueError( "Passing both `identical_okay` and `keys` is not possible. " "(Hint: Omit `keys`)" ) key_set = set(keys) def select(before, after): selected = {*before.keys(), *after.keys()} if exclude: return selected - key_set else: return selected & key_set def callback(update: StateUpdate) -> dict: before, after = update.before, update.after try: if not any(before[k] != after[k] for k in select(before, after)): raise _SkipStateUpdate except KeyError: # this indirectly implies that something has changed pass return update.after return StateWatcher( state=self, live=live, timeout=timeout, identical_okay=identical_okay, start_time=start_time, count=count, callback=callback, )
[ "def", "when_change", "(", "self", ",", "*", "keys", ":", "Hashable", ",", "exclude", ":", "bool", "=", "False", ",", "live", ":", "bool", "=", "False", ",", "timeout", ":", "float", "=", "None", ",", "identical_okay", ":", "bool", "=", "False", ",", "start_time", ":", "bool", "=", "None", ",", "count", ":", "int", "=", "None", ",", ")", "->", "StateWatcher", ":", "if", "not", "keys", ":", "def", "callback", "(", "update", ":", "StateUpdate", ")", "->", "dict", ":", "return", "update", ".", "after", "else", ":", "if", "identical_okay", ":", "raise", "ValueError", "(", "\"Passing both `identical_okay` and `keys` is not possible. \"", "\"(Hint: Omit `keys`)\"", ")", "key_set", "=", "set", "(", "keys", ")", "def", "select", "(", "before", ",", "after", ")", ":", "selected", "=", "{", "*", "before", ".", "keys", "(", ")", ",", "*", "after", ".", "keys", "(", ")", "}", "if", "exclude", ":", "return", "selected", "-", "key_set", "else", ":", "return", "selected", "&", "key_set", "def", "callback", "(", "update", ":", "StateUpdate", ")", "->", "dict", ":", "before", ",", "after", "=", "update", ".", "before", ",", "update", ".", "after", "try", ":", "if", "not", "any", "(", "before", "[", "k", "]", "!=", "after", "[", "k", "]", "for", "k", "in", "select", "(", "before", ",", "after", ")", ")", ":", "raise", "_SkipStateUpdate", "except", "KeyError", ":", "# this indirectly implies that something has changed", "pass", "return", "update", ".", "after", "return", "StateWatcher", "(", "state", "=", "self", ",", "live", "=", "live", ",", "timeout", "=", "timeout", ",", "identical_okay", "=", "identical_okay", ",", "start_time", "=", "start_time", ",", "count", "=", "count", ",", "callback", "=", "callback", ",", ")" ]
Block until a change is observed, and then return a copy of the state. .. include:: /api/state/get_when_change.rst
[ "Block", "until", "a", "change", "is", "observed", "and", "then", "return", "a", "copy", "of", "the", "state", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L329-L382
4,039
pycampers/zproc
zproc/state/state.py
State.when_available
def when_available(self, key: Hashable, **when_kwargs) -> StateWatcher: """ Block until ``key in state``, and then return a copy of the state. .. include:: /api/state/get_when_equality.rst """ return self.when(lambda snapshot: key in snapshot, **when_kwargs)
python
def when_available(self, key: Hashable, **when_kwargs) -> StateWatcher: return self.when(lambda snapshot: key in snapshot, **when_kwargs)
[ "def", "when_available", "(", "self", ",", "key", ":", "Hashable", ",", "*", "*", "when_kwargs", ")", "->", "StateWatcher", ":", "return", "self", ".", "when", "(", "lambda", "snapshot", ":", "key", "in", "snapshot", ",", "*", "*", "when_kwargs", ")" ]
Block until ``key in state``, and then return a copy of the state. .. include:: /api/state/get_when_equality.rst
[ "Block", "until", "key", "in", "state", "and", "then", "return", "a", "copy", "of", "the", "state", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L505-L511
4,040
pycampers/zproc
zproc/process.py
Process.stop
def stop(self): """ Stop this process. Once closed, it should not, and cannot be used again. :return: :py:attr:`~exitcode`. """ self.child.terminate() self._cleanup() return self.child.exitcode
python
def stop(self): self.child.terminate() self._cleanup() return self.child.exitcode
[ "def", "stop", "(", "self", ")", ":", "self", ".", "child", ".", "terminate", "(", ")", "self", ".", "_cleanup", "(", ")", "return", "self", ".", "child", ".", "exitcode" ]
Stop this process. Once closed, it should not, and cannot be used again. :return: :py:attr:`~exitcode`.
[ "Stop", "this", "process", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/process.py#L232-L242
4,041
pycampers/zproc
zproc/process.py
Process.wait
def wait(self, timeout: Union[int, float] = None): """ Wait until this process finishes execution, then return the value returned by the ``target``. This method raises a a :py:exc:`.ProcessWaitError`, if the child Process exits with a non-zero exitcode, or if something goes wrong while communicating with the child. :param timeout: The timeout in seconds. If the value is ``None``, it will block until the zproc server replies. For all other values, it will wait for a reply, for that amount of time before returning with a :py:class:`TimeoutError`. :return: The value returned by the ``target`` function. """ # try to fetch the cached result. if self._has_returned: return self._result if timeout is not None: target = time.time() + timeout while time.time() < target: self.child.join(timeout) if self.is_alive: raise TimeoutError( f"Timed-out while waiting for Process to return. -- {self!r}" ) else: self.child.join() if self.is_alive: return None exitcode = self.exitcode if exitcode != 0: raise exceptions.ProcessWaitError( f"Process finished with a non-zero exitcode ({exitcode}). -- {self!r}", exitcode, self, ) try: self._result = serializer.loads(self._result_sock.recv()) except zmq.error.Again: raise exceptions.ProcessWaitError( "The Process died before sending its return value. " "It probably crashed, got killed, or exited without warning.", exitcode, ) self._has_returned = True self._cleanup() return self._result
python
def wait(self, timeout: Union[int, float] = None): # try to fetch the cached result. if self._has_returned: return self._result if timeout is not None: target = time.time() + timeout while time.time() < target: self.child.join(timeout) if self.is_alive: raise TimeoutError( f"Timed-out while waiting for Process to return. -- {self!r}" ) else: self.child.join() if self.is_alive: return None exitcode = self.exitcode if exitcode != 0: raise exceptions.ProcessWaitError( f"Process finished with a non-zero exitcode ({exitcode}). -- {self!r}", exitcode, self, ) try: self._result = serializer.loads(self._result_sock.recv()) except zmq.error.Again: raise exceptions.ProcessWaitError( "The Process died before sending its return value. " "It probably crashed, got killed, or exited without warning.", exitcode, ) self._has_returned = True self._cleanup() return self._result
[ "def", "wait", "(", "self", ",", "timeout", ":", "Union", "[", "int", ",", "float", "]", "=", "None", ")", ":", "# try to fetch the cached result.", "if", "self", ".", "_has_returned", ":", "return", "self", ".", "_result", "if", "timeout", "is", "not", "None", ":", "target", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "time", ".", "time", "(", ")", "<", "target", ":", "self", ".", "child", ".", "join", "(", "timeout", ")", "if", "self", ".", "is_alive", ":", "raise", "TimeoutError", "(", "f\"Timed-out while waiting for Process to return. -- {self!r}\"", ")", "else", ":", "self", ".", "child", ".", "join", "(", ")", "if", "self", ".", "is_alive", ":", "return", "None", "exitcode", "=", "self", ".", "exitcode", "if", "exitcode", "!=", "0", ":", "raise", "exceptions", ".", "ProcessWaitError", "(", "f\"Process finished with a non-zero exitcode ({exitcode}). -- {self!r}\"", ",", "exitcode", ",", "self", ",", ")", "try", ":", "self", ".", "_result", "=", "serializer", ".", "loads", "(", "self", ".", "_result_sock", ".", "recv", "(", ")", ")", "except", "zmq", ".", "error", ".", "Again", ":", "raise", "exceptions", ".", "ProcessWaitError", "(", "\"The Process died before sending its return value. \"", "\"It probably crashed, got killed, or exited without warning.\"", ",", "exitcode", ",", ")", "self", ".", "_has_returned", "=", "True", "self", ".", "_cleanup", "(", ")", "return", "self", ".", "_result" ]
Wait until this process finishes execution, then return the value returned by the ``target``. This method raises a a :py:exc:`.ProcessWaitError`, if the child Process exits with a non-zero exitcode, or if something goes wrong while communicating with the child. :param timeout: The timeout in seconds. If the value is ``None``, it will block until the zproc server replies. For all other values, it will wait for a reply, for that amount of time before returning with a :py:class:`TimeoutError`. :return: The value returned by the ``target`` function.
[ "Wait", "until", "this", "process", "finishes", "execution", "then", "return", "the", "value", "returned", "by", "the", "target", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/process.py#L244-L299
4,042
pycampers/zproc
zproc/context.py
Context._process
def _process( self, target: Callable = None, **process_kwargs ) -> Union[Process, Callable]: r""" Produce a child process bound to this context. Can be used both as a function and decorator: .. code-block:: python :caption: Usage @zproc.process(pass_context=True) # you may pass some arguments here def p1(ctx): print('hello', ctx) @zproc.process # or not... def p2(state): print('hello', state) def p3(state): print('hello', state) zproc.process(p3) # or just use as a good ol' function :param target: Passed on to the :py:class:`Process` constructor. *Must be omitted when using this as a decorator.* :param \*\*process_kwargs: .. include:: /api/context/params/process_kwargs.rst :return: The :py:class:`Process` instance produced. """ process = Process( self.server_address, target, **{**self.process_kwargs, **process_kwargs} ) self.process_list.append(process) return process
python
def _process( self, target: Callable = None, **process_kwargs ) -> Union[Process, Callable]: r""" Produce a child process bound to this context. Can be used both as a function and decorator: .. code-block:: python :caption: Usage @zproc.process(pass_context=True) # you may pass some arguments here def p1(ctx): print('hello', ctx) @zproc.process # or not... def p2(state): print('hello', state) def p3(state): print('hello', state) zproc.process(p3) # or just use as a good ol' function :param target: Passed on to the :py:class:`Process` constructor. *Must be omitted when using this as a decorator.* :param \*\*process_kwargs: .. include:: /api/context/params/process_kwargs.rst :return: The :py:class:`Process` instance produced. """ process = Process( self.server_address, target, **{**self.process_kwargs, **process_kwargs} ) self.process_list.append(process) return process
[ "def", "_process", "(", "self", ",", "target", ":", "Callable", "=", "None", ",", "*", "*", "process_kwargs", ")", "->", "Union", "[", "Process", ",", "Callable", "]", ":", "process", "=", "Process", "(", "self", ".", "server_address", ",", "target", ",", "*", "*", "{", "*", "*", "self", ".", "process_kwargs", ",", "*", "*", "process_kwargs", "}", ")", "self", ".", "process_list", ".", "append", "(", "process", ")", "return", "process" ]
r""" Produce a child process bound to this context. Can be used both as a function and decorator: .. code-block:: python :caption: Usage @zproc.process(pass_context=True) # you may pass some arguments here def p1(ctx): print('hello', ctx) @zproc.process # or not... def p2(state): print('hello', state) def p3(state): print('hello', state) zproc.process(p3) # or just use as a good ol' function :param target: Passed on to the :py:class:`Process` constructor. *Must be omitted when using this as a decorator.* :param \*\*process_kwargs: .. include:: /api/context/params/process_kwargs.rst :return: The :py:class:`Process` instance produced.
[ "r", "Produce", "a", "child", "process", "bound", "to", "this", "context", "." ]
352a3c7166e2ccc3597c28385a8354b5a22afdc2
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/context.py#L230-L270
4,043
chr-1x/ananas
ananas/ananas.py
_expand_scheduledict
def _expand_scheduledict(scheduledict): """Converts a dict of items, some of which are scalar and some of which are lists, to a list of dicts with scalar items.""" result = [] def f(d): nonlocal result #print(d) d2 = {} for k,v in d.items(): if isinstance(v, str) and _cronslash(v, k) is not None: d[k] = _cronslash(v, k) for k,v in d.items(): if isinstance(v, Iterable): continue else: d2[k] = v if len(d2.keys()) == len(d.keys()): result.append(d2) return for k,v in d.items(): if isinstance(v, Iterable): for i in v: dprime = dict(**d) dprime[k] = i f(dprime) break f(scheduledict) return result
python
def _expand_scheduledict(scheduledict): result = [] def f(d): nonlocal result #print(d) d2 = {} for k,v in d.items(): if isinstance(v, str) and _cronslash(v, k) is not None: d[k] = _cronslash(v, k) for k,v in d.items(): if isinstance(v, Iterable): continue else: d2[k] = v if len(d2.keys()) == len(d.keys()): result.append(d2) return for k,v in d.items(): if isinstance(v, Iterable): for i in v: dprime = dict(**d) dprime[k] = i f(dprime) break f(scheduledict) return result
[ "def", "_expand_scheduledict", "(", "scheduledict", ")", ":", "result", "=", "[", "]", "def", "f", "(", "d", ")", ":", "nonlocal", "result", "#print(d)", "d2", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "str", ")", "and", "_cronslash", "(", "v", ",", "k", ")", "is", "not", "None", ":", "d", "[", "k", "]", "=", "_cronslash", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "Iterable", ")", ":", "continue", "else", ":", "d2", "[", "k", "]", "=", "v", "if", "len", "(", "d2", ".", "keys", "(", ")", ")", "==", "len", "(", "d", ".", "keys", "(", ")", ")", ":", "result", ".", "append", "(", "d2", ")", "return", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "Iterable", ")", ":", "for", "i", "in", "v", ":", "dprime", "=", "dict", "(", "*", "*", "d", ")", "dprime", "[", "k", "]", "=", "i", "f", "(", "dprime", ")", "break", "f", "(", "scheduledict", ")", "return", "result" ]
Converts a dict of items, some of which are scalar and some of which are lists, to a list of dicts with scalar items.
[ "Converts", "a", "dict", "of", "items", "some", "of", "which", "are", "scalar", "and", "some", "of", "which", "are", "lists", "to", "a", "list", "of", "dicts", "with", "scalar", "items", "." ]
e4625a3da193fa1c77119edb68d4ee18dcbc56ca
https://github.com/chr-1x/ananas/blob/e4625a3da193fa1c77119edb68d4ee18dcbc56ca/ananas/ananas.py#L55-L85
4,044
chr-1x/ananas
ananas/ananas.py
get_mentions
def get_mentions(status_dict, exclude=[]): """ Given a status dictionary, return all people mentioned in the toot, excluding those in the list passed in exclude. """ # Canonicalise the exclusion dictionary by lowercasing all names and # removing leading @'s for i, user in enumerate(exclude): user = user.casefold() if user[0] == "@": user = user[1:] exclude[i] = user users = [user["username"] for user in status_dict["mentions"] if user["username"].casefold() not in exclude] return users
python
def get_mentions(status_dict, exclude=[]): # Canonicalise the exclusion dictionary by lowercasing all names and # removing leading @'s for i, user in enumerate(exclude): user = user.casefold() if user[0] == "@": user = user[1:] exclude[i] = user users = [user["username"] for user in status_dict["mentions"] if user["username"].casefold() not in exclude] return users
[ "def", "get_mentions", "(", "status_dict", ",", "exclude", "=", "[", "]", ")", ":", "# Canonicalise the exclusion dictionary by lowercasing all names and", "# removing leading @'s", "for", "i", ",", "user", "in", "enumerate", "(", "exclude", ")", ":", "user", "=", "user", ".", "casefold", "(", ")", "if", "user", "[", "0", "]", "==", "\"@\"", ":", "user", "=", "user", "[", "1", ":", "]", "exclude", "[", "i", "]", "=", "user", "users", "=", "[", "user", "[", "\"username\"", "]", "for", "user", "in", "status_dict", "[", "\"mentions\"", "]", "if", "user", "[", "\"username\"", "]", ".", "casefold", "(", ")", "not", "in", "exclude", "]", "return", "users" ]
Given a status dictionary, return all people mentioned in the toot, excluding those in the list passed in exclude.
[ "Given", "a", "status", "dictionary", "return", "all", "people", "mentioned", "in", "the", "toot", "excluding", "those", "in", "the", "list", "passed", "in", "exclude", "." ]
e4625a3da193fa1c77119edb68d4ee18dcbc56ca
https://github.com/chr-1x/ananas/blob/e4625a3da193fa1c77119edb68d4ee18dcbc56ca/ananas/ananas.py#L210-L226
4,045
chr-1x/ananas
ananas/ananas.py
PineappleBot.report_error
def report_error(self, error, location=None): """Report an error that occurred during bot operations. The default handler tries to DM the bot admin, if one is set, but more handlers can be added by using the @error_reporter decorator.""" if location == None: location = inspect.stack()[1][3] self.log(location, error) for f in self.report_funcs: f(error)
python
def report_error(self, error, location=None): if location == None: location = inspect.stack()[1][3] self.log(location, error) for f in self.report_funcs: f(error)
[ "def", "report_error", "(", "self", ",", "error", ",", "location", "=", "None", ")", ":", "if", "location", "==", "None", ":", "location", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "3", "]", "self", ".", "log", "(", "location", ",", "error", ")", "for", "f", "in", "self", ".", "report_funcs", ":", "f", "(", "error", ")" ]
Report an error that occurred during bot operations. The default handler tries to DM the bot admin, if one is set, but more handlers can be added by using the @error_reporter decorator.
[ "Report", "an", "error", "that", "occurred", "during", "bot", "operations", ".", "The", "default", "handler", "tries", "to", "DM", "the", "bot", "admin", "if", "one", "is", "set", "but", "more", "handlers", "can", "be", "added", "by", "using", "the" ]
e4625a3da193fa1c77119edb68d4ee18dcbc56ca
https://github.com/chr-1x/ananas/blob/e4625a3da193fa1c77119edb68d4ee18dcbc56ca/ananas/ananas.py#L502-L509
4,046
chr-1x/ananas
ananas/ananas.py
PineappleBot.get_reply_visibility
def get_reply_visibility(self, status_dict): """Given a status dict, return the visibility that should be used. This behaves like Mastodon does by default. """ # Visibility rankings (higher is more limited) visibility = ("public", "unlisted", "private", "direct") default_visibility = visibility.index(self.default_visibility) status_visibility = visibility.index(status_dict["visibility"]) return visibility[max(default_visibility, status_visibility)]
python
def get_reply_visibility(self, status_dict): # Visibility rankings (higher is more limited) visibility = ("public", "unlisted", "private", "direct") default_visibility = visibility.index(self.default_visibility) status_visibility = visibility.index(status_dict["visibility"]) return visibility[max(default_visibility, status_visibility)]
[ "def", "get_reply_visibility", "(", "self", ",", "status_dict", ")", ":", "# Visibility rankings (higher is more limited)", "visibility", "=", "(", "\"public\"", ",", "\"unlisted\"", ",", "\"private\"", ",", "\"direct\"", ")", "default_visibility", "=", "visibility", ".", "index", "(", "self", ".", "default_visibility", ")", "status_visibility", "=", "visibility", ".", "index", "(", "status_dict", "[", "\"visibility\"", "]", ")", "return", "visibility", "[", "max", "(", "default_visibility", ",", "status_visibility", ")", "]" ]
Given a status dict, return the visibility that should be used. This behaves like Mastodon does by default.
[ "Given", "a", "status", "dict", "return", "the", "visibility", "that", "should", "be", "used", ".", "This", "behaves", "like", "Mastodon", "does", "by", "default", "." ]
e4625a3da193fa1c77119edb68d4ee18dcbc56ca
https://github.com/chr-1x/ananas/blob/e4625a3da193fa1c77119edb68d4ee18dcbc56ca/ananas/ananas.py#L556-L566
4,047
chr-1x/ananas
ananas/default/roll.py
spec_dice
def spec_dice(spec): """ Return the dice specification as a string in a common format """ if spec[0] == 'c': return str(spec[1]) elif spec[0] == 'r': r = spec[1:] s = "{}d{}".format(r[0], r[1]) if len(r) == 4 and ((r[2] == 'd' and r[3] < r[0]) or (r[2] == 'k' and r[3] > 0)): s += "{}{}".format(r[2], r[3]) return s elif spec[0] in ops: return "{} {} {}".format(spec_dice(spec[1]), spec[0], spec_dice(spec[2])) else: raise ValueError("Invalid dice specification")
python
def spec_dice(spec): if spec[0] == 'c': return str(spec[1]) elif spec[0] == 'r': r = spec[1:] s = "{}d{}".format(r[0], r[1]) if len(r) == 4 and ((r[2] == 'd' and r[3] < r[0]) or (r[2] == 'k' and r[3] > 0)): s += "{}{}".format(r[2], r[3]) return s elif spec[0] in ops: return "{} {} {}".format(spec_dice(spec[1]), spec[0], spec_dice(spec[2])) else: raise ValueError("Invalid dice specification")
[ "def", "spec_dice", "(", "spec", ")", ":", "if", "spec", "[", "0", "]", "==", "'c'", ":", "return", "str", "(", "spec", "[", "1", "]", ")", "elif", "spec", "[", "0", "]", "==", "'r'", ":", "r", "=", "spec", "[", "1", ":", "]", "s", "=", "\"{}d{}\"", ".", "format", "(", "r", "[", "0", "]", ",", "r", "[", "1", "]", ")", "if", "len", "(", "r", ")", "==", "4", "and", "(", "(", "r", "[", "2", "]", "==", "'d'", "and", "r", "[", "3", "]", "<", "r", "[", "0", "]", ")", "or", "(", "r", "[", "2", "]", "==", "'k'", "and", "r", "[", "3", "]", ">", "0", ")", ")", ":", "s", "+=", "\"{}{}\"", ".", "format", "(", "r", "[", "2", "]", ",", "r", "[", "3", "]", ")", "return", "s", "elif", "spec", "[", "0", "]", "in", "ops", ":", "return", "\"{} {} {}\"", ".", "format", "(", "spec_dice", "(", "spec", "[", "1", "]", ")", ",", "spec", "[", "0", "]", ",", "spec_dice", "(", "spec", "[", "2", "]", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid dice specification\"", ")" ]
Return the dice specification as a string in a common format
[ "Return", "the", "dice", "specification", "as", "a", "string", "in", "a", "common", "format" ]
e4625a3da193fa1c77119edb68d4ee18dcbc56ca
https://github.com/chr-1x/ananas/blob/e4625a3da193fa1c77119edb68d4ee18dcbc56ca/ananas/default/roll.py#L155-L167
4,048
chr-1x/ananas
ananas/default/roll.py
roll_dice
def roll_dice(spec): """ Perform the dice rolls and replace all roll expressions with lists of the dice faces that landed up. """ if spec[0] == 'c': return spec if spec[0] == 'r': r = spec[1:] if len(r) == 2: return ('r', perform_roll(r[0], r[1])) k = r[3] if r[2] == 'k' else -1 d = r[3] if r[2] == 'd' else -1 return ('r', perform_roll(r[0], r[1], k, d)) if spec[0] == "x": c = None roll = None if spec[1][0] == "c": c = spec[1] elif spec[1][0] == "r": roll = spec[1] if spec[2][0] == "c": c = spec[2] elif spec[2][0] == "r": roll = spec[2] if (c == None or roll == None): return ('*', roll_dice(spec[1]), roll_dice(spec[2])) else: if (c[1] > 50): raise SillyDiceError("I don't have that many dice!") return ("x", [roll_dice(roll) for i in range(c[1])]) if spec[0] in ops: return (spec[0], roll_dice(spec[1]), roll_dice(spec[2])) else: raise ValueError("Invalid dice specification")
python
def roll_dice(spec): if spec[0] == 'c': return spec if spec[0] == 'r': r = spec[1:] if len(r) == 2: return ('r', perform_roll(r[0], r[1])) k = r[3] if r[2] == 'k' else -1 d = r[3] if r[2] == 'd' else -1 return ('r', perform_roll(r[0], r[1], k, d)) if spec[0] == "x": c = None roll = None if spec[1][0] == "c": c = spec[1] elif spec[1][0] == "r": roll = spec[1] if spec[2][0] == "c": c = spec[2] elif spec[2][0] == "r": roll = spec[2] if (c == None or roll == None): return ('*', roll_dice(spec[1]), roll_dice(spec[2])) else: if (c[1] > 50): raise SillyDiceError("I don't have that many dice!") return ("x", [roll_dice(roll) for i in range(c[1])]) if spec[0] in ops: return (spec[0], roll_dice(spec[1]), roll_dice(spec[2])) else: raise ValueError("Invalid dice specification")
[ "def", "roll_dice", "(", "spec", ")", ":", "if", "spec", "[", "0", "]", "==", "'c'", ":", "return", "spec", "if", "spec", "[", "0", "]", "==", "'r'", ":", "r", "=", "spec", "[", "1", ":", "]", "if", "len", "(", "r", ")", "==", "2", ":", "return", "(", "'r'", ",", "perform_roll", "(", "r", "[", "0", "]", ",", "r", "[", "1", "]", ")", ")", "k", "=", "r", "[", "3", "]", "if", "r", "[", "2", "]", "==", "'k'", "else", "-", "1", "d", "=", "r", "[", "3", "]", "if", "r", "[", "2", "]", "==", "'d'", "else", "-", "1", "return", "(", "'r'", ",", "perform_roll", "(", "r", "[", "0", "]", ",", "r", "[", "1", "]", ",", "k", ",", "d", ")", ")", "if", "spec", "[", "0", "]", "==", "\"x\"", ":", "c", "=", "None", "roll", "=", "None", "if", "spec", "[", "1", "]", "[", "0", "]", "==", "\"c\"", ":", "c", "=", "spec", "[", "1", "]", "elif", "spec", "[", "1", "]", "[", "0", "]", "==", "\"r\"", ":", "roll", "=", "spec", "[", "1", "]", "if", "spec", "[", "2", "]", "[", "0", "]", "==", "\"c\"", ":", "c", "=", "spec", "[", "2", "]", "elif", "spec", "[", "2", "]", "[", "0", "]", "==", "\"r\"", ":", "roll", "=", "spec", "[", "2", "]", "if", "(", "c", "==", "None", "or", "roll", "==", "None", ")", ":", "return", "(", "'*'", ",", "roll_dice", "(", "spec", "[", "1", "]", ")", ",", "roll_dice", "(", "spec", "[", "2", "]", ")", ")", "else", ":", "if", "(", "c", "[", "1", "]", ">", "50", ")", ":", "raise", "SillyDiceError", "(", "\"I don't have that many dice!\"", ")", "return", "(", "\"x\"", ",", "[", "roll_dice", "(", "roll", ")", "for", "i", "in", "range", "(", "c", "[", "1", "]", ")", "]", ")", "if", "spec", "[", "0", "]", "in", "ops", ":", "return", "(", "spec", "[", "0", "]", ",", "roll_dice", "(", "spec", "[", "1", "]", ")", ",", "roll_dice", "(", "spec", "[", "2", "]", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid dice specification\"", ")" ]
Perform the dice rolls and replace all roll expressions with lists of the dice faces that landed up.
[ "Perform", "the", "dice", "rolls", "and", "replace", "all", "roll", "expressions", "with", "lists", "of", "the", "dice", "faces", "that", "landed", "up", "." ]
e4625a3da193fa1c77119edb68d4ee18dcbc56ca
https://github.com/chr-1x/ananas/blob/e4625a3da193fa1c77119edb68d4ee18dcbc56ca/ananas/default/roll.py#L169-L195
4,049
chr-1x/ananas
ananas/default/roll.py
sum_dice
def sum_dice(spec): """ Replace the dice roll arrays from roll_dice in place with summations of the rolls. """ if spec[0] == 'c': return spec[1] elif spec[0] == 'r': return sum(spec[1]) elif spec[0] == 'x': return [sum_dice(r) for r in spec[1]] elif spec[0] in ops: return (spec[0], sum_dice(spec[1]), sum_dice(spec[2])) else: raise ValueError("Invalid dice specification")
python
def sum_dice(spec): if spec[0] == 'c': return spec[1] elif spec[0] == 'r': return sum(spec[1]) elif spec[0] == 'x': return [sum_dice(r) for r in spec[1]] elif spec[0] in ops: return (spec[0], sum_dice(spec[1]), sum_dice(spec[2])) else: raise ValueError("Invalid dice specification")
[ "def", "sum_dice", "(", "spec", ")", ":", "if", "spec", "[", "0", "]", "==", "'c'", ":", "return", "spec", "[", "1", "]", "elif", "spec", "[", "0", "]", "==", "'r'", ":", "return", "sum", "(", "spec", "[", "1", "]", ")", "elif", "spec", "[", "0", "]", "==", "'x'", ":", "return", "[", "sum_dice", "(", "r", ")", "for", "r", "in", "spec", "[", "1", "]", "]", "elif", "spec", "[", "0", "]", "in", "ops", ":", "return", "(", "spec", "[", "0", "]", ",", "sum_dice", "(", "spec", "[", "1", "]", ")", ",", "sum_dice", "(", "spec", "[", "2", "]", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid dice specification\"", ")" ]
Replace the dice roll arrays from roll_dice in place with summations of the rolls.
[ "Replace", "the", "dice", "roll", "arrays", "from", "roll_dice", "in", "place", "with", "summations", "of", "the", "rolls", "." ]
e4625a3da193fa1c77119edb68d4ee18dcbc56ca
https://github.com/chr-1x/ananas/blob/e4625a3da193fa1c77119edb68d4ee18dcbc56ca/ananas/default/roll.py#L197-L206
4,050
mutalyzer/description-extractor
repeat-extractor.py
short_sequence_repeat_extractor
def short_sequence_repeat_extractor(string, min_length=1): """ Extract the short tandem repeat structure from a string. :arg string string: The string. :arg integer min_length: Minimum length of the repeat structure. """ length = len(string) k_max = length // 2 + 1 if k_max > THRESHOLD: k_max = THRESHOLD // 2 repeats = [] i = 0 last_repeat = i while i < length: max_count = 0 max_k = 1 for k in range(min_length, k_max): count = 0 for j in range(i + k, length - k + 1, k): if string[i:i + k] != string[j:j + k]: break count += 1 if count > 0 and count >= max_count: max_count = count max_k = k if max_count > 0: if last_repeat < i: repeats.append(Repeat(last_repeat, i)) repeats.append(Repeat(i, i + max_k, max_count)) last_repeat = i + max_k * (max_count + 1) i += max_k * (max_count + 1) if last_repeat < i: repeats.append(Repeat(last_repeat, i)) return repeats
python
def short_sequence_repeat_extractor(string, min_length=1): length = len(string) k_max = length // 2 + 1 if k_max > THRESHOLD: k_max = THRESHOLD // 2 repeats = [] i = 0 last_repeat = i while i < length: max_count = 0 max_k = 1 for k in range(min_length, k_max): count = 0 for j in range(i + k, length - k + 1, k): if string[i:i + k] != string[j:j + k]: break count += 1 if count > 0 and count >= max_count: max_count = count max_k = k if max_count > 0: if last_repeat < i: repeats.append(Repeat(last_repeat, i)) repeats.append(Repeat(i, i + max_k, max_count)) last_repeat = i + max_k * (max_count + 1) i += max_k * (max_count + 1) if last_repeat < i: repeats.append(Repeat(last_repeat, i)) return repeats
[ "def", "short_sequence_repeat_extractor", "(", "string", ",", "min_length", "=", "1", ")", ":", "length", "=", "len", "(", "string", ")", "k_max", "=", "length", "//", "2", "+", "1", "if", "k_max", ">", "THRESHOLD", ":", "k_max", "=", "THRESHOLD", "//", "2", "repeats", "=", "[", "]", "i", "=", "0", "last_repeat", "=", "i", "while", "i", "<", "length", ":", "max_count", "=", "0", "max_k", "=", "1", "for", "k", "in", "range", "(", "min_length", ",", "k_max", ")", ":", "count", "=", "0", "for", "j", "in", "range", "(", "i", "+", "k", ",", "length", "-", "k", "+", "1", ",", "k", ")", ":", "if", "string", "[", "i", ":", "i", "+", "k", "]", "!=", "string", "[", "j", ":", "j", "+", "k", "]", ":", "break", "count", "+=", "1", "if", "count", ">", "0", "and", "count", ">=", "max_count", ":", "max_count", "=", "count", "max_k", "=", "k", "if", "max_count", ">", "0", ":", "if", "last_repeat", "<", "i", ":", "repeats", ".", "append", "(", "Repeat", "(", "last_repeat", ",", "i", ")", ")", "repeats", ".", "append", "(", "Repeat", "(", "i", ",", "i", "+", "max_k", ",", "max_count", ")", ")", "last_repeat", "=", "i", "+", "max_k", "*", "(", "max_count", "+", "1", ")", "i", "+=", "max_k", "*", "(", "max_count", "+", "1", ")", "if", "last_repeat", "<", "i", ":", "repeats", ".", "append", "(", "Repeat", "(", "last_repeat", ",", "i", ")", ")", "return", "repeats" ]
Extract the short tandem repeat structure from a string. :arg string string: The string. :arg integer min_length: Minimum length of the repeat structure.
[ "Extract", "the", "short", "tandem", "repeat", "structure", "from", "a", "string", "." ]
9bea5f161c5038956391d77ef3841a2dcd2f1a1b
https://github.com/mutalyzer/description-extractor/blob/9bea5f161c5038956391d77ef3841a2dcd2f1a1b/repeat-extractor.py#L37-L79
4,051
nuagenetworks/monolithe
monolithe/lib/printer.py
Printer.json
def json(cls, message): """ Print a nice JSON output Args: message: the message to print """ if type(message) is OrderedDict: pprint(dict(message)) else: pprint(message)
python
def json(cls, message): if type(message) is OrderedDict: pprint(dict(message)) else: pprint(message)
[ "def", "json", "(", "cls", ",", "message", ")", ":", "if", "type", "(", "message", ")", "is", "OrderedDict", ":", "pprint", "(", "dict", "(", "message", ")", ")", "else", ":", "pprint", "(", "message", ")" ]
Print a nice JSON output Args: message: the message to print
[ "Print", "a", "nice", "JSON", "output" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/lib/printer.py#L109-L119
4,052
nuagenetworks/monolithe
monolithe/specifications/specification.py
Specification.to_dict
def to_dict(self): """ Transform the current specification to a dictionary """ data = {"model": {}} data["model"]["description"] = self.description data["model"]["entity_name"] = self.entity_name data["model"]["package"] = self.package data["model"]["resource_name"] = self.resource_name data["model"]["rest_name"] = self.rest_name data["model"]["extends"] = self.extends data["model"]["get"] = self.allows_get data["model"]["update"] = self.allows_update data["model"]["create"] = self.allows_create data["model"]["delete"] = self.allows_delete data["model"]["root"] = self.is_root data["model"]["userlabel"] = self.userlabel data["model"]["template"] = self.template data["model"]["allowed_job_commands"] = self.allowed_job_commands data["attributes"] = [] for attribute in self.attributes: data["attributes"].append(attribute.to_dict()) data["children"] = [] for api in self.child_apis: data["children"].append(api.to_dict()) return data
python
def to_dict(self): data = {"model": {}} data["model"]["description"] = self.description data["model"]["entity_name"] = self.entity_name data["model"]["package"] = self.package data["model"]["resource_name"] = self.resource_name data["model"]["rest_name"] = self.rest_name data["model"]["extends"] = self.extends data["model"]["get"] = self.allows_get data["model"]["update"] = self.allows_update data["model"]["create"] = self.allows_create data["model"]["delete"] = self.allows_delete data["model"]["root"] = self.is_root data["model"]["userlabel"] = self.userlabel data["model"]["template"] = self.template data["model"]["allowed_job_commands"] = self.allowed_job_commands data["attributes"] = [] for attribute in self.attributes: data["attributes"].append(attribute.to_dict()) data["children"] = [] for api in self.child_apis: data["children"].append(api.to_dict()) return data
[ "def", "to_dict", "(", "self", ")", ":", "data", "=", "{", "\"model\"", ":", "{", "}", "}", "data", "[", "\"model\"", "]", "[", "\"description\"", "]", "=", "self", ".", "description", "data", "[", "\"model\"", "]", "[", "\"entity_name\"", "]", "=", "self", ".", "entity_name", "data", "[", "\"model\"", "]", "[", "\"package\"", "]", "=", "self", ".", "package", "data", "[", "\"model\"", "]", "[", "\"resource_name\"", "]", "=", "self", ".", "resource_name", "data", "[", "\"model\"", "]", "[", "\"rest_name\"", "]", "=", "self", ".", "rest_name", "data", "[", "\"model\"", "]", "[", "\"extends\"", "]", "=", "self", ".", "extends", "data", "[", "\"model\"", "]", "[", "\"get\"", "]", "=", "self", ".", "allows_get", "data", "[", "\"model\"", "]", "[", "\"update\"", "]", "=", "self", ".", "allows_update", "data", "[", "\"model\"", "]", "[", "\"create\"", "]", "=", "self", ".", "allows_create", "data", "[", "\"model\"", "]", "[", "\"delete\"", "]", "=", "self", ".", "allows_delete", "data", "[", "\"model\"", "]", "[", "\"root\"", "]", "=", "self", ".", "is_root", "data", "[", "\"model\"", "]", "[", "\"userlabel\"", "]", "=", "self", ".", "userlabel", "data", "[", "\"model\"", "]", "[", "\"template\"", "]", "=", "self", ".", "template", "data", "[", "\"model\"", "]", "[", "\"allowed_job_commands\"", "]", "=", "self", ".", "allowed_job_commands", "data", "[", "\"attributes\"", "]", "=", "[", "]", "for", "attribute", "in", "self", ".", "attributes", ":", "data", "[", "\"attributes\"", "]", ".", "append", "(", "attribute", ".", "to_dict", "(", ")", ")", "data", "[", "\"children\"", "]", "=", "[", "]", "for", "api", "in", "self", ".", "child_apis", ":", "data", "[", "\"children\"", "]", ".", "append", "(", "api", ".", "to_dict", "(", ")", ")", "return", "data" ]
Transform the current specification to a dictionary
[ "Transform", "the", "current", "specification", "to", "a", "dictionary" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/specifications/specification.py#L101-L131
4,053
nuagenetworks/monolithe
monolithe/specifications/specification.py
Specification.from_dict
def from_dict(self, data): """ Fill the current object with information from the specification """ if "model" in data: model = data["model"] self.description = model["description"] if "description" in model else None self.package = model["package"] if "package" in model else None self.extends = model["extends"] if "extends" in model else [] self.entity_name = model["entity_name"] if "entity_name" in model else None self.rest_name = model["rest_name"] if "rest_name" in model else None self.resource_name = model["resource_name"] if "resource_name" in model else None self.allows_get = model["get"] if "get" in model else False self.allows_create = model["create"] if "create" in model else False self.allows_update = model["update"] if "update" in model else False self.allows_delete = model["delete"] if "delete" in model else False self.is_root = model["root"] if "root" in model else False self.userlabel = model["userlabel"] if "userlabel" in model else None self.template = model["template"] if "template" in model else False self.allowed_job_commands = model["allowed_job_commands"] if "allowed_job_commands" in model else None if "attributes" in data: self.attributes = self._get_attributes(data["attributes"]) if "children" in data: self.child_apis = self._get_apis(data["children"])
python
def from_dict(self, data): if "model" in data: model = data["model"] self.description = model["description"] if "description" in model else None self.package = model["package"] if "package" in model else None self.extends = model["extends"] if "extends" in model else [] self.entity_name = model["entity_name"] if "entity_name" in model else None self.rest_name = model["rest_name"] if "rest_name" in model else None self.resource_name = model["resource_name"] if "resource_name" in model else None self.allows_get = model["get"] if "get" in model else False self.allows_create = model["create"] if "create" in model else False self.allows_update = model["update"] if "update" in model else False self.allows_delete = model["delete"] if "delete" in model else False self.is_root = model["root"] if "root" in model else False self.userlabel = model["userlabel"] if "userlabel" in model else None self.template = model["template"] if "template" in model else False self.allowed_job_commands = model["allowed_job_commands"] if "allowed_job_commands" in model else None if "attributes" in data: self.attributes = self._get_attributes(data["attributes"]) if "children" in data: self.child_apis = self._get_apis(data["children"])
[ "def", "from_dict", "(", "self", ",", "data", ")", ":", "if", "\"model\"", "in", "data", ":", "model", "=", "data", "[", "\"model\"", "]", "self", ".", "description", "=", "model", "[", "\"description\"", "]", "if", "\"description\"", "in", "model", "else", "None", "self", ".", "package", "=", "model", "[", "\"package\"", "]", "if", "\"package\"", "in", "model", "else", "None", "self", ".", "extends", "=", "model", "[", "\"extends\"", "]", "if", "\"extends\"", "in", "model", "else", "[", "]", "self", ".", "entity_name", "=", "model", "[", "\"entity_name\"", "]", "if", "\"entity_name\"", "in", "model", "else", "None", "self", ".", "rest_name", "=", "model", "[", "\"rest_name\"", "]", "if", "\"rest_name\"", "in", "model", "else", "None", "self", ".", "resource_name", "=", "model", "[", "\"resource_name\"", "]", "if", "\"resource_name\"", "in", "model", "else", "None", "self", ".", "allows_get", "=", "model", "[", "\"get\"", "]", "if", "\"get\"", "in", "model", "else", "False", "self", ".", "allows_create", "=", "model", "[", "\"create\"", "]", "if", "\"create\"", "in", "model", "else", "False", "self", ".", "allows_update", "=", "model", "[", "\"update\"", "]", "if", "\"update\"", "in", "model", "else", "False", "self", ".", "allows_delete", "=", "model", "[", "\"delete\"", "]", "if", "\"delete\"", "in", "model", "else", "False", "self", ".", "is_root", "=", "model", "[", "\"root\"", "]", "if", "\"root\"", "in", "model", "else", "False", "self", ".", "userlabel", "=", "model", "[", "\"userlabel\"", "]", "if", "\"userlabel\"", "in", "model", "else", "None", "self", ".", "template", "=", "model", "[", "\"template\"", "]", "if", "\"template\"", "in", "model", "else", "False", "self", ".", "allowed_job_commands", "=", "model", "[", "\"allowed_job_commands\"", "]", "if", "\"allowed_job_commands\"", "in", "model", "else", "None", "if", "\"attributes\"", "in", "data", ":", "self", ".", "attributes", "=", "self", ".", "_get_attributes", "(", "data", "[", "\"attributes\"", "]", ")", "if", "\"children\"", "in", "data", ":", "self", ".", "child_apis", "=", "self", ".", "_get_apis", "(", "data", "[", "\"children\"", "]", ")" ]
Fill the current object with information from the specification
[ "Fill", "the", "current", "object", "with", "information", "from", "the", "specification" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/specifications/specification.py#L133-L158
4,054
nuagenetworks/monolithe
monolithe/specifications/specification.py
Specification._get_apis
def _get_apis(self, apis): """ Process apis for the given model Args: model: the model processed apis: the list of apis availble for the current model relations: dict containing all relations between resources """ ret = [] for data in apis: ret.append(SpecificationAPI(specification=self, data=data)) return sorted(ret, key=lambda x: x.rest_name[1:])
python
def _get_apis(self, apis): ret = [] for data in apis: ret.append(SpecificationAPI(specification=self, data=data)) return sorted(ret, key=lambda x: x.rest_name[1:])
[ "def", "_get_apis", "(", "self", ",", "apis", ")", ":", "ret", "=", "[", "]", "for", "data", "in", "apis", ":", "ret", ".", "append", "(", "SpecificationAPI", "(", "specification", "=", "self", ",", "data", "=", "data", ")", ")", "return", "sorted", "(", "ret", ",", "key", "=", "lambda", "x", ":", "x", ".", "rest_name", "[", "1", ":", "]", ")" ]
Process apis for the given model Args: model: the model processed apis: the list of apis availble for the current model relations: dict containing all relations between resources
[ "Process", "apis", "for", "the", "given", "model" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/specifications/specification.py#L160-L173
4,055
nuagenetworks/monolithe
monolithe/generators/lang/javascript/writers/apiversionwriter.py
APIVersionWriter._read_config
def _read_config(self): """ This method reads provided json config file. """ this_dir = os.path.dirname(__file__) config_file = os.path.abspath(os.path.join(this_dir, "..", "config", "config.json")) self.generic_enum_attrs = [] self.base_attrs = [] self.generic_enums = [] self.named_entity_attrs = [] self.overide_generic_enums = [] self.enum_attrs_for_locale = {} self.generic_enum_attrs_for_locale = {} self.list_subtypes_generic = [] Printer.log("Configuration file: %s" % (config_file)) if (os.path.isfile(config_file)): with open(config_file, 'r') as input_json: json_config_data = json.load(input_json) self.base_attrs = json_config_data['base_attrs'] self.generic_enums = json_config_data['generic_enums'] self.named_entity_attrs = json_config_data['named_entity_attrs'] self.overide_generic_enums = json_config_data['overide_generic_enums'] self.list_subtypes_generic = json_config_data['list_subtypes_generic'] for enum_name, values in self.generic_enums.iteritems(): enum_attr = SpecificationAttribute() enum_attr.name = enum_name enum_attr.allowed_choices = values self.generic_enum_attrs.append(enum_attr) else: Printer.log("Configuration file missing: %s" % (config_file))
python
def _read_config(self): this_dir = os.path.dirname(__file__) config_file = os.path.abspath(os.path.join(this_dir, "..", "config", "config.json")) self.generic_enum_attrs = [] self.base_attrs = [] self.generic_enums = [] self.named_entity_attrs = [] self.overide_generic_enums = [] self.enum_attrs_for_locale = {} self.generic_enum_attrs_for_locale = {} self.list_subtypes_generic = [] Printer.log("Configuration file: %s" % (config_file)) if (os.path.isfile(config_file)): with open(config_file, 'r') as input_json: json_config_data = json.load(input_json) self.base_attrs = json_config_data['base_attrs'] self.generic_enums = json_config_data['generic_enums'] self.named_entity_attrs = json_config_data['named_entity_attrs'] self.overide_generic_enums = json_config_data['overide_generic_enums'] self.list_subtypes_generic = json_config_data['list_subtypes_generic'] for enum_name, values in self.generic_enums.iteritems(): enum_attr = SpecificationAttribute() enum_attr.name = enum_name enum_attr.allowed_choices = values self.generic_enum_attrs.append(enum_attr) else: Printer.log("Configuration file missing: %s" % (config_file))
[ "def", "_read_config", "(", "self", ")", ":", "this_dir", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "config_file", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "this_dir", ",", "\"..\"", ",", "\"config\"", ",", "\"config.json\"", ")", ")", "self", ".", "generic_enum_attrs", "=", "[", "]", "self", ".", "base_attrs", "=", "[", "]", "self", ".", "generic_enums", "=", "[", "]", "self", ".", "named_entity_attrs", "=", "[", "]", "self", ".", "overide_generic_enums", "=", "[", "]", "self", ".", "enum_attrs_for_locale", "=", "{", "}", "self", ".", "generic_enum_attrs_for_locale", "=", "{", "}", "self", ".", "list_subtypes_generic", "=", "[", "]", "Printer", ".", "log", "(", "\"Configuration file: %s\"", "%", "(", "config_file", ")", ")", "if", "(", "os", ".", "path", ".", "isfile", "(", "config_file", ")", ")", ":", "with", "open", "(", "config_file", ",", "'r'", ")", "as", "input_json", ":", "json_config_data", "=", "json", ".", "load", "(", "input_json", ")", "self", ".", "base_attrs", "=", "json_config_data", "[", "'base_attrs'", "]", "self", ".", "generic_enums", "=", "json_config_data", "[", "'generic_enums'", "]", "self", ".", "named_entity_attrs", "=", "json_config_data", "[", "'named_entity_attrs'", "]", "self", ".", "overide_generic_enums", "=", "json_config_data", "[", "'overide_generic_enums'", "]", "self", ".", "list_subtypes_generic", "=", "json_config_data", "[", "'list_subtypes_generic'", "]", "for", "enum_name", ",", "values", "in", "self", ".", "generic_enums", ".", "iteritems", "(", ")", ":", "enum_attr", "=", "SpecificationAttribute", "(", ")", "enum_attr", ".", "name", "=", "enum_name", "enum_attr", ".", "allowed_choices", "=", "values", "self", ".", "generic_enum_attrs", ".", "append", "(", "enum_attr", ")", "else", ":", "Printer", ".", "log", "(", "\"Configuration file missing: %s\"", "%", "(", "config_file", ")", ")" ]
This method reads provided json config file.
[ "This", "method", "reads", "provided", "json", "config", "file", "." ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/javascript/writers/apiversionwriter.py#L36-L70
4,056
nuagenetworks/monolithe
monolithe/generators/lang/javascript/writers/apiversionwriter.py
APIVersionWriter.perform
def perform(self, specifications): """ This method is the entry point of javascript code writer. Monolithe will call it when the javascript plugin is to generate code. """ self.enum_list = [] self.model_list = [] self.job_commands = filter(lambda attr: attr.name == 'command', specifications.get("job").attributes)[0].allowed_choices #Printer.log("job_commands: %s" % (self.job_commands)) self._write_abstract_named_entity() self.entity_names = [specification.entity_name for rest_name, specification in specifications.iteritems()] for rest_name, specification in specifications.iteritems(): self._write_model(specification=specification) #self._write_generic_enums() self.write(destination = self.model_directory, filename="index.js", template_name="model_index.js.tpl", class_prefix = self._class_prefix, model_list = sorted(self.model_list)) self.write(destination = self.enum_directory, filename="index.js", template_name="enum_index.js.tpl", class_prefix = self._class_prefix, enum_list = sorted(self.enum_list)) self._write_locales(specifications)
python
def perform(self, specifications): self.enum_list = [] self.model_list = [] self.job_commands = filter(lambda attr: attr.name == 'command', specifications.get("job").attributes)[0].allowed_choices #Printer.log("job_commands: %s" % (self.job_commands)) self._write_abstract_named_entity() self.entity_names = [specification.entity_name for rest_name, specification in specifications.iteritems()] for rest_name, specification in specifications.iteritems(): self._write_model(specification=specification) #self._write_generic_enums() self.write(destination = self.model_directory, filename="index.js", template_name="model_index.js.tpl", class_prefix = self._class_prefix, model_list = sorted(self.model_list)) self.write(destination = self.enum_directory, filename="index.js", template_name="enum_index.js.tpl", class_prefix = self._class_prefix, enum_list = sorted(self.enum_list)) self._write_locales(specifications)
[ "def", "perform", "(", "self", ",", "specifications", ")", ":", "self", ".", "enum_list", "=", "[", "]", "self", ".", "model_list", "=", "[", "]", "self", ".", "job_commands", "=", "filter", "(", "lambda", "attr", ":", "attr", ".", "name", "==", "'command'", ",", "specifications", ".", "get", "(", "\"job\"", ")", ".", "attributes", ")", "[", "0", "]", ".", "allowed_choices", "#Printer.log(\"job_commands: %s\" % (self.job_commands))", "self", ".", "_write_abstract_named_entity", "(", ")", "self", ".", "entity_names", "=", "[", "specification", ".", "entity_name", "for", "rest_name", ",", "specification", "in", "specifications", ".", "iteritems", "(", ")", "]", "for", "rest_name", ",", "specification", "in", "specifications", ".", "iteritems", "(", ")", ":", "self", ".", "_write_model", "(", "specification", "=", "specification", ")", "#self._write_generic_enums()", "self", ".", "write", "(", "destination", "=", "self", ".", "model_directory", ",", "filename", "=", "\"index.js\"", ",", "template_name", "=", "\"model_index.js.tpl\"", ",", "class_prefix", "=", "self", ".", "_class_prefix", ",", "model_list", "=", "sorted", "(", "self", ".", "model_list", ")", ")", "self", ".", "write", "(", "destination", "=", "self", ".", "enum_directory", ",", "filename", "=", "\"index.js\"", ",", "template_name", "=", "\"enum_index.js.tpl\"", ",", "class_prefix", "=", "self", ".", "_class_prefix", ",", "enum_list", "=", "sorted", "(", "self", ".", "enum_list", ")", ")", "self", ".", "_write_locales", "(", "specifications", ")" ]
This method is the entry point of javascript code writer. Monolithe will call it when the javascript plugin is to generate code.
[ "This", "method", "is", "the", "entry", "point", "of", "javascript", "code", "writer", ".", "Monolithe", "will", "call", "it", "when", "the", "javascript", "plugin", "is", "to", "generate", "code", "." ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/javascript/writers/apiversionwriter.py#L73-L103
4,057
nuagenetworks/monolithe
monolithe/generators/lang/javascript/writers/apiversionwriter.py
APIVersionWriter._write_abstract_named_entity
def _write_abstract_named_entity(self): """ This method generates AbstractNamedEntity class js file. """ filename = "%sAbstractNamedEntity.js" % (self._class_prefix) superclass_name = "%sEntity" % (self._class_prefix) # write will write a file using a template. # mandatory params: destination directory, destination file name, template file name # optional params: whatever that is needed from inside the Jinja template self.write(destination = self.abstract_directory, filename = filename, template_name = "abstract_named_entity.js.tpl", class_prefix = self._class_prefix, superclass_name = superclass_name)
python
def _write_abstract_named_entity(self): filename = "%sAbstractNamedEntity.js" % (self._class_prefix) superclass_name = "%sEntity" % (self._class_prefix) # write will write a file using a template. # mandatory params: destination directory, destination file name, template file name # optional params: whatever that is needed from inside the Jinja template self.write(destination = self.abstract_directory, filename = filename, template_name = "abstract_named_entity.js.tpl", class_prefix = self._class_prefix, superclass_name = superclass_name)
[ "def", "_write_abstract_named_entity", "(", "self", ")", ":", "filename", "=", "\"%sAbstractNamedEntity.js\"", "%", "(", "self", ".", "_class_prefix", ")", "superclass_name", "=", "\"%sEntity\"", "%", "(", "self", ".", "_class_prefix", ")", "# write will write a file using a template.", "# mandatory params: destination directory, destination file name, template file name", "# optional params: whatever that is needed from inside the Jinja template", "self", ".", "write", "(", "destination", "=", "self", ".", "abstract_directory", ",", "filename", "=", "filename", ",", "template_name", "=", "\"abstract_named_entity.js.tpl\"", ",", "class_prefix", "=", "self", ".", "_class_prefix", ",", "superclass_name", "=", "superclass_name", ")" ]
This method generates AbstractNamedEntity class js file.
[ "This", "method", "generates", "AbstractNamedEntity", "class", "js", "file", "." ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/javascript/writers/apiversionwriter.py#L131-L146
4,058
nuagenetworks/monolithe
monolithe/lib/taskmanager.py
TaskManager.wait_until_exit
def wait_until_exit(self): """ Wait until all the threads are finished. """ [t.join() for t in self.threads] self.threads = list()
python
def wait_until_exit(self): [t.join() for t in self.threads] self.threads = list()
[ "def", "wait_until_exit", "(", "self", ")", ":", "[", "t", ".", "join", "(", ")", "for", "t", "in", "self", ".", "threads", "]", "self", ".", "threads", "=", "list", "(", ")" ]
Wait until all the threads are finished.
[ "Wait", "until", "all", "the", "threads", "are", "finished", "." ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/lib/taskmanager.py#L45-L51
4,059
nuagenetworks/monolithe
monolithe/lib/taskmanager.py
TaskManager.start_task
def start_task(self, method, *args, **kwargs): """ Start a task in a separate thread Args: method: the method to start in a separate thread args: Accept args/kwargs arguments """ thread = threading.Thread(target=method, args=args, kwargs=kwargs) thread.is_daemon = False thread.start() self.threads.append(thread)
python
def start_task(self, method, *args, **kwargs): thread = threading.Thread(target=method, args=args, kwargs=kwargs) thread.is_daemon = False thread.start() self.threads.append(thread)
[ "def", "start_task", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "method", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "thread", ".", "is_daemon", "=", "False", "thread", ".", "start", "(", ")", "self", ".", "threads", ".", "append", "(", "thread", ")" ]
Start a task in a separate thread Args: method: the method to start in a separate thread args: Accept args/kwargs arguments
[ "Start", "a", "task", "in", "a", "separate", "thread" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/lib/taskmanager.py#L53-L63
4,060
nuagenetworks/monolithe
monolithe/courgette/result.py
CourgetteResult.add_report
def add_report(self, specification_name, report): """ Adds a given report with the given specification_name as key to the reports list and computes the number of success, failures and errors Args: specification_name: string representing the specification (with ".spec") report: The """ self._reports[specification_name] = report self._total = self._total + report.testsRun self._failures = self._failures + len(report.failures) self._errors = self._errors + len(report.errors) self._success = self._total - self._failures - self._errors
python
def add_report(self, specification_name, report): self._reports[specification_name] = report self._total = self._total + report.testsRun self._failures = self._failures + len(report.failures) self._errors = self._errors + len(report.errors) self._success = self._total - self._failures - self._errors
[ "def", "add_report", "(", "self", ",", "specification_name", ",", "report", ")", ":", "self", ".", "_reports", "[", "specification_name", "]", "=", "report", "self", ".", "_total", "=", "self", ".", "_total", "+", "report", ".", "testsRun", "self", ".", "_failures", "=", "self", ".", "_failures", "+", "len", "(", "report", ".", "failures", ")", "self", ".", "_errors", "=", "self", ".", "_errors", "+", "len", "(", "report", ".", "errors", ")", "self", ".", "_success", "=", "self", ".", "_total", "-", "self", ".", "_failures", "-", "self", ".", "_errors" ]
Adds a given report with the given specification_name as key to the reports list and computes the number of success, failures and errors Args: specification_name: string representing the specification (with ".spec") report: The
[ "Adds", "a", "given", "report", "with", "the", "given", "specification_name", "as", "key", "to", "the", "reports", "list", "and", "computes", "the", "number", "of", "success", "failures", "and", "errors" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/courgette/result.py#L67-L82
4,061
nuagenetworks/monolithe
monolithe/lib/sdkutils.py
SDKUtils.massage_type_name
def massage_type_name(cls, type_name): """ Returns a readable type according to a java type """ if type_name.lower() in ("enum", "enumeration"): return "enum" if type_name.lower() in ("str", "string"): return "string" if type_name.lower() in ("boolean", "bool"): return "boolean" if type_name.lower() in ("int", "integer"): return "integer" if type_name.lower() in ("date", "datetime", "time"): return "time" if type_name.lower() in ("double", "float", "long"): return "float" if type_name.lower() in ("list", "array"): return "list" if type_name.lower() in ("object", "dict"): return "object" if "array" in type_name.lower(): return "list" return "string"
python
def massage_type_name(cls, type_name): if type_name.lower() in ("enum", "enumeration"): return "enum" if type_name.lower() in ("str", "string"): return "string" if type_name.lower() in ("boolean", "bool"): return "boolean" if type_name.lower() in ("int", "integer"): return "integer" if type_name.lower() in ("date", "datetime", "time"): return "time" if type_name.lower() in ("double", "float", "long"): return "float" if type_name.lower() in ("list", "array"): return "list" if type_name.lower() in ("object", "dict"): return "object" if "array" in type_name.lower(): return "list" return "string"
[ "def", "massage_type_name", "(", "cls", ",", "type_name", ")", ":", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"enum\"", ",", "\"enumeration\"", ")", ":", "return", "\"enum\"", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"str\"", ",", "\"string\"", ")", ":", "return", "\"string\"", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"boolean\"", ",", "\"bool\"", ")", ":", "return", "\"boolean\"", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"int\"", ",", "\"integer\"", ")", ":", "return", "\"integer\"", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"date\"", ",", "\"datetime\"", ",", "\"time\"", ")", ":", "return", "\"time\"", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"double\"", ",", "\"float\"", ",", "\"long\"", ")", ":", "return", "\"float\"", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"list\"", ",", "\"array\"", ")", ":", "return", "\"list\"", "if", "type_name", ".", "lower", "(", ")", "in", "(", "\"object\"", ",", "\"dict\"", ")", ":", "return", "\"object\"", "if", "\"array\"", "in", "type_name", ".", "lower", "(", ")", ":", "return", "\"list\"", "return", "\"string\"" ]
Returns a readable type according to a java type
[ "Returns", "a", "readable", "type", "according", "to", "a", "java", "type" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/lib/sdkutils.py#L44-L75
4,062
nuagenetworks/monolithe
monolithe/lib/sdkutils.py
SDKUtils.get_idiomatic_name_in_language
def get_idiomatic_name_in_language(cls, name, language): """ Get the name for the given language Args: name (str): the name to convert language (str): the language to use Returns: a name in the given language Example: get_idiomatic_name_in_language("EnterpriseNetwork", "python") >>> enterprise_network """ if language in cls.idiomatic_methods_cache: m = cls.idiomatic_methods_cache[language] if not m: return name return m(name) found, method = load_language_plugins(language, 'get_idiomatic_name') if found: cls.idiomatic_methods_cache[language] = method if method: return method(name) else: return name module = importlib.import_module('.lang.%s' % language, package="monolithe.generators") if not hasattr(module, 'get_idiomatic_name'): cls.idiomatic_methods_cache[language] = None return name method = getattr(module, 'get_idiomatic_name') cls.idiomatic_methods_cache[language] = method return method(name)
python
def get_idiomatic_name_in_language(cls, name, language): if language in cls.idiomatic_methods_cache: m = cls.idiomatic_methods_cache[language] if not m: return name return m(name) found, method = load_language_plugins(language, 'get_idiomatic_name') if found: cls.idiomatic_methods_cache[language] = method if method: return method(name) else: return name module = importlib.import_module('.lang.%s' % language, package="monolithe.generators") if not hasattr(module, 'get_idiomatic_name'): cls.idiomatic_methods_cache[language] = None return name method = getattr(module, 'get_idiomatic_name') cls.idiomatic_methods_cache[language] = method return method(name)
[ "def", "get_idiomatic_name_in_language", "(", "cls", ",", "name", ",", "language", ")", ":", "if", "language", "in", "cls", ".", "idiomatic_methods_cache", ":", "m", "=", "cls", ".", "idiomatic_methods_cache", "[", "language", "]", "if", "not", "m", ":", "return", "name", "return", "m", "(", "name", ")", "found", ",", "method", "=", "load_language_plugins", "(", "language", ",", "'get_idiomatic_name'", ")", "if", "found", ":", "cls", ".", "idiomatic_methods_cache", "[", "language", "]", "=", "method", "if", "method", ":", "return", "method", "(", "name", ")", "else", ":", "return", "name", "module", "=", "importlib", ".", "import_module", "(", "'.lang.%s'", "%", "language", ",", "package", "=", "\"monolithe.generators\"", ")", "if", "not", "hasattr", "(", "module", ",", "'get_idiomatic_name'", ")", ":", "cls", ".", "idiomatic_methods_cache", "[", "language", "]", "=", "None", "return", "name", "method", "=", "getattr", "(", "module", ",", "'get_idiomatic_name'", ")", "cls", ".", "idiomatic_methods_cache", "[", "language", "]", "=", "method", "return", "method", "(", "name", ")" ]
Get the name for the given language Args: name (str): the name to convert language (str): the language to use Returns: a name in the given language Example: get_idiomatic_name_in_language("EnterpriseNetwork", "python") >>> enterprise_network
[ "Get", "the", "name", "for", "the", "given", "language" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/lib/sdkutils.py#L141-L177
4,063
nuagenetworks/monolithe
monolithe/lib/sdkutils.py
SDKUtils.get_type_name_in_language
def get_type_name_in_language(cls, type_name, sub_type, language): """ Get the type for the given language Args: type_name (str): the type to convert language (str): the language to use Returns: a type name in the given language Example: get_type_name_in_language("Varchar", "python") >>> str """ if language in cls.type_methods_cache: m = cls.type_methods_cache[language] if not m: return type_name return m(type_name) found, method = load_language_plugins(language, 'get_type_name') if found: cls.type_methods_cache[language] = method if method: return method(type_name, sub_type) else: return type_name module = importlib.import_module('.lang.%s' % language, package="monolithe.generators") if not hasattr(module, 'get_type_name'): cls.type_methods_cache[language] = None return type_name method = getattr(module, 'get_type_name') cls.type_methods_cache[language] = method return method(type_name, sub_type)
python
def get_type_name_in_language(cls, type_name, sub_type, language): if language in cls.type_methods_cache: m = cls.type_methods_cache[language] if not m: return type_name return m(type_name) found, method = load_language_plugins(language, 'get_type_name') if found: cls.type_methods_cache[language] = method if method: return method(type_name, sub_type) else: return type_name module = importlib.import_module('.lang.%s' % language, package="monolithe.generators") if not hasattr(module, 'get_type_name'): cls.type_methods_cache[language] = None return type_name method = getattr(module, 'get_type_name') cls.type_methods_cache[language] = method return method(type_name, sub_type)
[ "def", "get_type_name_in_language", "(", "cls", ",", "type_name", ",", "sub_type", ",", "language", ")", ":", "if", "language", "in", "cls", ".", "type_methods_cache", ":", "m", "=", "cls", ".", "type_methods_cache", "[", "language", "]", "if", "not", "m", ":", "return", "type_name", "return", "m", "(", "type_name", ")", "found", ",", "method", "=", "load_language_plugins", "(", "language", ",", "'get_type_name'", ")", "if", "found", ":", "cls", ".", "type_methods_cache", "[", "language", "]", "=", "method", "if", "method", ":", "return", "method", "(", "type_name", ",", "sub_type", ")", "else", ":", "return", "type_name", "module", "=", "importlib", ".", "import_module", "(", "'.lang.%s'", "%", "language", ",", "package", "=", "\"monolithe.generators\"", ")", "if", "not", "hasattr", "(", "module", ",", "'get_type_name'", ")", ":", "cls", ".", "type_methods_cache", "[", "language", "]", "=", "None", "return", "type_name", "method", "=", "getattr", "(", "module", ",", "'get_type_name'", ")", "cls", ".", "type_methods_cache", "[", "language", "]", "=", "method", "return", "method", "(", "type_name", ",", "sub_type", ")" ]
Get the type for the given language Args: type_name (str): the type to convert language (str): the language to use Returns: a type name in the given language Example: get_type_name_in_language("Varchar", "python") >>> str
[ "Get", "the", "type", "for", "the", "given", "language" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/lib/sdkutils.py#L180-L216
4,064
nuagenetworks/monolithe
monolithe/generators/lang/go/converter.py
get_type_name
def get_type_name(type_name, sub_type=None): """ Returns a go type according to a spec type """ if type_name in ("string", "enum"): return "string" if type_name == "float": return "float64" if type_name == "boolean": return "bool" if type_name == "list": st = get_type_name(type_name=sub_type, sub_type=None) if sub_type else "interface{}" return "[]%s" % st if type_name == "integer": return "int" if type_name == "time": return "float64" return "interface{}"
python
def get_type_name(type_name, sub_type=None): if type_name in ("string", "enum"): return "string" if type_name == "float": return "float64" if type_name == "boolean": return "bool" if type_name == "list": st = get_type_name(type_name=sub_type, sub_type=None) if sub_type else "interface{}" return "[]%s" % st if type_name == "integer": return "int" if type_name == "time": return "float64" return "interface{}"
[ "def", "get_type_name", "(", "type_name", ",", "sub_type", "=", "None", ")", ":", "if", "type_name", "in", "(", "\"string\"", ",", "\"enum\"", ")", ":", "return", "\"string\"", "if", "type_name", "==", "\"float\"", ":", "return", "\"float64\"", "if", "type_name", "==", "\"boolean\"", ":", "return", "\"bool\"", "if", "type_name", "==", "\"list\"", ":", "st", "=", "get_type_name", "(", "type_name", "=", "sub_type", ",", "sub_type", "=", "None", ")", "if", "sub_type", "else", "\"interface{}\"", "return", "\"[]%s\"", "%", "st", "if", "type_name", "==", "\"integer\"", ":", "return", "\"int\"", "if", "type_name", "==", "\"time\"", ":", "return", "\"float64\"", "return", "\"interface{}\"" ]
Returns a go type according to a spec type
[ "Returns", "a", "go", "type", "according", "to", "a", "spec", "type" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/go/converter.py#L29-L52
4,065
nuagenetworks/monolithe
monolithe/generators/lang/csharp/writers/apiversionwriter.py
APIVersionWriter._write_info
def _write_info(self): """ Write API Info file """ self.write(destination=self.output_directory, filename="vspk/SdkInfo.cs", template_name="sdkinfo.cs.tpl", version=self.api_version, product_accronym=self._product_accronym, class_prefix=self._class_prefix, root_api=self.api_root, api_prefix=self.api_prefix, product_name=self._product_name, name=self._name, header=self.header_content, version_string=self._api_version_string, package_name=self._package_name)
python
def _write_info(self): self.write(destination=self.output_directory, filename="vspk/SdkInfo.cs", template_name="sdkinfo.cs.tpl", version=self.api_version, product_accronym=self._product_accronym, class_prefix=self._class_prefix, root_api=self.api_root, api_prefix=self.api_prefix, product_name=self._product_name, name=self._name, header=self.header_content, version_string=self._api_version_string, package_name=self._package_name)
[ "def", "_write_info", "(", "self", ")", ":", "self", ".", "write", "(", "destination", "=", "self", ".", "output_directory", ",", "filename", "=", "\"vspk/SdkInfo.cs\"", ",", "template_name", "=", "\"sdkinfo.cs.tpl\"", ",", "version", "=", "self", ".", "api_version", ",", "product_accronym", "=", "self", ".", "_product_accronym", ",", "class_prefix", "=", "self", ".", "_class_prefix", ",", "root_api", "=", "self", ".", "api_root", ",", "api_prefix", "=", "self", ".", "api_prefix", ",", "product_name", "=", "self", ".", "_product_name", ",", "name", "=", "self", ".", "_name", ",", "header", "=", "self", ".", "header_content", ",", "version_string", "=", "self", ".", "_api_version_string", ",", "package_name", "=", "self", ".", "_package_name", ")" ]
Write API Info file
[ "Write", "API", "Info", "file" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/csharp/writers/apiversionwriter.py#L125-L140
4,066
nuagenetworks/monolithe
monolithe/specifications/specification_attribute.py
SpecificationAttribute.to_dict
def to_dict(self): """ Transform an attribute to a dict """ data = {} # mandatory characteristics data["name"] = self.name data["description"] = self.description if self.description and len(self.description) else None data["type"] = self.type if self.type and len(self.type) else None data["allowed_chars"] = self.allowed_chars if self.allowed_chars and len(self.allowed_chars) else None data["allowed_choices"] = self.allowed_choices data["autogenerated"] = self.autogenerated data["channel"] = self.channel if self.channel and len(self.channel) else None data["creation_only"] = self.creation_only data["default_order"] = self.default_order data["default_value"] = self.default_value if self.default_value and len(self.default_value) else None data["deprecated"] = self.deprecated data["exposed"] = self.exposed data["filterable"] = self.filterable data["format"] = self.format if self.format and len(self.format) else None data["max_length"] = int(self.max_length) if self.max_length is not None else None data["max_value"] = int(self.max_value) if self.max_value is not None else None data["min_length"] = int(self.min_length) if self.min_length is not None else None data["min_value"] = int(self.min_value) if self.min_value is not None else None data["orderable"] = self.orderable data["read_only"] = self.read_only data["required"] = self.required data["transient"] = self.transient data["unique"] = self.unique data["uniqueScope"] = self.unique_scope if self.unique_scope and len(self.unique_scope) else None data["subtype"] = self.subtype if self.subtype and len(self.subtype) else None data["userlabel"] = self.userlabel if self.userlabel and len(self.userlabel) else None return data
python
def to_dict(self): data = {} # mandatory characteristics data["name"] = self.name data["description"] = self.description if self.description and len(self.description) else None data["type"] = self.type if self.type and len(self.type) else None data["allowed_chars"] = self.allowed_chars if self.allowed_chars and len(self.allowed_chars) else None data["allowed_choices"] = self.allowed_choices data["autogenerated"] = self.autogenerated data["channel"] = self.channel if self.channel and len(self.channel) else None data["creation_only"] = self.creation_only data["default_order"] = self.default_order data["default_value"] = self.default_value if self.default_value and len(self.default_value) else None data["deprecated"] = self.deprecated data["exposed"] = self.exposed data["filterable"] = self.filterable data["format"] = self.format if self.format and len(self.format) else None data["max_length"] = int(self.max_length) if self.max_length is not None else None data["max_value"] = int(self.max_value) if self.max_value is not None else None data["min_length"] = int(self.min_length) if self.min_length is not None else None data["min_value"] = int(self.min_value) if self.min_value is not None else None data["orderable"] = self.orderable data["read_only"] = self.read_only data["required"] = self.required data["transient"] = self.transient data["unique"] = self.unique data["uniqueScope"] = self.unique_scope if self.unique_scope and len(self.unique_scope) else None data["subtype"] = self.subtype if self.subtype and len(self.subtype) else None data["userlabel"] = self.userlabel if self.userlabel and len(self.userlabel) else None return data
[ "def", "to_dict", "(", "self", ")", ":", "data", "=", "{", "}", "# mandatory characteristics", "data", "[", "\"name\"", "]", "=", "self", ".", "name", "data", "[", "\"description\"", "]", "=", "self", ".", "description", "if", "self", ".", "description", "and", "len", "(", "self", ".", "description", ")", "else", "None", "data", "[", "\"type\"", "]", "=", "self", ".", "type", "if", "self", ".", "type", "and", "len", "(", "self", ".", "type", ")", "else", "None", "data", "[", "\"allowed_chars\"", "]", "=", "self", ".", "allowed_chars", "if", "self", ".", "allowed_chars", "and", "len", "(", "self", ".", "allowed_chars", ")", "else", "None", "data", "[", "\"allowed_choices\"", "]", "=", "self", ".", "allowed_choices", "data", "[", "\"autogenerated\"", "]", "=", "self", ".", "autogenerated", "data", "[", "\"channel\"", "]", "=", "self", ".", "channel", "if", "self", ".", "channel", "and", "len", "(", "self", ".", "channel", ")", "else", "None", "data", "[", "\"creation_only\"", "]", "=", "self", ".", "creation_only", "data", "[", "\"default_order\"", "]", "=", "self", ".", "default_order", "data", "[", "\"default_value\"", "]", "=", "self", ".", "default_value", "if", "self", ".", "default_value", "and", "len", "(", "self", ".", "default_value", ")", "else", "None", "data", "[", "\"deprecated\"", "]", "=", "self", ".", "deprecated", "data", "[", "\"exposed\"", "]", "=", "self", ".", "exposed", "data", "[", "\"filterable\"", "]", "=", "self", ".", "filterable", "data", "[", "\"format\"", "]", "=", "self", ".", "format", "if", "self", ".", "format", "and", "len", "(", "self", ".", "format", ")", "else", "None", "data", "[", "\"max_length\"", "]", "=", "int", "(", "self", ".", "max_length", ")", "if", "self", ".", "max_length", "is", "not", "None", "else", "None", "data", "[", "\"max_value\"", "]", "=", "int", "(", "self", ".", "max_value", ")", "if", "self", ".", "max_value", "is", "not", "None", "else", "None", "data", "[", "\"min_length\"", "]", "=", "int", "(", "self", ".", "min_length", ")", "if", "self", ".", "min_length", "is", "not", "None", "else", "None", "data", "[", "\"min_value\"", "]", "=", "int", "(", "self", ".", "min_value", ")", "if", "self", ".", "min_value", "is", "not", "None", "else", "None", "data", "[", "\"orderable\"", "]", "=", "self", ".", "orderable", "data", "[", "\"read_only\"", "]", "=", "self", ".", "read_only", "data", "[", "\"required\"", "]", "=", "self", ".", "required", "data", "[", "\"transient\"", "]", "=", "self", ".", "transient", "data", "[", "\"unique\"", "]", "=", "self", ".", "unique", "data", "[", "\"uniqueScope\"", "]", "=", "self", ".", "unique_scope", "if", "self", ".", "unique_scope", "and", "len", "(", "self", ".", "unique_scope", ")", "else", "None", "data", "[", "\"subtype\"", "]", "=", "self", ".", "subtype", "if", "self", ".", "subtype", "and", "len", "(", "self", ".", "subtype", ")", "else", "None", "data", "[", "\"userlabel\"", "]", "=", "self", ".", "userlabel", "if", "self", ".", "userlabel", "and", "len", "(", "self", ".", "userlabel", ")", "else", "None", "return", "data" ]
Transform an attribute to a dict
[ "Transform", "an", "attribute", "to", "a", "dict" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/specifications/specification_attribute.py#L158-L191
4,067
nuagenetworks/monolithe
monolithe/generators/lib/templatefilewriter.py
_FileWriter.write
def write(self, destination, filename, content): """ Write a file at the specific destination with the content. Args: destination (string): the destination location filename (string): the filename that will be written content (string): the content of the filename """ if not os.path.exists(destination): try: os.makedirs(destination) except: # The directory can be created while creating it. pass filepath = "%s/%s" % (destination, filename) f = open(filepath, "w+") f.write(content) f.close()
python
def write(self, destination, filename, content): if not os.path.exists(destination): try: os.makedirs(destination) except: # The directory can be created while creating it. pass filepath = "%s/%s" % (destination, filename) f = open(filepath, "w+") f.write(content) f.close()
[ "def", "write", "(", "self", ",", "destination", ",", "filename", ",", "content", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "destination", ")", ":", "try", ":", "os", ".", "makedirs", "(", "destination", ")", "except", ":", "# The directory can be created while creating it.", "pass", "filepath", "=", "\"%s/%s\"", "%", "(", "destination", ",", "filename", ")", "f", "=", "open", "(", "filepath", ",", "\"w+\"", ")", "f", ".", "write", "(", "content", ")", "f", ".", "close", "(", ")" ]
Write a file at the specific destination with the content. Args: destination (string): the destination location filename (string): the filename that will be written content (string): the content of the filename
[ "Write", "a", "file", "at", "the", "specific", "destination", "with", "the", "content", "." ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lib/templatefilewriter.py#L39-L58
4,068
nuagenetworks/monolithe
monolithe/generators/lib/templatefilewriter.py
TemplateFileWriter.write
def write(self, destination, filename, template_name, **kwargs): """ Write a file according to the template name Args: destination (string): the destination location filename (string): the filename that will be written template_name (string): the name of the template kwargs (dict): all attribute that will be passed to the template """ template = self.env.get_template(template_name) content = template.render(kwargs) super(TemplateFileWriter, self).write(destination=destination, filename=filename, content=content)
python
def write(self, destination, filename, template_name, **kwargs): template = self.env.get_template(template_name) content = template.render(kwargs) super(TemplateFileWriter, self).write(destination=destination, filename=filename, content=content)
[ "def", "write", "(", "self", ",", "destination", ",", "filename", ",", "template_name", ",", "*", "*", "kwargs", ")", ":", "template", "=", "self", ".", "env", ".", "get_template", "(", "template_name", ")", "content", "=", "template", ".", "render", "(", "kwargs", ")", "super", "(", "TemplateFileWriter", ",", "self", ")", ".", "write", "(", "destination", "=", "destination", ",", "filename", "=", "filename", ",", "content", "=", "content", ")" ]
Write a file according to the template name Args: destination (string): the destination location filename (string): the filename that will be written template_name (string): the name of the template kwargs (dict): all attribute that will be passed to the template
[ "Write", "a", "file", "according", "to", "the", "template", "name" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lib/templatefilewriter.py#L76-L87
4,069
nuagenetworks/monolithe
monolithe/generators/lang/python/writers/apiversionwriter.py
APIVersionWriter._write_session
def _write_session(self): """ Write SDK session file Args: version (str): the version of the server """ base_name = "%ssession" % self._product_accronym.lower() filename = "%s%s.py" % (self._class_prefix.lower(), base_name) override_content = self._extract_override_content(base_name) self.write(destination=self.output_directory, filename=filename, template_name="session.py.tpl", version=self.api_version, product_accronym=self._product_accronym, class_prefix=self._class_prefix, root_api=self.api_root, api_prefix=self.api_prefix, override_content=override_content, header=self.header_content)
python
def _write_session(self): base_name = "%ssession" % self._product_accronym.lower() filename = "%s%s.py" % (self._class_prefix.lower(), base_name) override_content = self._extract_override_content(base_name) self.write(destination=self.output_directory, filename=filename, template_name="session.py.tpl", version=self.api_version, product_accronym=self._product_accronym, class_prefix=self._class_prefix, root_api=self.api_root, api_prefix=self.api_prefix, override_content=override_content, header=self.header_content)
[ "def", "_write_session", "(", "self", ")", ":", "base_name", "=", "\"%ssession\"", "%", "self", ".", "_product_accronym", ".", "lower", "(", ")", "filename", "=", "\"%s%s.py\"", "%", "(", "self", ".", "_class_prefix", ".", "lower", "(", ")", ",", "base_name", ")", "override_content", "=", "self", ".", "_extract_override_content", "(", "base_name", ")", "self", ".", "write", "(", "destination", "=", "self", ".", "output_directory", ",", "filename", "=", "filename", ",", "template_name", "=", "\"session.py.tpl\"", ",", "version", "=", "self", ".", "api_version", ",", "product_accronym", "=", "self", ".", "_product_accronym", ",", "class_prefix", "=", "self", ".", "_class_prefix", ",", "root_api", "=", "self", ".", "api_root", ",", "api_prefix", "=", "self", ".", "api_prefix", ",", "override_content", "=", "override_content", ",", "header", "=", "self", ".", "header_content", ")" ]
Write SDK session file Args: version (str): the version of the server
[ "Write", "SDK", "session", "file" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/python/writers/apiversionwriter.py#L84-L102
4,070
nuagenetworks/monolithe
monolithe/generators/lang/python/writers/apiversionwriter.py
APIVersionWriter._write_init_models
def _write_init_models(self, filenames): """ Write init file Args: filenames (dict): dict of filename and classes """ self.write(destination=self.output_directory, filename="__init__.py", template_name="__init_model__.py.tpl", filenames=self._prepare_filenames(filenames), class_prefix=self._class_prefix, product_accronym=self._product_accronym, header=self.header_content)
python
def _write_init_models(self, filenames): self.write(destination=self.output_directory, filename="__init__.py", template_name="__init_model__.py.tpl", filenames=self._prepare_filenames(filenames), class_prefix=self._class_prefix, product_accronym=self._product_accronym, header=self.header_content)
[ "def", "_write_init_models", "(", "self", ",", "filenames", ")", ":", "self", ".", "write", "(", "destination", "=", "self", ".", "output_directory", ",", "filename", "=", "\"__init__.py\"", ",", "template_name", "=", "\"__init_model__.py.tpl\"", ",", "filenames", "=", "self", ".", "_prepare_filenames", "(", "filenames", ")", ",", "class_prefix", "=", "self", ".", "_class_prefix", ",", "product_accronym", "=", "self", ".", "_product_accronym", ",", "header", "=", "self", ".", "header_content", ")" ]
Write init file Args: filenames (dict): dict of filename and classes
[ "Write", "init", "file" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/python/writers/apiversionwriter.py#L117-L129
4,071
nuagenetworks/monolithe
monolithe/generators/lang/python/writers/apiversionwriter.py
APIVersionWriter._write_init_fetchers
def _write_init_fetchers(self, filenames): """ Write fetcher init file Args: filenames (dict): dict of filename and classes """ destination = "%s%s" % (self.output_directory, self.fetchers_path) self.write(destination=destination, filename="__init__.py", template_name="__init_fetcher__.py.tpl", filenames=self._prepare_filenames(filenames, suffix='Fetcher'), class_prefix=self._class_prefix, product_accronym=self._product_accronym, header=self.header_content)
python
def _write_init_fetchers(self, filenames): destination = "%s%s" % (self.output_directory, self.fetchers_path) self.write(destination=destination, filename="__init__.py", template_name="__init_fetcher__.py.tpl", filenames=self._prepare_filenames(filenames, suffix='Fetcher'), class_prefix=self._class_prefix, product_accronym=self._product_accronym, header=self.header_content)
[ "def", "_write_init_fetchers", "(", "self", ",", "filenames", ")", ":", "destination", "=", "\"%s%s\"", "%", "(", "self", ".", "output_directory", ",", "self", ".", "fetchers_path", ")", "self", ".", "write", "(", "destination", "=", "destination", ",", "filename", "=", "\"__init__.py\"", ",", "template_name", "=", "\"__init_fetcher__.py.tpl\"", ",", "filenames", "=", "self", ".", "_prepare_filenames", "(", "filenames", ",", "suffix", "=", "'Fetcher'", ")", ",", "class_prefix", "=", "self", ".", "_class_prefix", ",", "product_accronym", "=", "self", ".", "_product_accronym", ",", "header", "=", "self", ".", "header_content", ")" ]
Write fetcher init file Args: filenames (dict): dict of filename and classes
[ "Write", "fetcher", "init", "file" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/python/writers/apiversionwriter.py#L164-L176
4,072
nuagenetworks/monolithe
monolithe/generators/lang/python/writers/apiversionwriter.py
APIVersionWriter._extract_constants
def _extract_constants(self, specification): """ Removes attributes and computes constants """ constants = {} for attribute in specification.attributes: if attribute.allowed_choices and len(attribute.allowed_choices) > 0: name = attribute.local_name.upper() for choice in attribute.allowed_choices: constants["CONST_%s_%s" % (name, choice.upper())] = choice return constants
python
def _extract_constants(self, specification): constants = {} for attribute in specification.attributes: if attribute.allowed_choices and len(attribute.allowed_choices) > 0: name = attribute.local_name.upper() for choice in attribute.allowed_choices: constants["CONST_%s_%s" % (name, choice.upper())] = choice return constants
[ "def", "_extract_constants", "(", "self", ",", "specification", ")", ":", "constants", "=", "{", "}", "for", "attribute", "in", "specification", ".", "attributes", ":", "if", "attribute", ".", "allowed_choices", "and", "len", "(", "attribute", ".", "allowed_choices", ")", ">", "0", ":", "name", "=", "attribute", ".", "local_name", ".", "upper", "(", ")", "for", "choice", "in", "attribute", ".", "allowed_choices", ":", "constants", "[", "\"CONST_%s_%s\"", "%", "(", "name", ",", "choice", ".", "upper", "(", ")", ")", "]", "=", "choice", "return", "constants" ]
Removes attributes and computes constants
[ "Removes", "attributes", "and", "computes", "constants" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/generators/lang/python/writers/apiversionwriter.py#L244-L259
4,073
nuagenetworks/monolithe
monolithe/courgette/courgette.py
Courgette.run
def run(self, configurations): """ Run all tests Returns: A dictionnary containing tests results. """ result = CourgetteResult() for configuration in configurations: runner = CourgetteTestsRunner(url=self.url, username=self.username, password=self.password, enterprise=self.enterprise, version=self.apiversion, specification=configuration.specification, sdk_identifier=self.sdk_identifier, monolithe_config=self.monolithe_config, parent_resource=configuration.parent_resource_name, parent_id=configuration.parent_id, default_values=configuration.default_values) result.add_report(configuration.specification.rest_name + ".spec", runner.run()) return result
python
def run(self, configurations): result = CourgetteResult() for configuration in configurations: runner = CourgetteTestsRunner(url=self.url, username=self.username, password=self.password, enterprise=self.enterprise, version=self.apiversion, specification=configuration.specification, sdk_identifier=self.sdk_identifier, monolithe_config=self.monolithe_config, parent_resource=configuration.parent_resource_name, parent_id=configuration.parent_id, default_values=configuration.default_values) result.add_report(configuration.specification.rest_name + ".spec", runner.run()) return result
[ "def", "run", "(", "self", ",", "configurations", ")", ":", "result", "=", "CourgetteResult", "(", ")", "for", "configuration", "in", "configurations", ":", "runner", "=", "CourgetteTestsRunner", "(", "url", "=", "self", ".", "url", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "enterprise", "=", "self", ".", "enterprise", ",", "version", "=", "self", ".", "apiversion", ",", "specification", "=", "configuration", ".", "specification", ",", "sdk_identifier", "=", "self", ".", "sdk_identifier", ",", "monolithe_config", "=", "self", ".", "monolithe_config", ",", "parent_resource", "=", "configuration", ".", "parent_resource_name", ",", "parent_id", "=", "configuration", ".", "parent_id", ",", "default_values", "=", "configuration", ".", "default_values", ")", "result", ".", "add_report", "(", "configuration", ".", "specification", ".", "rest_name", "+", "\".spec\"", ",", "runner", ".", "run", "(", ")", ")", "return", "result" ]
Run all tests Returns: A dictionnary containing tests results.
[ "Run", "all", "tests" ]
626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/courgette/courgette.py#L57-L82
4,074
agiliq/django-graphos
graphos/utils.py
get_db
def get_db(db_name=None): """ GetDB - simple function to wrap getting a database connection from the connection pool. """ import pymongo return pymongo.Connection(host=DB_HOST, port=DB_PORT)[db_name]
python
def get_db(db_name=None): import pymongo return pymongo.Connection(host=DB_HOST, port=DB_PORT)[db_name]
[ "def", "get_db", "(", "db_name", "=", "None", ")", ":", "import", "pymongo", "return", "pymongo", ".", "Connection", "(", "host", "=", "DB_HOST", ",", "port", "=", "DB_PORT", ")", "[", "db_name", "]" ]
GetDB - simple function to wrap getting a database connection from the connection pool.
[ "GetDB", "-", "simple", "function", "to", "wrap", "getting", "a", "database", "connection", "from", "the", "connection", "pool", "." ]
2f11e98de8a51f808e536099e830b2fc3a508a6a
https://github.com/agiliq/django-graphos/blob/2f11e98de8a51f808e536099e830b2fc3a508a6a/graphos/utils.py#L35-L41
4,075
vstconsulting/vstutils
vstutils/api/doc_generator.py
VSTOpenApiBase.get_main_title
def get_main_title(self, path_name, request_name): ''' Get title, from request type and path :param path_name: --path for create title :type path_name: str, unicode :param request_name: --name of request :type request_name: str, unicode :return: ''' main_title = '.. http:{}:: {}'.format(request_name, path_name) self.write(main_title) self.write('')
python
def get_main_title(self, path_name, request_name): ''' Get title, from request type and path :param path_name: --path for create title :type path_name: str, unicode :param request_name: --name of request :type request_name: str, unicode :return: ''' main_title = '.. http:{}:: {}'.format(request_name, path_name) self.write(main_title) self.write('')
[ "def", "get_main_title", "(", "self", ",", "path_name", ",", "request_name", ")", ":", "main_title", "=", "'.. http:{}:: {}'", ".", "format", "(", "request_name", ",", "path_name", ")", "self", ".", "write", "(", "main_title", ")", "self", ".", "write", "(", "''", ")" ]
Get title, from request type and path :param path_name: --path for create title :type path_name: str, unicode :param request_name: --name of request :type request_name: str, unicode :return:
[ "Get", "title", "from", "request", "type", "and", "path" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/api/doc_generator.py#L153-L165
4,076
vstconsulting/vstutils
vstutils/api/doc_generator.py
VSTOpenApiBase.schema_handler
def schema_handler(self, schema): ''' Function prepare body of response with examples and create detailed information about response fields :param schema: --dictionary with information about answer :type schema: dict :return: ''' dict_for_render = schema.get('properties', dict()).items() if schema.get('$ref', None): def_name = schema.get('$ref').split('/')[-1] dict_for_render = self.definitions[def_name].get('properties', dict()).items() elif schema.get('properties', None) is None: return '' answer_dict = dict() json_dict = dict() for opt_name, opt_value in dict_for_render: var_type = opt_value.get('format', None) or opt_value.get('type', None) or 'object' json_name = self.indent + ':jsonparameter {} {}:'.format(var_type, opt_name) json_dict[json_name] = self.get_json_props_for_response(var_type, opt_value) answer_dict[opt_name] = self.get_response_example(opt_name, var_type, opt_value) if var_type == 'string': answer_dict[opt_name] = answer_dict[opt_name].format(opt_name) self.write('') for line in json.dumps(answer_dict, indent=4).split('\n'): self.write(line, self.indent_depth) self.write('') for json_param_name, json_param_value in json_dict.items(): desc = '{}{}'.format( json_param_value['title'], json_param_value['props_str'] ) or 'None' self.write(json_param_name + ' ' + desc)
python
def schema_handler(self, schema): ''' Function prepare body of response with examples and create detailed information about response fields :param schema: --dictionary with information about answer :type schema: dict :return: ''' dict_for_render = schema.get('properties', dict()).items() if schema.get('$ref', None): def_name = schema.get('$ref').split('/')[-1] dict_for_render = self.definitions[def_name].get('properties', dict()).items() elif schema.get('properties', None) is None: return '' answer_dict = dict() json_dict = dict() for opt_name, opt_value in dict_for_render: var_type = opt_value.get('format', None) or opt_value.get('type', None) or 'object' json_name = self.indent + ':jsonparameter {} {}:'.format(var_type, opt_name) json_dict[json_name] = self.get_json_props_for_response(var_type, opt_value) answer_dict[opt_name] = self.get_response_example(opt_name, var_type, opt_value) if var_type == 'string': answer_dict[opt_name] = answer_dict[opt_name].format(opt_name) self.write('') for line in json.dumps(answer_dict, indent=4).split('\n'): self.write(line, self.indent_depth) self.write('') for json_param_name, json_param_value in json_dict.items(): desc = '{}{}'.format( json_param_value['title'], json_param_value['props_str'] ) or 'None' self.write(json_param_name + ' ' + desc)
[ "def", "schema_handler", "(", "self", ",", "schema", ")", ":", "dict_for_render", "=", "schema", ".", "get", "(", "'properties'", ",", "dict", "(", ")", ")", ".", "items", "(", ")", "if", "schema", ".", "get", "(", "'$ref'", ",", "None", ")", ":", "def_name", "=", "schema", ".", "get", "(", "'$ref'", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "dict_for_render", "=", "self", ".", "definitions", "[", "def_name", "]", ".", "get", "(", "'properties'", ",", "dict", "(", ")", ")", ".", "items", "(", ")", "elif", "schema", ".", "get", "(", "'properties'", ",", "None", ")", "is", "None", ":", "return", "''", "answer_dict", "=", "dict", "(", ")", "json_dict", "=", "dict", "(", ")", "for", "opt_name", ",", "opt_value", "in", "dict_for_render", ":", "var_type", "=", "opt_value", ".", "get", "(", "'format'", ",", "None", ")", "or", "opt_value", ".", "get", "(", "'type'", ",", "None", ")", "or", "'object'", "json_name", "=", "self", ".", "indent", "+", "':jsonparameter {} {}:'", ".", "format", "(", "var_type", ",", "opt_name", ")", "json_dict", "[", "json_name", "]", "=", "self", ".", "get_json_props_for_response", "(", "var_type", ",", "opt_value", ")", "answer_dict", "[", "opt_name", "]", "=", "self", ".", "get_response_example", "(", "opt_name", ",", "var_type", ",", "opt_value", ")", "if", "var_type", "==", "'string'", ":", "answer_dict", "[", "opt_name", "]", "=", "answer_dict", "[", "opt_name", "]", ".", "format", "(", "opt_name", ")", "self", ".", "write", "(", "''", ")", "for", "line", "in", "json", ".", "dumps", "(", "answer_dict", ",", "indent", "=", "4", ")", ".", "split", "(", "'\\n'", ")", ":", "self", ".", "write", "(", "line", ",", "self", ".", "indent_depth", ")", "self", ".", "write", "(", "''", ")", "for", "json_param_name", ",", "json_param_value", "in", "json_dict", ".", "items", "(", ")", ":", "desc", "=", "'{}{}'", ".", "format", "(", "json_param_value", "[", "'title'", "]", ",", "json_param_value", "[", "'props_str'", "]", ")", "or", "'None'", "self", ".", "write", "(", "json_param_name", "+", "' '", "+", "desc", ")" ]
Function prepare body of response with examples and create detailed information about response fields :param schema: --dictionary with information about answer :type schema: dict :return:
[ "Function", "prepare", "body", "of", "response", "with", "examples", "and", "create", "detailed", "information", "about", "response", "fields" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/api/doc_generator.py#L195-L231
4,077
vstconsulting/vstutils
vstutils/api/doc_generator.py
VSTOpenApiBase.get_json_props_for_response
def get_json_props_for_response(self, var_type, option_value): ''' Prepare JSON section with detailed information about response :param var_type: --contains variable type :type var_type: , unicode :param option_value: --dictionary that contains information about property :type option_value: dict :return: dictionary that contains, title and all properties of field :rtype: dict ''' props = list() for name, value in option_value.items(): if var_type in ['dynamic', 'select2']: break elif name in ['format', 'title', 'type']: continue elif isinstance(value, dict) and value.get('$ref', None): props.append(':ref:`{}`'.format(value['$ref'].split('/')[-1])) elif '$ref' in name: props.append(':ref:`{}`'.format(value.split('/')[-1])) elif var_type == 'autocomplete': props.append('Example values: ' + ', '.join(value)) else: props.append('{}={}'.format(name, value)) if len(props): props_str = '(' + ', '.join(props) + ')' else: props_str = '' return dict(props_str=props_str, title=option_value.get('title', ''))
python
def get_json_props_for_response(self, var_type, option_value): ''' Prepare JSON section with detailed information about response :param var_type: --contains variable type :type var_type: , unicode :param option_value: --dictionary that contains information about property :type option_value: dict :return: dictionary that contains, title and all properties of field :rtype: dict ''' props = list() for name, value in option_value.items(): if var_type in ['dynamic', 'select2']: break elif name in ['format', 'title', 'type']: continue elif isinstance(value, dict) and value.get('$ref', None): props.append(':ref:`{}`'.format(value['$ref'].split('/')[-1])) elif '$ref' in name: props.append(':ref:`{}`'.format(value.split('/')[-1])) elif var_type == 'autocomplete': props.append('Example values: ' + ', '.join(value)) else: props.append('{}={}'.format(name, value)) if len(props): props_str = '(' + ', '.join(props) + ')' else: props_str = '' return dict(props_str=props_str, title=option_value.get('title', ''))
[ "def", "get_json_props_for_response", "(", "self", ",", "var_type", ",", "option_value", ")", ":", "props", "=", "list", "(", ")", "for", "name", ",", "value", "in", "option_value", ".", "items", "(", ")", ":", "if", "var_type", "in", "[", "'dynamic'", ",", "'select2'", "]", ":", "break", "elif", "name", "in", "[", "'format'", ",", "'title'", ",", "'type'", "]", ":", "continue", "elif", "isinstance", "(", "value", ",", "dict", ")", "and", "value", ".", "get", "(", "'$ref'", ",", "None", ")", ":", "props", ".", "append", "(", "':ref:`{}`'", ".", "format", "(", "value", "[", "'$ref'", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", ")", "elif", "'$ref'", "in", "name", ":", "props", ".", "append", "(", "':ref:`{}`'", ".", "format", "(", "value", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", ")", "elif", "var_type", "==", "'autocomplete'", ":", "props", ".", "append", "(", "'Example values: '", "+", "', '", ".", "join", "(", "value", ")", ")", "else", ":", "props", ".", "append", "(", "'{}={}'", ".", "format", "(", "name", ",", "value", ")", ")", "if", "len", "(", "props", ")", ":", "props_str", "=", "'('", "+", "', '", ".", "join", "(", "props", ")", "+", "')'", "else", ":", "props_str", "=", "''", "return", "dict", "(", "props_str", "=", "props_str", ",", "title", "=", "option_value", ".", "get", "(", "'title'", ",", "''", ")", ")" ]
Prepare JSON section with detailed information about response :param var_type: --contains variable type :type var_type: , unicode :param option_value: --dictionary that contains information about property :type option_value: dict :return: dictionary that contains, title and all properties of field :rtype: dict
[ "Prepare", "JSON", "section", "with", "detailed", "information", "about", "response" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/api/doc_generator.py#L233-L263
4,078
vstconsulting/vstutils
vstutils/api/doc_generator.py
VSTOpenApiBase.get_object_example
def get_object_example(self, def_name): ''' Create example for response, from object structure :param def_name: --deffinition name of structure :type def_name: str, unicode :return: example of object :rtype: dict ''' def_model = self.definitions[def_name] example = dict() for opt_name, opt_value in def_model.get('properties', dict()).items(): var_type = opt_value.get('format', None) or opt_value.get('type', None) example[opt_name] = self.get_response_example(opt_name, var_type, opt_value) if var_type == 'string': example[opt_name] = example[opt_name].format(opt_name) return example
python
def get_object_example(self, def_name): ''' Create example for response, from object structure :param def_name: --deffinition name of structure :type def_name: str, unicode :return: example of object :rtype: dict ''' def_model = self.definitions[def_name] example = dict() for opt_name, opt_value in def_model.get('properties', dict()).items(): var_type = opt_value.get('format', None) or opt_value.get('type', None) example[opt_name] = self.get_response_example(opt_name, var_type, opt_value) if var_type == 'string': example[opt_name] = example[opt_name].format(opt_name) return example
[ "def", "get_object_example", "(", "self", ",", "def_name", ")", ":", "def_model", "=", "self", ".", "definitions", "[", "def_name", "]", "example", "=", "dict", "(", ")", "for", "opt_name", ",", "opt_value", "in", "def_model", ".", "get", "(", "'properties'", ",", "dict", "(", ")", ")", ".", "items", "(", ")", ":", "var_type", "=", "opt_value", ".", "get", "(", "'format'", ",", "None", ")", "or", "opt_value", ".", "get", "(", "'type'", ",", "None", ")", "example", "[", "opt_name", "]", "=", "self", ".", "get_response_example", "(", "opt_name", ",", "var_type", ",", "opt_value", ")", "if", "var_type", "==", "'string'", ":", "example", "[", "opt_name", "]", "=", "example", "[", "opt_name", "]", ".", "format", "(", "opt_name", ")", "return", "example" ]
Create example for response, from object structure :param def_name: --deffinition name of structure :type def_name: str, unicode :return: example of object :rtype: dict
[ "Create", "example", "for", "response", "from", "object", "structure" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/api/doc_generator.py#L309-L325
4,079
vstconsulting/vstutils
vstutils/utils.py
get_render
def get_render(name, data, trans='en'): """ Render string based on template :param name: -- full template name :type name: str,unicode :param data: -- dict of rendered vars :type data: dict :param trans: -- translation for render. Default 'en'. :type trans: str,unicode :return: -- rendered string :rtype: str,unicode """ translation.activate(trans) config = loader.get_template(name) result = config.render(data).replace('\r', '') translation.deactivate() return result
python
def get_render(name, data, trans='en'): translation.activate(trans) config = loader.get_template(name) result = config.render(data).replace('\r', '') translation.deactivate() return result
[ "def", "get_render", "(", "name", ",", "data", ",", "trans", "=", "'en'", ")", ":", "translation", ".", "activate", "(", "trans", ")", "config", "=", "loader", ".", "get_template", "(", "name", ")", "result", "=", "config", ".", "render", "(", "data", ")", ".", "replace", "(", "'\\r'", ",", "''", ")", "translation", ".", "deactivate", "(", ")", "return", "result" ]
Render string based on template :param name: -- full template name :type name: str,unicode :param data: -- dict of rendered vars :type data: dict :param trans: -- translation for render. Default 'en'. :type trans: str,unicode :return: -- rendered string :rtype: str,unicode
[ "Render", "string", "based", "on", "template" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/utils.py#L30-L47
4,080
vstconsulting/vstutils
vstutils/utils.py
tmp_file.write
def write(self, wr_string): """ Write to file and flush :param wr_string: -- writable string :type wr_string: str :return: None :rtype: None """ result = self.fd.write(wr_string) self.fd.flush() return result
python
def write(self, wr_string): result = self.fd.write(wr_string) self.fd.flush() return result
[ "def", "write", "(", "self", ",", "wr_string", ")", ":", "result", "=", "self", ".", "fd", ".", "write", "(", "wr_string", ")", "self", ".", "fd", ".", "flush", "(", ")", "return", "result" ]
Write to file and flush :param wr_string: -- writable string :type wr_string: str :return: None :rtype: None
[ "Write", "to", "file", "and", "flush" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/utils.py#L154-L165
4,081
vstconsulting/vstutils
vstutils/utils.py
BaseVstObject.get_django_settings
def get_django_settings(cls, name, default=None): # pylint: disable=access-member-before-definition """ Get params from Django settings. :param name: name of param :type name: str,unicode :param default: default value of param :type default: object :return: Param from Django settings or default. """ if hasattr(cls, '__django_settings__'): return getattr(cls.__django_settings__, name, default) from django.conf import settings cls.__django_settings__ = settings return cls.get_django_settings(name)
python
def get_django_settings(cls, name, default=None): # pylint: disable=access-member-before-definition if hasattr(cls, '__django_settings__'): return getattr(cls.__django_settings__, name, default) from django.conf import settings cls.__django_settings__ = settings return cls.get_django_settings(name)
[ "def", "get_django_settings", "(", "cls", ",", "name", ",", "default", "=", "None", ")", ":", "# pylint: disable=access-member-before-definition", "if", "hasattr", "(", "cls", ",", "'__django_settings__'", ")", ":", "return", "getattr", "(", "cls", ".", "__django_settings__", ",", "name", ",", "default", ")", "from", "django", ".", "conf", "import", "settings", "cls", ".", "__django_settings__", "=", "settings", "return", "cls", ".", "get_django_settings", "(", "name", ")" ]
Get params from Django settings. :param name: name of param :type name: str,unicode :param default: default value of param :type default: object :return: Param from Django settings or default.
[ "Get", "params", "from", "Django", "settings", "." ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/utils.py#L270-L285
4,082
vstconsulting/vstutils
vstutils/utils.py
Executor._unbuffered
def _unbuffered(self, proc, stream='stdout'): """ Unbuffered output handler. :type proc: subprocess.Popen :type stream: six.text_types :return: """ if self.working_handler is not None: t = Thread(target=self._handle_process, args=(proc, stream)) t.start() out = getattr(proc, stream) try: for line in iter(out.readline, ""): yield line.rstrip() finally: out.close()
python
def _unbuffered(self, proc, stream='stdout'): if self.working_handler is not None: t = Thread(target=self._handle_process, args=(proc, stream)) t.start() out = getattr(proc, stream) try: for line in iter(out.readline, ""): yield line.rstrip() finally: out.close()
[ "def", "_unbuffered", "(", "self", ",", "proc", ",", "stream", "=", "'stdout'", ")", ":", "if", "self", ".", "working_handler", "is", "not", "None", ":", "t", "=", "Thread", "(", "target", "=", "self", ".", "_handle_process", ",", "args", "=", "(", "proc", ",", "stream", ")", ")", "t", ".", "start", "(", ")", "out", "=", "getattr", "(", "proc", ",", "stream", ")", "try", ":", "for", "line", "in", "iter", "(", "out", ".", "readline", ",", "\"\"", ")", ":", "yield", "line", ".", "rstrip", "(", ")", "finally", ":", "out", ".", "close", "(", ")" ]
Unbuffered output handler. :type proc: subprocess.Popen :type stream: six.text_types :return:
[ "Unbuffered", "output", "handler", "." ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/utils.py#L341-L357
4,083
vstconsulting/vstutils
vstutils/utils.py
Executor.execute
def execute(self, cmd, cwd): """ Execute commands and output this :param cmd: -- list of cmd command and arguments :type cmd: list :param cwd: -- workdir for executions :type cwd: str,unicode :return: -- string with full output :rtype: str """ self.output = "" env = os.environ.copy() env.update(self.env) if six.PY2: # nocv # Ugly hack because python 2.7. if self._stdout == self.DEVNULL: self._stdout = open(os.devnull, 'w+b') if self._stderr == self.DEVNULL: self._stderr = open(os.devnull, 'w+b') proc = subprocess.Popen( cmd, stdout=self._stdout, stderr=self._stderr, bufsize=0, universal_newlines=True, cwd=cwd, env=env, close_fds=ON_POSIX ) for line in self._unbuffered(proc): self.line_handler(line) return_code = proc.poll() if return_code: logger.error(self.output) raise subprocess.CalledProcessError( return_code, cmd, output=str(self.output) ) return self.output
python
def execute(self, cmd, cwd): self.output = "" env = os.environ.copy() env.update(self.env) if six.PY2: # nocv # Ugly hack because python 2.7. if self._stdout == self.DEVNULL: self._stdout = open(os.devnull, 'w+b') if self._stderr == self.DEVNULL: self._stderr = open(os.devnull, 'w+b') proc = subprocess.Popen( cmd, stdout=self._stdout, stderr=self._stderr, bufsize=0, universal_newlines=True, cwd=cwd, env=env, close_fds=ON_POSIX ) for line in self._unbuffered(proc): self.line_handler(line) return_code = proc.poll() if return_code: logger.error(self.output) raise subprocess.CalledProcessError( return_code, cmd, output=str(self.output) ) return self.output
[ "def", "execute", "(", "self", ",", "cmd", ",", "cwd", ")", ":", "self", ".", "output", "=", "\"\"", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "env", ".", "update", "(", "self", ".", "env", ")", "if", "six", ".", "PY2", ":", "# nocv", "# Ugly hack because python 2.7.", "if", "self", ".", "_stdout", "==", "self", ".", "DEVNULL", ":", "self", ".", "_stdout", "=", "open", "(", "os", ".", "devnull", ",", "'w+b'", ")", "if", "self", ".", "_stderr", "==", "self", ".", "DEVNULL", ":", "self", ".", "_stderr", "=", "open", "(", "os", ".", "devnull", ",", "'w+b'", ")", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "self", ".", "_stdout", ",", "stderr", "=", "self", ".", "_stderr", ",", "bufsize", "=", "0", ",", "universal_newlines", "=", "True", ",", "cwd", "=", "cwd", ",", "env", "=", "env", ",", "close_fds", "=", "ON_POSIX", ")", "for", "line", "in", "self", ".", "_unbuffered", "(", "proc", ")", ":", "self", ".", "line_handler", "(", "line", ")", "return_code", "=", "proc", ".", "poll", "(", ")", "if", "return_code", ":", "logger", ".", "error", "(", "self", ".", "output", ")", "raise", "subprocess", ".", "CalledProcessError", "(", "return_code", ",", "cmd", ",", "output", "=", "str", "(", "self", ".", "output", ")", ")", "return", "self", ".", "output" ]
Execute commands and output this :param cmd: -- list of cmd command and arguments :type cmd: list :param cwd: -- workdir for executions :type cwd: str,unicode :return: -- string with full output :rtype: str
[ "Execute", "commands", "and", "output", "this" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/utils.py#L369-L403
4,084
vstconsulting/vstutils
vstutils/utils.py
ModelHandlers.backend
def backend(self, name): """ Get backend class :param name: -- name of backend type :type name: str :return: class of backend :rtype: class,module,object """ try: backend = self.get_backend_handler_path(name) if backend is None: raise ex.VSTUtilsException("Backend is 'None'.") # pragma: no cover return self._get_baskend(backend) except KeyError or ImportError: msg = "{} ({})".format(name, self.err_message) if self.err_message else name raise ex.UnknownTypeException(msg)
python
def backend(self, name): try: backend = self.get_backend_handler_path(name) if backend is None: raise ex.VSTUtilsException("Backend is 'None'.") # pragma: no cover return self._get_baskend(backend) except KeyError or ImportError: msg = "{} ({})".format(name, self.err_message) if self.err_message else name raise ex.UnknownTypeException(msg)
[ "def", "backend", "(", "self", ",", "name", ")", ":", "try", ":", "backend", "=", "self", ".", "get_backend_handler_path", "(", "name", ")", "if", "backend", "is", "None", ":", "raise", "ex", ".", "VSTUtilsException", "(", "\"Backend is 'None'.\"", ")", "# pragma: no cover", "return", "self", ".", "_get_baskend", "(", "backend", ")", "except", "KeyError", "or", "ImportError", ":", "msg", "=", "\"{} ({})\"", ".", "format", "(", "name", ",", "self", ".", "err_message", ")", "if", "self", ".", "err_message", "else", "name", "raise", "ex", ".", "UnknownTypeException", "(", "msg", ")" ]
Get backend class :param name: -- name of backend type :type name: str :return: class of backend :rtype: class,module,object
[ "Get", "backend", "class" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/utils.py#L650-L666
4,085
vstconsulting/vstutils
vstutils/utils.py
URLHandlers.get_object
def get_object(self, name, *argv, **kwargs): """ Get url object tuple for url :param name: url regexp from :type name: str :param argv: overrided args :param kwargs: overrided kwargs :return: url object :rtype: django.conf.urls.url """ regexp = name options = self.opts(regexp) options.update(kwargs) args = options.pop('view_args', argv) csrf_enable = self.get_backend_data(regexp).get('CSRF_ENABLE', True) if regexp in self.settings_urls: regexp = r'^{}'.format(self.get_django_settings(regexp)[1:]) view = self[name].as_view() if not csrf_enable: view = csrf_exempt(view) return url(regexp, view, *args, **options)
python
def get_object(self, name, *argv, **kwargs): regexp = name options = self.opts(regexp) options.update(kwargs) args = options.pop('view_args', argv) csrf_enable = self.get_backend_data(regexp).get('CSRF_ENABLE', True) if regexp in self.settings_urls: regexp = r'^{}'.format(self.get_django_settings(regexp)[1:]) view = self[name].as_view() if not csrf_enable: view = csrf_exempt(view) return url(regexp, view, *args, **options)
[ "def", "get_object", "(", "self", ",", "name", ",", "*", "argv", ",", "*", "*", "kwargs", ")", ":", "regexp", "=", "name", "options", "=", "self", ".", "opts", "(", "regexp", ")", "options", ".", "update", "(", "kwargs", ")", "args", "=", "options", ".", "pop", "(", "'view_args'", ",", "argv", ")", "csrf_enable", "=", "self", ".", "get_backend_data", "(", "regexp", ")", ".", "get", "(", "'CSRF_ENABLE'", ",", "True", ")", "if", "regexp", "in", "self", ".", "settings_urls", ":", "regexp", "=", "r'^{}'", ".", "format", "(", "self", ".", "get_django_settings", "(", "regexp", ")", "[", "1", ":", "]", ")", "view", "=", "self", "[", "name", "]", ".", "as_view", "(", ")", "if", "not", "csrf_enable", ":", "view", "=", "csrf_exempt", "(", "view", ")", "return", "url", "(", "regexp", ",", "view", ",", "*", "args", ",", "*", "*", "options", ")" ]
Get url object tuple for url :param name: url regexp from :type name: str :param argv: overrided args :param kwargs: overrided kwargs :return: url object :rtype: django.conf.urls.url
[ "Get", "url", "object", "tuple", "for", "url" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/utils.py#L718-L739
4,086
vstconsulting/vstutils
vstutils/api/base.py
CopyMixin.copy
def copy(self, request, **kwargs): # pylint: disable=unused-argument ''' Copy instance with deps. ''' instance = self.copy_instance(self.get_object()) serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid() serializer.save() return Response(serializer.data, status.HTTP_201_CREATED).resp
python
def copy(self, request, **kwargs): # pylint: disable=unused-argument ''' Copy instance with deps. ''' instance = self.copy_instance(self.get_object()) serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid() serializer.save() return Response(serializer.data, status.HTTP_201_CREATED).resp
[ "def", "copy", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "instance", "=", "self", ".", "copy_instance", "(", "self", ".", "get_object", "(", ")", ")", "serializer", "=", "self", ".", "get_serializer", "(", "instance", ",", "data", "=", "request", ".", "data", ",", "partial", "=", "True", ")", "serializer", ".", "is_valid", "(", ")", "serializer", ".", "save", "(", ")", "return", "Response", "(", "serializer", ".", "data", ",", "status", ".", "HTTP_201_CREATED", ")", ".", "resp" ]
Copy instance with deps.
[ "Copy", "instance", "with", "deps", "." ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/api/base.py#L273-L282
4,087
vstconsulting/vstutils
vstutils/models.py
BaseManager._get_queryset_methods
def _get_queryset_methods(cls, queryset_class): ''' Django overrloaded method for add cyfunction. ''' def create_method(name, method): def manager_method(self, *args, **kwargs): return getattr(self.get_queryset(), name)(*args, **kwargs) manager_method.__name__ = method.__name__ manager_method.__doc__ = method.__doc__ return manager_method orig_method = models.Manager._get_queryset_methods new_methods = orig_method(queryset_class) inspect_func = inspect.isfunction for name, method in inspect.getmembers(queryset_class, predicate=inspect_func): # Only copy missing methods. if hasattr(cls, name) or name in new_methods: continue queryset_only = getattr(method, 'queryset_only', None) if queryset_only or (queryset_only is None and name.startswith('_')): continue # Copy the method onto the manager. new_methods[name] = create_method(name, method) return new_methods
python
def _get_queryset_methods(cls, queryset_class): ''' Django overrloaded method for add cyfunction. ''' def create_method(name, method): def manager_method(self, *args, **kwargs): return getattr(self.get_queryset(), name)(*args, **kwargs) manager_method.__name__ = method.__name__ manager_method.__doc__ = method.__doc__ return manager_method orig_method = models.Manager._get_queryset_methods new_methods = orig_method(queryset_class) inspect_func = inspect.isfunction for name, method in inspect.getmembers(queryset_class, predicate=inspect_func): # Only copy missing methods. if hasattr(cls, name) or name in new_methods: continue queryset_only = getattr(method, 'queryset_only', None) if queryset_only or (queryset_only is None and name.startswith('_')): continue # Copy the method onto the manager. new_methods[name] = create_method(name, method) return new_methods
[ "def", "_get_queryset_methods", "(", "cls", ",", "queryset_class", ")", ":", "def", "create_method", "(", "name", ",", "method", ")", ":", "def", "manager_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "getattr", "(", "self", ".", "get_queryset", "(", ")", ",", "name", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")", "manager_method", ".", "__name__", "=", "method", ".", "__name__", "manager_method", ".", "__doc__", "=", "method", ".", "__doc__", "return", "manager_method", "orig_method", "=", "models", ".", "Manager", ".", "_get_queryset_methods", "new_methods", "=", "orig_method", "(", "queryset_class", ")", "inspect_func", "=", "inspect", ".", "isfunction", "for", "name", ",", "method", "in", "inspect", ".", "getmembers", "(", "queryset_class", ",", "predicate", "=", "inspect_func", ")", ":", "# Only copy missing methods.", "if", "hasattr", "(", "cls", ",", "name", ")", "or", "name", "in", "new_methods", ":", "continue", "queryset_only", "=", "getattr", "(", "method", ",", "'queryset_only'", ",", "None", ")", "if", "queryset_only", "or", "(", "queryset_only", "is", "None", "and", "name", ".", "startswith", "(", "'_'", ")", ")", ":", "continue", "# Copy the method onto the manager.", "new_methods", "[", "name", "]", "=", "create_method", "(", "name", ",", "method", ")", "return", "new_methods" ]
Django overrloaded method for add cyfunction.
[ "Django", "overrloaded", "method", "for", "add", "cyfunction", "." ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/models.py#L65-L89
4,088
vstconsulting/vstutils
vstutils/ldap_utils.py
LDAP.__authenticate
def __authenticate(self, ad, username, password): ''' Active Directory auth function :param ad: LDAP connection string ('ldap://server') :param username: username with domain ('[email protected]') :param password: auth password :return: ldap connection or None if error ''' result = None conn = ldap.initialize(ad) conn.protocol_version = 3 conn.set_option(ldap.OPT_REFERRALS, 0) user = self.__prepare_user_with_domain(username) self.logger.debug("Trying to auth with user '{}' to {}".format(user, ad)) try: conn.simple_bind_s(user, password) result = conn self.username, self.password = username, password self.logger.debug("Successfull login as {}".format(username)) except ldap.INVALID_CREDENTIALS: result = False self.logger.debug(traceback.format_exc()) self.logger.debug("Invalid ldap-creds.") except Exception as ex: # nocv self.logger.debug(traceback.format_exc()) self.logger.debug("Unknown error: {}".format(str(ex))) return result
python
def __authenticate(self, ad, username, password): ''' Active Directory auth function :param ad: LDAP connection string ('ldap://server') :param username: username with domain ('[email protected]') :param password: auth password :return: ldap connection or None if error ''' result = None conn = ldap.initialize(ad) conn.protocol_version = 3 conn.set_option(ldap.OPT_REFERRALS, 0) user = self.__prepare_user_with_domain(username) self.logger.debug("Trying to auth with user '{}' to {}".format(user, ad)) try: conn.simple_bind_s(user, password) result = conn self.username, self.password = username, password self.logger.debug("Successfull login as {}".format(username)) except ldap.INVALID_CREDENTIALS: result = False self.logger.debug(traceback.format_exc()) self.logger.debug("Invalid ldap-creds.") except Exception as ex: # nocv self.logger.debug(traceback.format_exc()) self.logger.debug("Unknown error: {}".format(str(ex))) return result
[ "def", "__authenticate", "(", "self", ",", "ad", ",", "username", ",", "password", ")", ":", "result", "=", "None", "conn", "=", "ldap", ".", "initialize", "(", "ad", ")", "conn", ".", "protocol_version", "=", "3", "conn", ".", "set_option", "(", "ldap", ".", "OPT_REFERRALS", ",", "0", ")", "user", "=", "self", ".", "__prepare_user_with_domain", "(", "username", ")", "self", ".", "logger", ".", "debug", "(", "\"Trying to auth with user '{}' to {}\"", ".", "format", "(", "user", ",", "ad", ")", ")", "try", ":", "conn", ".", "simple_bind_s", "(", "user", ",", "password", ")", "result", "=", "conn", "self", ".", "username", ",", "self", ".", "password", "=", "username", ",", "password", "self", ".", "logger", ".", "debug", "(", "\"Successfull login as {}\"", ".", "format", "(", "username", ")", ")", "except", "ldap", ".", "INVALID_CREDENTIALS", ":", "result", "=", "False", "self", ".", "logger", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"Invalid ldap-creds.\"", ")", "except", "Exception", "as", "ex", ":", "# nocv", "self", ".", "logger", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"Unknown error: {}\"", ".", "format", "(", "str", "(", "ex", ")", ")", ")", "return", "result" ]
Active Directory auth function :param ad: LDAP connection string ('ldap://server') :param username: username with domain ('[email protected]') :param password: auth password :return: ldap connection or None if error
[ "Active", "Directory", "auth", "function" ]
3d6d140c2463952dc9835a4e40caf758468b3049
https://github.com/vstconsulting/vstutils/blob/3d6d140c2463952dc9835a4e40caf758468b3049/vstutils/ldap_utils.py#L91-L119
4,089
gregmuellegger/django-autofixture
autofixture/__init__.py
register
def register(model, autofixture, overwrite=False, fail_silently=False): ''' Register a model with the registry. Arguments: *model* can be either a model class or a string that contains the model's app label and class name seperated by a dot, e.g. ``"app.ModelClass"``. *autofixture* is the :mod:`AutoFixture` subclass that shall be used to generated instances of *model*. By default :func:`register` will raise :exc:`ValueError` if the given *model* is already registered. You can overwrite the registered *model* if you pass ``True`` to the *overwrite* argument. The :exc:`ValueError` that is usually raised if a model is already registered can be suppressed by passing ``True`` to the *fail_silently* argument. ''' from .compat import get_model if isinstance(model, string_types): model = get_model(*model.split('.', 1)) if not overwrite and model in REGISTRY: if fail_silently: return raise ValueError( u'%s.%s is already registered. You can overwrite the registered ' u'autofixture by providing the `overwrite` argument.' % ( model._meta.app_label, model._meta.object_name, )) REGISTRY[model] = autofixture
python
def register(model, autofixture, overwrite=False, fail_silently=False): ''' Register a model with the registry. Arguments: *model* can be either a model class or a string that contains the model's app label and class name seperated by a dot, e.g. ``"app.ModelClass"``. *autofixture* is the :mod:`AutoFixture` subclass that shall be used to generated instances of *model*. By default :func:`register` will raise :exc:`ValueError` if the given *model* is already registered. You can overwrite the registered *model* if you pass ``True`` to the *overwrite* argument. The :exc:`ValueError` that is usually raised if a model is already registered can be suppressed by passing ``True`` to the *fail_silently* argument. ''' from .compat import get_model if isinstance(model, string_types): model = get_model(*model.split('.', 1)) if not overwrite and model in REGISTRY: if fail_silently: return raise ValueError( u'%s.%s is already registered. You can overwrite the registered ' u'autofixture by providing the `overwrite` argument.' % ( model._meta.app_label, model._meta.object_name, )) REGISTRY[model] = autofixture
[ "def", "register", "(", "model", ",", "autofixture", ",", "overwrite", "=", "False", ",", "fail_silently", "=", "False", ")", ":", "from", ".", "compat", "import", "get_model", "if", "isinstance", "(", "model", ",", "string_types", ")", ":", "model", "=", "get_model", "(", "*", "model", ".", "split", "(", "'.'", ",", "1", ")", ")", "if", "not", "overwrite", "and", "model", "in", "REGISTRY", ":", "if", "fail_silently", ":", "return", "raise", "ValueError", "(", "u'%s.%s is already registered. You can overwrite the registered '", "u'autofixture by providing the `overwrite` argument.'", "%", "(", "model", ".", "_meta", ".", "app_label", ",", "model", ".", "_meta", ".", "object_name", ",", ")", ")", "REGISTRY", "[", "model", "]", "=", "autofixture" ]
Register a model with the registry. Arguments: *model* can be either a model class or a string that contains the model's app label and class name seperated by a dot, e.g. ``"app.ModelClass"``. *autofixture* is the :mod:`AutoFixture` subclass that shall be used to generated instances of *model*. By default :func:`register` will raise :exc:`ValueError` if the given *model* is already registered. You can overwrite the registered *model* if you pass ``True`` to the *overwrite* argument. The :exc:`ValueError` that is usually raised if a model is already registered can be suppressed by passing ``True`` to the *fail_silently* argument.
[ "Register", "a", "model", "with", "the", "registry", "." ]
0b696fd3a06747459981e4269aff427676f84ae0
https://github.com/gregmuellegger/django-autofixture/blob/0b696fd3a06747459981e4269aff427676f84ae0/autofixture/__init__.py#L21-L54
4,090
gregmuellegger/django-autofixture
autofixture/__init__.py
unregister
def unregister(model_or_iterable, fail_silently=False): ''' Remove one or more models from the autofixture registry. ''' from django.db import models from .compat import get_model if issubclass(model_or_iterable, models.Model): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if isinstance(model, string_types): model = get_model(*model.split('.', 1)) try: del REGISTRY[model] except KeyError: if fail_silently: continue raise ValueError( u'The model %s.%s is not registered.' % ( model._meta.app_label, model._meta.object_name, ))
python
def unregister(model_or_iterable, fail_silently=False): ''' Remove one or more models from the autofixture registry. ''' from django.db import models from .compat import get_model if issubclass(model_or_iterable, models.Model): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if isinstance(model, string_types): model = get_model(*model.split('.', 1)) try: del REGISTRY[model] except KeyError: if fail_silently: continue raise ValueError( u'The model %s.%s is not registered.' % ( model._meta.app_label, model._meta.object_name, ))
[ "def", "unregister", "(", "model_or_iterable", ",", "fail_silently", "=", "False", ")", ":", "from", "django", ".", "db", "import", "models", "from", ".", "compat", "import", "get_model", "if", "issubclass", "(", "model_or_iterable", ",", "models", ".", "Model", ")", ":", "model_or_iterable", "=", "[", "model_or_iterable", "]", "for", "model", "in", "model_or_iterable", ":", "if", "isinstance", "(", "model", ",", "string_types", ")", ":", "model", "=", "get_model", "(", "*", "model", ".", "split", "(", "'.'", ",", "1", ")", ")", "try", ":", "del", "REGISTRY", "[", "model", "]", "except", "KeyError", ":", "if", "fail_silently", ":", "continue", "raise", "ValueError", "(", "u'The model %s.%s is not registered.'", "%", "(", "model", ".", "_meta", ".", "app_label", ",", "model", ".", "_meta", ".", "object_name", ",", ")", ")" ]
Remove one or more models from the autofixture registry.
[ "Remove", "one", "or", "more", "models", "from", "the", "autofixture", "registry", "." ]
0b696fd3a06747459981e4269aff427676f84ae0
https://github.com/gregmuellegger/django-autofixture/blob/0b696fd3a06747459981e4269aff427676f84ae0/autofixture/__init__.py#L57-L78
4,091
gregmuellegger/django-autofixture
autofixture/__init__.py
autodiscover
def autodiscover(): ''' Auto-discover INSTALLED_APPS autofixtures.py and tests.py modules and fail silently when not present. This forces an import on them to register any autofixture bits they may want. ''' from .compat import importlib # Bail out if autodiscover didn't finish loading from a previous call so # that we avoid running autodiscover again when the URLconf is loaded by # the exception handler to resolve the handler500 view. This prevents an # autofixtures.py module with errors from re-registering models and raising a # spurious AlreadyRegistered exception (see #8245). global LOADING if LOADING: return LOADING = True app_paths = {} # For each app, we need to look for an autofixture.py inside that app's # package. We can't use os.path here -- recall that modules may be # imported different ways (think zip files) -- so we need to get # the app's __path__ and look for autofixture.py on that path. # Step 1: find out the app's __path__ Import errors here will (and # should) bubble up, but a missing __path__ (which is legal, but weird) # fails silently -- apps that do weird things with __path__ might # need to roll their own autofixture registration. import imp try: from django.apps import apps for app_config in apps.get_app_configs(): app_paths[app_config.name] = [app_config.path] except ImportError: # Django < 1.7 from django.conf import settings for app in settings.INSTALLED_APPS: mod = importlib.import_module(app) try: app_paths[app] = mod.__path__ except AttributeError: continue for app, app_path in app_paths.items(): # Step 2: use imp.find_module to find the app's autofixtures.py. For some # reason imp.find_module raises ImportError if the app can't be found # but doesn't actually try to import the module. So skip this app if # its autofixtures.py doesn't exist try: file, _, _ = imp.find_module('autofixtures', app_path) except ImportError: continue else: if file: file.close() # Step 3: import the app's autofixtures file. If this has errors we want them # to bubble up. try: importlib.import_module("%s.autofixtures" % app) except Exception as e: warnings.warn(u'Error while importing %s.autofixtures: %r' % (app, e)) for app, app_path in app_paths.items(): try: file, _, _ = imp.find_module('tests', app_path) except ImportError: continue else: if file: file.close() try: importlib.import_module("%s.tests" % app) except Exception as e: warnings.warn(u'Error while importing %s.tests: %r' % (app, e)) # autodiscover was successful, reset loading flag. LOADING = False
python
def autodiscover(): ''' Auto-discover INSTALLED_APPS autofixtures.py and tests.py modules and fail silently when not present. This forces an import on them to register any autofixture bits they may want. ''' from .compat import importlib # Bail out if autodiscover didn't finish loading from a previous call so # that we avoid running autodiscover again when the URLconf is loaded by # the exception handler to resolve the handler500 view. This prevents an # autofixtures.py module with errors from re-registering models and raising a # spurious AlreadyRegistered exception (see #8245). global LOADING if LOADING: return LOADING = True app_paths = {} # For each app, we need to look for an autofixture.py inside that app's # package. We can't use os.path here -- recall that modules may be # imported different ways (think zip files) -- so we need to get # the app's __path__ and look for autofixture.py on that path. # Step 1: find out the app's __path__ Import errors here will (and # should) bubble up, but a missing __path__ (which is legal, but weird) # fails silently -- apps that do weird things with __path__ might # need to roll their own autofixture registration. import imp try: from django.apps import apps for app_config in apps.get_app_configs(): app_paths[app_config.name] = [app_config.path] except ImportError: # Django < 1.7 from django.conf import settings for app in settings.INSTALLED_APPS: mod = importlib.import_module(app) try: app_paths[app] = mod.__path__ except AttributeError: continue for app, app_path in app_paths.items(): # Step 2: use imp.find_module to find the app's autofixtures.py. For some # reason imp.find_module raises ImportError if the app can't be found # but doesn't actually try to import the module. So skip this app if # its autofixtures.py doesn't exist try: file, _, _ = imp.find_module('autofixtures', app_path) except ImportError: continue else: if file: file.close() # Step 3: import the app's autofixtures file. If this has errors we want them # to bubble up. try: importlib.import_module("%s.autofixtures" % app) except Exception as e: warnings.warn(u'Error while importing %s.autofixtures: %r' % (app, e)) for app, app_path in app_paths.items(): try: file, _, _ = imp.find_module('tests', app_path) except ImportError: continue else: if file: file.close() try: importlib.import_module("%s.tests" % app) except Exception as e: warnings.warn(u'Error while importing %s.tests: %r' % (app, e)) # autodiscover was successful, reset loading flag. LOADING = False
[ "def", "autodiscover", "(", ")", ":", "from", ".", "compat", "import", "importlib", "# Bail out if autodiscover didn't finish loading from a previous call so", "# that we avoid running autodiscover again when the URLconf is loaded by", "# the exception handler to resolve the handler500 view. This prevents an", "# autofixtures.py module with errors from re-registering models and raising a", "# spurious AlreadyRegistered exception (see #8245).", "global", "LOADING", "if", "LOADING", ":", "return", "LOADING", "=", "True", "app_paths", "=", "{", "}", "# For each app, we need to look for an autofixture.py inside that app's", "# package. We can't use os.path here -- recall that modules may be", "# imported different ways (think zip files) -- so we need to get", "# the app's __path__ and look for autofixture.py on that path.", "# Step 1: find out the app's __path__ Import errors here will (and", "# should) bubble up, but a missing __path__ (which is legal, but weird)", "# fails silently -- apps that do weird things with __path__ might", "# need to roll their own autofixture registration.", "import", "imp", "try", ":", "from", "django", ".", "apps", "import", "apps", "for", "app_config", "in", "apps", ".", "get_app_configs", "(", ")", ":", "app_paths", "[", "app_config", ".", "name", "]", "=", "[", "app_config", ".", "path", "]", "except", "ImportError", ":", "# Django < 1.7", "from", "django", ".", "conf", "import", "settings", "for", "app", "in", "settings", ".", "INSTALLED_APPS", ":", "mod", "=", "importlib", ".", "import_module", "(", "app", ")", "try", ":", "app_paths", "[", "app", "]", "=", "mod", ".", "__path__", "except", "AttributeError", ":", "continue", "for", "app", ",", "app_path", "in", "app_paths", ".", "items", "(", ")", ":", "# Step 2: use imp.find_module to find the app's autofixtures.py. For some", "# reason imp.find_module raises ImportError if the app can't be found", "# but doesn't actually try to import the module. So skip this app if", "# its autofixtures.py doesn't exist", "try", ":", "file", ",", "_", ",", "_", "=", "imp", ".", "find_module", "(", "'autofixtures'", ",", "app_path", ")", "except", "ImportError", ":", "continue", "else", ":", "if", "file", ":", "file", ".", "close", "(", ")", "# Step 3: import the app's autofixtures file. If this has errors we want them", "# to bubble up.", "try", ":", "importlib", ".", "import_module", "(", "\"%s.autofixtures\"", "%", "app", ")", "except", "Exception", "as", "e", ":", "warnings", ".", "warn", "(", "u'Error while importing %s.autofixtures: %r'", "%", "(", "app", ",", "e", ")", ")", "for", "app", ",", "app_path", "in", "app_paths", ".", "items", "(", ")", ":", "try", ":", "file", ",", "_", ",", "_", "=", "imp", ".", "find_module", "(", "'tests'", ",", "app_path", ")", "except", "ImportError", ":", "continue", "else", ":", "if", "file", ":", "file", ".", "close", "(", ")", "try", ":", "importlib", ".", "import_module", "(", "\"%s.tests\"", "%", "app", ")", "except", "Exception", "as", "e", ":", "warnings", ".", "warn", "(", "u'Error while importing %s.tests: %r'", "%", "(", "app", ",", "e", ")", ")", "# autodiscover was successful, reset loading flag.", "LOADING", "=", "False" ]
Auto-discover INSTALLED_APPS autofixtures.py and tests.py modules and fail silently when not present. This forces an import on them to register any autofixture bits they may want.
[ "Auto", "-", "discover", "INSTALLED_APPS", "autofixtures", ".", "py", "and", "tests", ".", "py", "modules", "and", "fail", "silently", "when", "not", "present", ".", "This", "forces", "an", "import", "on", "them", "to", "register", "any", "autofixture", "bits", "they", "may", "want", "." ]
0b696fd3a06747459981e4269aff427676f84ae0
https://github.com/gregmuellegger/django-autofixture/blob/0b696fd3a06747459981e4269aff427676f84ae0/autofixture/__init__.py#L151-L235
4,092
gregmuellegger/django-autofixture
autofixture/base.py
AutoFixtureBase.is_inheritance_parent
def is_inheritance_parent(self, field): ''' Checks if the field is the automatically created OneToOneField used by django mulit-table inheritance ''' return ( isinstance(field, related.OneToOneField) and field.primary_key and issubclass(field.model, get_remote_field_to(field)) )
python
def is_inheritance_parent(self, field): ''' Checks if the field is the automatically created OneToOneField used by django mulit-table inheritance ''' return ( isinstance(field, related.OneToOneField) and field.primary_key and issubclass(field.model, get_remote_field_to(field)) )
[ "def", "is_inheritance_parent", "(", "self", ",", "field", ")", ":", "return", "(", "isinstance", "(", "field", ",", "related", ".", "OneToOneField", ")", "and", "field", ".", "primary_key", "and", "issubclass", "(", "field", ".", "model", ",", "get_remote_field_to", "(", "field", ")", ")", ")" ]
Checks if the field is the automatically created OneToOneField used by django mulit-table inheritance
[ "Checks", "if", "the", "field", "is", "the", "automatically", "created", "OneToOneField", "used", "by", "django", "mulit", "-", "table", "inheritance" ]
0b696fd3a06747459981e4269aff427676f84ae0
https://github.com/gregmuellegger/django-autofixture/blob/0b696fd3a06747459981e4269aff427676f84ae0/autofixture/base.py#L249-L258
4,093
gregmuellegger/django-autofixture
autofixture/base.py
AutoFixtureBase.check_constraints
def check_constraints(self, instance): ''' Return fieldnames which need recalculation. ''' recalc_fields = [] for constraint in self.constraints: try: constraint(self.model, instance) except constraints.InvalidConstraint as e: recalc_fields.extend(e.fields) return recalc_fields
python
def check_constraints(self, instance): ''' Return fieldnames which need recalculation. ''' recalc_fields = [] for constraint in self.constraints: try: constraint(self.model, instance) except constraints.InvalidConstraint as e: recalc_fields.extend(e.fields) return recalc_fields
[ "def", "check_constraints", "(", "self", ",", "instance", ")", ":", "recalc_fields", "=", "[", "]", "for", "constraint", "in", "self", ".", "constraints", ":", "try", ":", "constraint", "(", "self", ".", "model", ",", "instance", ")", "except", "constraints", ".", "InvalidConstraint", "as", "e", ":", "recalc_fields", ".", "extend", "(", "e", ".", "fields", ")", "return", "recalc_fields" ]
Return fieldnames which need recalculation.
[ "Return", "fieldnames", "which", "need", "recalculation", "." ]
0b696fd3a06747459981e4269aff427676f84ae0
https://github.com/gregmuellegger/django-autofixture/blob/0b696fd3a06747459981e4269aff427676f84ae0/autofixture/base.py#L458-L468
4,094
gregmuellegger/django-autofixture
fabfile.py
opendocs
def opendocs(where='index', how='default'): ''' Rebuild documentation and opens it in your browser. Use the first argument to specify how it should be opened: `d` or `default`: Open in new tab or new window, using the default method of your browser. `t` or `tab`: Open documentation in new tab. `n`, `w` or `window`: Open documentation in new window. ''' import webbrowser docs_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'docs') index = os.path.join(docs_dir, '_build/html/%s.html' % where) builddocs('html') url = 'file://%s' % os.path.abspath(index) if how in ('d', 'default'): webbrowser.open(url) elif how in ('t', 'tab'): webbrowser.open_new_tab(url) elif how in ('n', 'w', 'window'): webbrowser.open_new(url)
python
def opendocs(where='index', how='default'): ''' Rebuild documentation and opens it in your browser. Use the first argument to specify how it should be opened: `d` or `default`: Open in new tab or new window, using the default method of your browser. `t` or `tab`: Open documentation in new tab. `n`, `w` or `window`: Open documentation in new window. ''' import webbrowser docs_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'docs') index = os.path.join(docs_dir, '_build/html/%s.html' % where) builddocs('html') url = 'file://%s' % os.path.abspath(index) if how in ('d', 'default'): webbrowser.open(url) elif how in ('t', 'tab'): webbrowser.open_new_tab(url) elif how in ('n', 'w', 'window'): webbrowser.open_new(url)
[ "def", "opendocs", "(", "where", "=", "'index'", ",", "how", "=", "'default'", ")", ":", "import", "webbrowser", "docs_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "'docs'", ")", "index", "=", "os", ".", "path", ".", "join", "(", "docs_dir", ",", "'_build/html/%s.html'", "%", "where", ")", "builddocs", "(", "'html'", ")", "url", "=", "'file://%s'", "%", "os", ".", "path", ".", "abspath", "(", "index", ")", "if", "how", "in", "(", "'d'", ",", "'default'", ")", ":", "webbrowser", ".", "open", "(", "url", ")", "elif", "how", "in", "(", "'t'", ",", "'tab'", ")", ":", "webbrowser", ".", "open_new_tab", "(", "url", ")", "elif", "how", "in", "(", "'n'", ",", "'w'", ",", "'window'", ")", ":", "webbrowser", ".", "open_new", "(", "url", ")" ]
Rebuild documentation and opens it in your browser. Use the first argument to specify how it should be opened: `d` or `default`: Open in new tab or new window, using the default method of your browser. `t` or `tab`: Open documentation in new tab. `n`, `w` or `window`: Open documentation in new window.
[ "Rebuild", "documentation", "and", "opens", "it", "in", "your", "browser", "." ]
0b696fd3a06747459981e4269aff427676f84ae0
https://github.com/gregmuellegger/django-autofixture/blob/0b696fd3a06747459981e4269aff427676f84ae0/fabfile.py#L24-L49
4,095
plumdog/flask_table
flask_table/columns.py
Col.td_contents
def td_contents(self, item, attr_list): """Given an item and an attr, return the contents of the td. This method is a likely candidate to override when extending the Col class, which is done in LinkCol and ButtonCol. Override this method if you need to get some extra data from the item. Note that the output of this function is NOT escaped. """ return self.td_format(self.from_attr_list(item, attr_list))
python
def td_contents(self, item, attr_list): return self.td_format(self.from_attr_list(item, attr_list))
[ "def", "td_contents", "(", "self", ",", "item", ",", "attr_list", ")", ":", "return", "self", ".", "td_format", "(", "self", ".", "from_attr_list", "(", "item", ",", "attr_list", ")", ")" ]
Given an item and an attr, return the contents of the td. This method is a likely candidate to override when extending the Col class, which is done in LinkCol and ButtonCol. Override this method if you need to get some extra data from the item. Note that the output of this function is NOT escaped.
[ "Given", "an", "item", "and", "an", "attr", "return", "the", "contents", "of", "the", "td", "." ]
1eae252c6b26037a6aa19fcd787a981ddb3a9191
https://github.com/plumdog/flask_table/blob/1eae252c6b26037a6aa19fcd787a981ddb3a9191/flask_table/columns.py#L102-L113
4,096
peterjc/backports.lzma
backports/lzma/__init__.py
open
def open(filename, mode="rb", format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None): """Open an LZMA-compressed file in binary or text mode. filename can be either an actual file name (given as a str or bytes object), in which case the named file is opened, or it can be an existing file object to read from or write to. The mode argument can be "r", "rb" (default), "w", "wb", "a", or "ab" for binary mode, or "rt", "wt" or "at" for text mode. The format, check, preset and filters arguments specify the compression settings, as for LZMACompressor, LZMADecompressor and LZMAFile. For binary mode, this function is equivalent to the LZMAFile constructor: LZMAFile(filename, mode, ...). In this case, the encoding, errors and newline arguments must not be provided. For text mode, a LZMAFile object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s). """ if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if errors is not None: raise ValueError("Argument 'errors' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode") lz_mode = mode.replace("t", "") binary_file = LZMAFile(filename, lz_mode, format=format, check=check, preset=preset, filters=filters) if "t" in mode: return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file
python
def open(filename, mode="rb", format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None): if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if errors is not None: raise ValueError("Argument 'errors' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode") lz_mode = mode.replace("t", "") binary_file = LZMAFile(filename, lz_mode, format=format, check=check, preset=preset, filters=filters) if "t" in mode: return io.TextIOWrapper(binary_file, encoding, errors, newline) else: return binary_file
[ "def", "open", "(", "filename", ",", "mode", "=", "\"rb\"", ",", "format", "=", "None", ",", "check", "=", "-", "1", ",", "preset", "=", "None", ",", "filters", "=", "None", ",", "encoding", "=", "None", ",", "errors", "=", "None", ",", "newline", "=", "None", ")", ":", "if", "\"t\"", "in", "mode", ":", "if", "\"b\"", "in", "mode", ":", "raise", "ValueError", "(", "\"Invalid mode: %r\"", "%", "(", "mode", ",", ")", ")", "else", ":", "if", "encoding", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Argument 'encoding' not supported in binary mode\"", ")", "if", "errors", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Argument 'errors' not supported in binary mode\"", ")", "if", "newline", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Argument 'newline' not supported in binary mode\"", ")", "lz_mode", "=", "mode", ".", "replace", "(", "\"t\"", ",", "\"\"", ")", "binary_file", "=", "LZMAFile", "(", "filename", ",", "lz_mode", ",", "format", "=", "format", ",", "check", "=", "check", ",", "preset", "=", "preset", ",", "filters", "=", "filters", ")", "if", "\"t\"", "in", "mode", ":", "return", "io", ".", "TextIOWrapper", "(", "binary_file", ",", "encoding", ",", "errors", ",", "newline", ")", "else", ":", "return", "binary_file" ]
Open an LZMA-compressed file in binary or text mode. filename can be either an actual file name (given as a str or bytes object), in which case the named file is opened, or it can be an existing file object to read from or write to. The mode argument can be "r", "rb" (default), "w", "wb", "a", or "ab" for binary mode, or "rt", "wt" or "at" for text mode. The format, check, preset and filters arguments specify the compression settings, as for LZMACompressor, LZMADecompressor and LZMAFile. For binary mode, this function is equivalent to the LZMAFile constructor: LZMAFile(filename, mode, ...). In this case, the encoding, errors and newline arguments must not be provided. For text mode, a LZMAFile object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).
[ "Open", "an", "LZMA", "-", "compressed", "file", "in", "binary", "or", "text", "mode", "." ]
6555d8b8e493a35159025b4cfc204dfb54c33d3e
https://github.com/peterjc/backports.lzma/blob/6555d8b8e493a35159025b4cfc204dfb54c33d3e/backports/lzma/__init__.py#L396-L438
4,097
peterjc/backports.lzma
backports/lzma/__init__.py
compress
def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None): """Compress a block of data. Refer to LZMACompressor's docstring for a description of the optional arguments *format*, *check*, *preset* and *filters*. For incremental compression, use an LZMACompressor object instead. """ comp = LZMACompressor(format, check, preset, filters) return comp.compress(data) + comp.flush()
python
def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None): comp = LZMACompressor(format, check, preset, filters) return comp.compress(data) + comp.flush()
[ "def", "compress", "(", "data", ",", "format", "=", "FORMAT_XZ", ",", "check", "=", "-", "1", ",", "preset", "=", "None", ",", "filters", "=", "None", ")", ":", "comp", "=", "LZMACompressor", "(", "format", ",", "check", ",", "preset", ",", "filters", ")", "return", "comp", ".", "compress", "(", "data", ")", "+", "comp", ".", "flush", "(", ")" ]
Compress a block of data. Refer to LZMACompressor's docstring for a description of the optional arguments *format*, *check*, *preset* and *filters*. For incremental compression, use an LZMACompressor object instead.
[ "Compress", "a", "block", "of", "data", "." ]
6555d8b8e493a35159025b4cfc204dfb54c33d3e
https://github.com/peterjc/backports.lzma/blob/6555d8b8e493a35159025b4cfc204dfb54c33d3e/backports/lzma/__init__.py#L441-L450
4,098
peterjc/backports.lzma
backports/lzma/__init__.py
decompress
def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None): """Decompress a block of data. Refer to LZMADecompressor's docstring for a description of the optional arguments *format*, *check* and *filters*. For incremental decompression, use a LZMADecompressor object instead. """ results = [] while True: decomp = LZMADecompressor(format, memlimit, filters) try: res = decomp.decompress(data) except LZMAError: if results: break # Leftover data is not a valid LZMA/XZ stream; ignore it. else: raise # Error on the first iteration; bail out. results.append(res) if not decomp.eof: raise LZMAError("Compressed data ended before the " "end-of-stream marker was reached") data = decomp.unused_data if not data: break return b"".join(results)
python
def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None): results = [] while True: decomp = LZMADecompressor(format, memlimit, filters) try: res = decomp.decompress(data) except LZMAError: if results: break # Leftover data is not a valid LZMA/XZ stream; ignore it. else: raise # Error on the first iteration; bail out. results.append(res) if not decomp.eof: raise LZMAError("Compressed data ended before the " "end-of-stream marker was reached") data = decomp.unused_data if not data: break return b"".join(results)
[ "def", "decompress", "(", "data", ",", "format", "=", "FORMAT_AUTO", ",", "memlimit", "=", "None", ",", "filters", "=", "None", ")", ":", "results", "=", "[", "]", "while", "True", ":", "decomp", "=", "LZMADecompressor", "(", "format", ",", "memlimit", ",", "filters", ")", "try", ":", "res", "=", "decomp", ".", "decompress", "(", "data", ")", "except", "LZMAError", ":", "if", "results", ":", "break", "# Leftover data is not a valid LZMA/XZ stream; ignore it.", "else", ":", "raise", "# Error on the first iteration; bail out.", "results", ".", "append", "(", "res", ")", "if", "not", "decomp", ".", "eof", ":", "raise", "LZMAError", "(", "\"Compressed data ended before the \"", "\"end-of-stream marker was reached\"", ")", "data", "=", "decomp", ".", "unused_data", "if", "not", "data", ":", "break", "return", "b\"\"", ".", "join", "(", "results", ")" ]
Decompress a block of data. Refer to LZMADecompressor's docstring for a description of the optional arguments *format*, *check* and *filters*. For incremental decompression, use a LZMADecompressor object instead.
[ "Decompress", "a", "block", "of", "data", "." ]
6555d8b8e493a35159025b4cfc204dfb54c33d3e
https://github.com/peterjc/backports.lzma/blob/6555d8b8e493a35159025b4cfc204dfb54c33d3e/backports/lzma/__init__.py#L453-L478
4,099
peterjc/backports.lzma
backports/lzma/__init__.py
LZMAFile.close
def close(self): """Flush and close the file. May be called more than once without error. Once the file is closed, any other operation on it will raise a ValueError. """ if self._mode == _MODE_CLOSED: return try: if self._mode in (_MODE_READ, _MODE_READ_EOF): self._decompressor = None self._buffer = None elif self._mode == _MODE_WRITE: self._fp.write(self._compressor.flush()) self._compressor = None finally: try: if self._closefp: self._fp.close() finally: self._fp = None self._closefp = False self._mode = _MODE_CLOSED
python
def close(self): if self._mode == _MODE_CLOSED: return try: if self._mode in (_MODE_READ, _MODE_READ_EOF): self._decompressor = None self._buffer = None elif self._mode == _MODE_WRITE: self._fp.write(self._compressor.flush()) self._compressor = None finally: try: if self._closefp: self._fp.close() finally: self._fp = None self._closefp = False self._mode = _MODE_CLOSED
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_mode", "==", "_MODE_CLOSED", ":", "return", "try", ":", "if", "self", ".", "_mode", "in", "(", "_MODE_READ", ",", "_MODE_READ_EOF", ")", ":", "self", ".", "_decompressor", "=", "None", "self", ".", "_buffer", "=", "None", "elif", "self", ".", "_mode", "==", "_MODE_WRITE", ":", "self", ".", "_fp", ".", "write", "(", "self", ".", "_compressor", ".", "flush", "(", ")", ")", "self", ".", "_compressor", "=", "None", "finally", ":", "try", ":", "if", "self", ".", "_closefp", ":", "self", ".", "_fp", ".", "close", "(", ")", "finally", ":", "self", ".", "_fp", "=", "None", "self", ".", "_closefp", "=", "False", "self", ".", "_mode", "=", "_MODE_CLOSED" ]
Flush and close the file. May be called more than once without error. Once the file is closed, any other operation on it will raise a ValueError.
[ "Flush", "and", "close", "the", "file", "." ]
6555d8b8e493a35159025b4cfc204dfb54c33d3e
https://github.com/peterjc/backports.lzma/blob/6555d8b8e493a35159025b4cfc204dfb54c33d3e/backports/lzma/__init__.py#L134-L156