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 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
246,500 | tbreitenfeldt/invisible_ui | invisible_ui/events/eventManager.py | EventManager.change_event_params | def change_event_params(self, handler, **kwargs):
"""
This allows the client to change the parameters for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
kwargs - the variable number of keyword arguments for the parameters that must match the properties of the corresponding event.
"""
if not isinstance(handler, Handler):
raise TypeError("given object must be of type Handler.")
if not self.remove_handler(handler):
raise ValueError("You must pass in a valid handler that already exists.")
self.add_handler(handler.type, handler.actions, **kwargs)
self.event = handler.event | python | def change_event_params(self, handler, **kwargs):
"""
This allows the client to change the parameters for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
kwargs - the variable number of keyword arguments for the parameters that must match the properties of the corresponding event.
"""
if not isinstance(handler, Handler):
raise TypeError("given object must be of type Handler.")
if not self.remove_handler(handler):
raise ValueError("You must pass in a valid handler that already exists.")
self.add_handler(handler.type, handler.actions, **kwargs)
self.event = handler.event | [
"def",
"change_event_params",
"(",
"self",
",",
"handler",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"handler",
",",
"Handler",
")",
":",
"raise",
"TypeError",
"(",
"\"given object must be of type Handler.\"",
")",
"if",
"not",
"self",
".",
"remove_handler",
"(",
"handler",
")",
":",
"raise",
"ValueError",
"(",
"\"You must pass in a valid handler that already exists.\"",
")",
"self",
".",
"add_handler",
"(",
"handler",
".",
"type",
",",
"handler",
".",
"actions",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"event",
"=",
"handler",
".",
"event"
] | This allows the client to change the parameters for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
kwargs - the variable number of keyword arguments for the parameters that must match the properties of the corresponding event. | [
"This",
"allows",
"the",
"client",
"to",
"change",
"the",
"parameters",
"for",
"an",
"event",
"in",
"the",
"case",
"that",
"there",
"is",
"a",
"desire",
"for",
"slightly",
"different",
"behavior",
"such",
"as",
"reasigning",
"keys",
"."
] | 1a6907bfa61bded13fa9fb83ec7778c0df84487f | https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L133-L147 |
246,501 | tbreitenfeldt/invisible_ui | invisible_ui/events/eventManager.py | EventManager.change_event_actions | def change_event_actions(self, handler, actions):
"""
This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The methods that are called when this handler is varified against the current event.
"""
if not isinstance(handler, Handler):
raise TypeError("given object must be of type Handler.")
if not self.remove_handler(handler):
raise ValueError("You must pass in a valid handler that already exists.")
self.add_handler(handler.type, actions, handler.params)
self.event = handler.event | python | def change_event_actions(self, handler, actions):
"""
This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The methods that are called when this handler is varified against the current event.
"""
if not isinstance(handler, Handler):
raise TypeError("given object must be of type Handler.")
if not self.remove_handler(handler):
raise ValueError("You must pass in a valid handler that already exists.")
self.add_handler(handler.type, actions, handler.params)
self.event = handler.event | [
"def",
"change_event_actions",
"(",
"self",
",",
"handler",
",",
"actions",
")",
":",
"if",
"not",
"isinstance",
"(",
"handler",
",",
"Handler",
")",
":",
"raise",
"TypeError",
"(",
"\"given object must be of type Handler.\"",
")",
"if",
"not",
"self",
".",
"remove_handler",
"(",
"handler",
")",
":",
"raise",
"ValueError",
"(",
"\"You must pass in a valid handler that already exists.\"",
")",
"self",
".",
"add_handler",
"(",
"handler",
".",
"type",
",",
"actions",
",",
"handler",
".",
"params",
")",
"self",
".",
"event",
"=",
"handler",
".",
"event"
] | This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The methods that are called when this handler is varified against the current event. | [
"This",
"allows",
"the",
"client",
"to",
"change",
"the",
"actions",
"for",
"an",
"event",
"in",
"the",
"case",
"that",
"there",
"is",
"a",
"desire",
"for",
"slightly",
"different",
"behavior",
"such",
"as",
"reasigning",
"keys",
"."
] | 1a6907bfa61bded13fa9fb83ec7778c0df84487f | https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L149-L163 |
246,502 | FujiMakoto/IPS-Vagrant | ips_vagrant/common/ssl.py | CertificateFactory.get | def get(self, bits=2048, type=crypto.TYPE_RSA, digest='sha1'):
"""
Get a new self-signed certificate
@type bits: int
@type digest: str
@rtype: Certificate
"""
self.log.debug('Creating a new self-signed SSL certificate')
# Generate the key and ready our cert
key = crypto.PKey()
key.generate_key(type, bits)
cert = crypto.X509()
# Fill in some pseudo certificate information with a wildcard common name
cert.get_subject().C = 'US'
cert.get_subject().ST = 'California'
cert.get_subject().L = 'Los Angeles'
cert.get_subject().O = 'Wright Anything Agency'
cert.get_subject().OU = 'Law firm / talent agency'
cert.get_subject().CN = '*.{dn}'.format(dn=self.site.domain.name)
# Set the serial number, expiration and issued
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(315360000)
cert.set_issuer(cert.get_subject())
# Map the key and sign our certificate
cert.set_pubkey(key)
cert.sign(key, digest)
# Dump the PEM data and return a certificate container
_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
return Certificate(_cert, _key, type, bits, digest) | python | def get(self, bits=2048, type=crypto.TYPE_RSA, digest='sha1'):
"""
Get a new self-signed certificate
@type bits: int
@type digest: str
@rtype: Certificate
"""
self.log.debug('Creating a new self-signed SSL certificate')
# Generate the key and ready our cert
key = crypto.PKey()
key.generate_key(type, bits)
cert = crypto.X509()
# Fill in some pseudo certificate information with a wildcard common name
cert.get_subject().C = 'US'
cert.get_subject().ST = 'California'
cert.get_subject().L = 'Los Angeles'
cert.get_subject().O = 'Wright Anything Agency'
cert.get_subject().OU = 'Law firm / talent agency'
cert.get_subject().CN = '*.{dn}'.format(dn=self.site.domain.name)
# Set the serial number, expiration and issued
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(315360000)
cert.set_issuer(cert.get_subject())
# Map the key and sign our certificate
cert.set_pubkey(key)
cert.sign(key, digest)
# Dump the PEM data and return a certificate container
_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
return Certificate(_cert, _key, type, bits, digest) | [
"def",
"get",
"(",
"self",
",",
"bits",
"=",
"2048",
",",
"type",
"=",
"crypto",
".",
"TYPE_RSA",
",",
"digest",
"=",
"'sha1'",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating a new self-signed SSL certificate'",
")",
"# Generate the key and ready our cert",
"key",
"=",
"crypto",
".",
"PKey",
"(",
")",
"key",
".",
"generate_key",
"(",
"type",
",",
"bits",
")",
"cert",
"=",
"crypto",
".",
"X509",
"(",
")",
"# Fill in some pseudo certificate information with a wildcard common name",
"cert",
".",
"get_subject",
"(",
")",
".",
"C",
"=",
"'US'",
"cert",
".",
"get_subject",
"(",
")",
".",
"ST",
"=",
"'California'",
"cert",
".",
"get_subject",
"(",
")",
".",
"L",
"=",
"'Los Angeles'",
"cert",
".",
"get_subject",
"(",
")",
".",
"O",
"=",
"'Wright Anything Agency'",
"cert",
".",
"get_subject",
"(",
")",
".",
"OU",
"=",
"'Law firm / talent agency'",
"cert",
".",
"get_subject",
"(",
")",
".",
"CN",
"=",
"'*.{dn}'",
".",
"format",
"(",
"dn",
"=",
"self",
".",
"site",
".",
"domain",
".",
"name",
")",
"# Set the serial number, expiration and issued",
"cert",
".",
"set_serial_number",
"(",
"1000",
")",
"cert",
".",
"gmtime_adj_notBefore",
"(",
"0",
")",
"cert",
".",
"gmtime_adj_notAfter",
"(",
"315360000",
")",
"cert",
".",
"set_issuer",
"(",
"cert",
".",
"get_subject",
"(",
")",
")",
"# Map the key and sign our certificate",
"cert",
".",
"set_pubkey",
"(",
"key",
")",
"cert",
".",
"sign",
"(",
"key",
",",
"digest",
")",
"# Dump the PEM data and return a certificate container",
"_cert",
"=",
"crypto",
".",
"dump_certificate",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"cert",
")",
"_key",
"=",
"crypto",
".",
"dump_privatekey",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"key",
")",
"return",
"Certificate",
"(",
"_cert",
",",
"_key",
",",
"type",
",",
"bits",
",",
"digest",
")"
] | Get a new self-signed certificate
@type bits: int
@type digest: str
@rtype: Certificate | [
"Get",
"a",
"new",
"self",
"-",
"signed",
"certificate"
] | 7b1d6d095034dd8befb026d9315ecc6494d52269 | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/common/ssl.py#L18-L53 |
246,503 | treycucco/bidon | bidon/util/convert.py | to_compressed_string | def to_compressed_string(val, max_length=0):
"""Converts val to a compressed string.
A compressed string is one with no leading or trailing spaces.
If val is None, or is blank (all spaces) None is returned.
If max_length > 0 and the stripped val is greater than max_length, val[:max_length] is returned.
"""
if val is None or len(val) == 0:
return None
rval = " ".join(val.split())
if len(rval) == 0:
return None
if max_length == 0:
return rval
else:
return rval[:max_length] | python | def to_compressed_string(val, max_length=0):
"""Converts val to a compressed string.
A compressed string is one with no leading or trailing spaces.
If val is None, or is blank (all spaces) None is returned.
If max_length > 0 and the stripped val is greater than max_length, val[:max_length] is returned.
"""
if val is None or len(val) == 0:
return None
rval = " ".join(val.split())
if len(rval) == 0:
return None
if max_length == 0:
return rval
else:
return rval[:max_length] | [
"def",
"to_compressed_string",
"(",
"val",
",",
"max_length",
"=",
"0",
")",
":",
"if",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
":",
"return",
"None",
"rval",
"=",
"\" \"",
".",
"join",
"(",
"val",
".",
"split",
"(",
")",
")",
"if",
"len",
"(",
"rval",
")",
"==",
"0",
":",
"return",
"None",
"if",
"max_length",
"==",
"0",
":",
"return",
"rval",
"else",
":",
"return",
"rval",
"[",
":",
"max_length",
"]"
] | Converts val to a compressed string.
A compressed string is one with no leading or trailing spaces.
If val is None, or is blank (all spaces) None is returned.
If max_length > 0 and the stripped val is greater than max_length, val[:max_length] is returned. | [
"Converts",
"val",
"to",
"a",
"compressed",
"string",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/convert.py#L55-L72 |
246,504 | treycucco/bidon | bidon/util/convert.py | incrementor | def incrementor(start=0, step=1):
"""Returns a function that first returns the start value, and returns previous value + step on
each subsequent call.
"""
def fxn(_):
"""Returns the next value in the sequnce defined by [start::step)"""
nonlocal start
rval = start
start += step
return rval
return fxn | python | def incrementor(start=0, step=1):
"""Returns a function that first returns the start value, and returns previous value + step on
each subsequent call.
"""
def fxn(_):
"""Returns the next value in the sequnce defined by [start::step)"""
nonlocal start
rval = start
start += step
return rval
return fxn | [
"def",
"incrementor",
"(",
"start",
"=",
"0",
",",
"step",
"=",
"1",
")",
":",
"def",
"fxn",
"(",
"_",
")",
":",
"\"\"\"Returns the next value in the sequnce defined by [start::step)\"\"\"",
"nonlocal",
"start",
"rval",
"=",
"start",
"start",
"+=",
"step",
"return",
"rval",
"return",
"fxn"
] | Returns a function that first returns the start value, and returns previous value + step on
each subsequent call. | [
"Returns",
"a",
"function",
"that",
"first",
"returns",
"the",
"start",
"value",
"and",
"returns",
"previous",
"value",
"+",
"step",
"on",
"each",
"subsequent",
"call",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/convert.py#L122-L132 |
246,505 | hirokiky/uiro | uiro/static.py | generate_static_matching | def generate_static_matching(app,
directory_serve_app=DirectoryApp):
""" Creating a matching for WSGI application to serve static files
for passed app.
Static files will be collected from directory named 'static'
under passed application::
./blog/static/
This example is with an application named `blog`.
URLs for static files in static directory will begin with
/static/app_name/. so in blog app case, if the directory has
css/main.css file, the file will be published like this::
yoursite.com/static/blog/css/main.css
And you can get this URL by reversing form matching object::
matching.reverse('blog:static', path=['css', 'main.css'])
"""
static_dir = os.path.join(os.path.dirname(app.__file__),
'static')
try:
static_app = directory_serve_app(static_dir, index_page='')
except OSError:
return None
static_pattern = '/static/{app.__name__}/*path'.format(app=app)
static_name = '{app.__name__}:static'.format(app=app)
return Matching(static_pattern, static_app, static_name) | python | def generate_static_matching(app,
directory_serve_app=DirectoryApp):
""" Creating a matching for WSGI application to serve static files
for passed app.
Static files will be collected from directory named 'static'
under passed application::
./blog/static/
This example is with an application named `blog`.
URLs for static files in static directory will begin with
/static/app_name/. so in blog app case, if the directory has
css/main.css file, the file will be published like this::
yoursite.com/static/blog/css/main.css
And you can get this URL by reversing form matching object::
matching.reverse('blog:static', path=['css', 'main.css'])
"""
static_dir = os.path.join(os.path.dirname(app.__file__),
'static')
try:
static_app = directory_serve_app(static_dir, index_page='')
except OSError:
return None
static_pattern = '/static/{app.__name__}/*path'.format(app=app)
static_name = '{app.__name__}:static'.format(app=app)
return Matching(static_pattern, static_app, static_name) | [
"def",
"generate_static_matching",
"(",
"app",
",",
"directory_serve_app",
"=",
"DirectoryApp",
")",
":",
"static_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"app",
".",
"__file__",
")",
",",
"'static'",
")",
"try",
":",
"static_app",
"=",
"directory_serve_app",
"(",
"static_dir",
",",
"index_page",
"=",
"''",
")",
"except",
"OSError",
":",
"return",
"None",
"static_pattern",
"=",
"'/static/{app.__name__}/*path'",
".",
"format",
"(",
"app",
"=",
"app",
")",
"static_name",
"=",
"'{app.__name__}:static'",
".",
"format",
"(",
"app",
"=",
"app",
")",
"return",
"Matching",
"(",
"static_pattern",
",",
"static_app",
",",
"static_name",
")"
] | Creating a matching for WSGI application to serve static files
for passed app.
Static files will be collected from directory named 'static'
under passed application::
./blog/static/
This example is with an application named `blog`.
URLs for static files in static directory will begin with
/static/app_name/. so in blog app case, if the directory has
css/main.css file, the file will be published like this::
yoursite.com/static/blog/css/main.css
And you can get this URL by reversing form matching object::
matching.reverse('blog:static', path=['css', 'main.css']) | [
"Creating",
"a",
"matching",
"for",
"WSGI",
"application",
"to",
"serve",
"static",
"files",
"for",
"passed",
"app",
"."
] | 8436976b21ac9b0eac4243768f5ada12479b9e00 | https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/static.py#L8-L37 |
246,506 | hirokiky/uiro | uiro/static.py | get_static_app_matching | def get_static_app_matching(apps):
""" Returning a matching containing applications to serve static files
correspond to each passed applications.
"""
return reduce(lambda a, b: a + b,
[generate_static_matching(app)
for app in apps if app is not None]) | python | def get_static_app_matching(apps):
""" Returning a matching containing applications to serve static files
correspond to each passed applications.
"""
return reduce(lambda a, b: a + b,
[generate_static_matching(app)
for app in apps if app is not None]) | [
"def",
"get_static_app_matching",
"(",
"apps",
")",
":",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"a",
"+",
"b",
",",
"[",
"generate_static_matching",
"(",
"app",
")",
"for",
"app",
"in",
"apps",
"if",
"app",
"is",
"not",
"None",
"]",
")"
] | Returning a matching containing applications to serve static files
correspond to each passed applications. | [
"Returning",
"a",
"matching",
"containing",
"applications",
"to",
"serve",
"static",
"files",
"correspond",
"to",
"each",
"passed",
"applications",
"."
] | 8436976b21ac9b0eac4243768f5ada12479b9e00 | https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/static.py#L40-L46 |
246,507 | kxgames/vecrec | vecrec/shapes.py | Vector.random | def random(magnitude=1):
""" Create a unit vector pointing in a random direction. """
theta = random.uniform(0, 2 * math.pi)
return magnitude * Vector(math.cos(theta), math.sin(theta)) | python | def random(magnitude=1):
""" Create a unit vector pointing in a random direction. """
theta = random.uniform(0, 2 * math.pi)
return magnitude * Vector(math.cos(theta), math.sin(theta)) | [
"def",
"random",
"(",
"magnitude",
"=",
"1",
")",
":",
"theta",
"=",
"random",
".",
"uniform",
"(",
"0",
",",
"2",
"*",
"math",
".",
"pi",
")",
"return",
"magnitude",
"*",
"Vector",
"(",
"math",
".",
"cos",
"(",
"theta",
")",
",",
"math",
".",
"sin",
"(",
"theta",
")",
")"
] | Create a unit vector pointing in a random direction. | [
"Create",
"a",
"unit",
"vector",
"pointing",
"in",
"a",
"random",
"direction",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L172-L175 |
246,508 | kxgames/vecrec | vecrec/shapes.py | Vector.from_rectangle | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | python | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) | [
"def",
"from_rectangle",
"(",
"box",
")",
":",
"x",
"=",
"box",
".",
"left",
"+",
"box",
".",
"width",
"*",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"y",
"=",
"box",
".",
"bottom",
"+",
"box",
".",
"height",
"*",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"return",
"Vector",
"(",
"x",
",",
"y",
")"
] | Create a vector randomly within the given rectangle. | [
"Create",
"a",
"vector",
"randomly",
"within",
"the",
"given",
"rectangle",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L198-L202 |
246,509 | kxgames/vecrec | vecrec/shapes.py | Vector.interpolate | def interpolate(self, target, extent):
""" Move this vector towards the given towards the target by the given
extent. The extent should be between 0 and 1. """
target = cast_anything_to_vector(target)
self += extent * (target - self) | python | def interpolate(self, target, extent):
""" Move this vector towards the given towards the target by the given
extent. The extent should be between 0 and 1. """
target = cast_anything_to_vector(target)
self += extent * (target - self) | [
"def",
"interpolate",
"(",
"self",
",",
"target",
",",
"extent",
")",
":",
"target",
"=",
"cast_anything_to_vector",
"(",
"target",
")",
"self",
"+=",
"extent",
"*",
"(",
"target",
"-",
"self",
")"
] | Move this vector towards the given towards the target by the given
extent. The extent should be between 0 and 1. | [
"Move",
"this",
"vector",
"towards",
"the",
"given",
"towards",
"the",
"target",
"by",
"the",
"given",
"extent",
".",
"The",
"extent",
"should",
"be",
"between",
"0",
"and",
"1",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L231-L235 |
246,510 | kxgames/vecrec | vecrec/shapes.py | Vector.project | def project(self, axis):
""" Project this vector onto the given axis. """
projection = self.get_projection(axis)
self.assign(projection) | python | def project(self, axis):
""" Project this vector onto the given axis. """
projection = self.get_projection(axis)
self.assign(projection) | [
"def",
"project",
"(",
"self",
",",
"axis",
")",
":",
"projection",
"=",
"self",
".",
"get_projection",
"(",
"axis",
")",
"self",
".",
"assign",
"(",
"projection",
")"
] | Project this vector onto the given axis. | [
"Project",
"this",
"vector",
"onto",
"the",
"given",
"axis",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L238-L241 |
246,511 | kxgames/vecrec | vecrec/shapes.py | Vector.dot_product | def dot_product(self, other):
""" Return the dot product of the given vectors. """
return self.x * other.x + self.y * other.y | python | def dot_product(self, other):
""" Return the dot product of the given vectors. """
return self.x * other.x + self.y * other.y | [
"def",
"dot_product",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"x",
"*",
"other",
".",
"x",
"+",
"self",
".",
"y",
"*",
"other",
".",
"y"
] | Return the dot product of the given vectors. | [
"Return",
"the",
"dot",
"product",
"of",
"the",
"given",
"vectors",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L244-L246 |
246,512 | kxgames/vecrec | vecrec/shapes.py | Vector.perp_product | def perp_product(self, other):
""" Return the perp product of the given vectors. The perp product is
just a cross product where the third dimension is taken to be zero and
the result is returned as a scalar. """
return self.x * other.y - self.y * other.x | python | def perp_product(self, other):
""" Return the perp product of the given vectors. The perp product is
just a cross product where the third dimension is taken to be zero and
the result is returned as a scalar. """
return self.x * other.y - self.y * other.x | [
"def",
"perp_product",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"x",
"*",
"other",
".",
"y",
"-",
"self",
".",
"y",
"*",
"other",
".",
"x"
] | Return the perp product of the given vectors. The perp product is
just a cross product where the third dimension is taken to be zero and
the result is returned as a scalar. | [
"Return",
"the",
"perp",
"product",
"of",
"the",
"given",
"vectors",
".",
"The",
"perp",
"product",
"is",
"just",
"a",
"cross",
"product",
"where",
"the",
"third",
"dimension",
"is",
"taken",
"to",
"be",
"zero",
"and",
"the",
"result",
"is",
"returned",
"as",
"a",
"scalar",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L249-L254 |
246,513 | kxgames/vecrec | vecrec/shapes.py | Vector.rotate | def rotate(self, angle):
""" Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """
x, y = self.tuple
self.x = x * math.cos(angle) - y * math.sin(angle)
self.y = x * math.sin(angle) + y * math.cos(angle) | python | def rotate(self, angle):
""" Rotate the given vector by an angle. Angle measured in radians counter-clockwise. """
x, y = self.tuple
self.x = x * math.cos(angle) - y * math.sin(angle)
self.y = x * math.sin(angle) + y * math.cos(angle) | [
"def",
"rotate",
"(",
"self",
",",
"angle",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"tuple",
"self",
".",
"x",
"=",
"x",
"*",
"math",
".",
"cos",
"(",
"angle",
")",
"-",
"y",
"*",
"math",
".",
"sin",
"(",
"angle",
")",
"self",
".",
"y",
"=",
"x",
"*",
"math",
".",
"sin",
"(",
"angle",
")",
"+",
"y",
"*",
"math",
".",
"cos",
"(",
"angle",
")"
] | Rotate the given vector by an angle. Angle measured in radians counter-clockwise. | [
"Rotate",
"the",
"given",
"vector",
"by",
"an",
"angle",
".",
"Angle",
"measured",
"in",
"radians",
"counter",
"-",
"clockwise",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L256-L260 |
246,514 | kxgames/vecrec | vecrec/shapes.py | Vector.round | def round(self, digits=0):
""" Round the elements of the given vector to the given number of digits. """
# Meant as a way to clean up Vector.rotate()
# For example:
# V = Vector(1,0)
# V.rotate(2*pi)
#
# V is now <1.0, -2.4492935982947064e-16>, when it should be
# <1,0>. V.round(15) will correct the error in this example.
self.x = round(self.x, digits)
self.y = round(self.y, digits) | python | def round(self, digits=0):
""" Round the elements of the given vector to the given number of digits. """
# Meant as a way to clean up Vector.rotate()
# For example:
# V = Vector(1,0)
# V.rotate(2*pi)
#
# V is now <1.0, -2.4492935982947064e-16>, when it should be
# <1,0>. V.round(15) will correct the error in this example.
self.x = round(self.x, digits)
self.y = round(self.y, digits) | [
"def",
"round",
"(",
"self",
",",
"digits",
"=",
"0",
")",
":",
"# Meant as a way to clean up Vector.rotate()",
"# For example:",
"# V = Vector(1,0)",
"# V.rotate(2*pi)",
"# ",
"# V is now <1.0, -2.4492935982947064e-16>, when it should be ",
"# <1,0>. V.round(15) will correct the error in this example.",
"self",
".",
"x",
"=",
"round",
"(",
"self",
".",
"x",
",",
"digits",
")",
"self",
".",
"y",
"=",
"round",
"(",
"self",
".",
"y",
",",
"digits",
")"
] | Round the elements of the given vector to the given number of digits. | [
"Round",
"the",
"elements",
"of",
"the",
"given",
"vector",
"to",
"the",
"given",
"number",
"of",
"digits",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L262-L273 |
246,515 | kxgames/vecrec | vecrec/shapes.py | Vector.get_scaled | def get_scaled(self, magnitude):
""" Return a unit vector parallel to this one. """
result = self.copy()
result.scale(magnitude)
return result | python | def get_scaled(self, magnitude):
""" Return a unit vector parallel to this one. """
result = self.copy()
result.scale(magnitude)
return result | [
"def",
"get_scaled",
"(",
"self",
",",
"magnitude",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"scale",
"(",
"magnitude",
")",
"return",
"result"
] | Return a unit vector parallel to this one. | [
"Return",
"a",
"unit",
"vector",
"parallel",
"to",
"this",
"one",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L412-L416 |
246,516 | kxgames/vecrec | vecrec/shapes.py | Vector.get_interpolated | def get_interpolated(self, target, extent):
""" Return a new vector that has been moved towards the given target by
the given extent. The extent should be between 0 and 1. """
result = self.copy()
result.interpolate(target, extent)
return result | python | def get_interpolated(self, target, extent):
""" Return a new vector that has been moved towards the given target by
the given extent. The extent should be between 0 and 1. """
result = self.copy()
result.interpolate(target, extent)
return result | [
"def",
"get_interpolated",
"(",
"self",
",",
"target",
",",
"extent",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"interpolate",
"(",
"target",
",",
"extent",
")",
"return",
"result"
] | Return a new vector that has been moved towards the given target by
the given extent. The extent should be between 0 and 1. | [
"Return",
"a",
"new",
"vector",
"that",
"has",
"been",
"moved",
"towards",
"the",
"given",
"target",
"by",
"the",
"given",
"extent",
".",
"The",
"extent",
"should",
"be",
"between",
"0",
"and",
"1",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L418-L423 |
246,517 | kxgames/vecrec | vecrec/shapes.py | Vector.get_projection | def get_projection(self, axis):
""" Return the projection of this vector onto the given axis. The
axis does not need to be normalized. """
scale = axis.dot(self) / axis.dot(axis)
return axis * scale | python | def get_projection(self, axis):
""" Return the projection of this vector onto the given axis. The
axis does not need to be normalized. """
scale = axis.dot(self) / axis.dot(axis)
return axis * scale | [
"def",
"get_projection",
"(",
"self",
",",
"axis",
")",
":",
"scale",
"=",
"axis",
".",
"dot",
"(",
"self",
")",
"/",
"axis",
".",
"dot",
"(",
"axis",
")",
"return",
"axis",
"*",
"scale"
] | Return the projection of this vector onto the given axis. The
axis does not need to be normalized. | [
"Return",
"the",
"projection",
"of",
"this",
"vector",
"onto",
"the",
"given",
"axis",
".",
"The",
"axis",
"does",
"not",
"need",
"to",
"be",
"normalized",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L426-L430 |
246,518 | kxgames/vecrec | vecrec/shapes.py | Vector.get_components | def get_components(self, other):
""" Break this vector into one vector that is perpendicular to the
given vector and another that is parallel to it. """
tangent = self.get_projection(other)
normal = self - tangent
return normal, tangent | python | def get_components(self, other):
""" Break this vector into one vector that is perpendicular to the
given vector and another that is parallel to it. """
tangent = self.get_projection(other)
normal = self - tangent
return normal, tangent | [
"def",
"get_components",
"(",
"self",
",",
"other",
")",
":",
"tangent",
"=",
"self",
".",
"get_projection",
"(",
"other",
")",
"normal",
"=",
"self",
"-",
"tangent",
"return",
"normal",
",",
"tangent"
] | Break this vector into one vector that is perpendicular to the
given vector and another that is parallel to it. | [
"Break",
"this",
"vector",
"into",
"one",
"vector",
"that",
"is",
"perpendicular",
"to",
"the",
"given",
"vector",
"and",
"another",
"that",
"is",
"parallel",
"to",
"it",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L433-L438 |
246,519 | kxgames/vecrec | vecrec/shapes.py | Vector.get_radians | def get_radians(self):
""" Return the angle between this vector and the positive x-axis
measured in radians. Result will be between -pi and pi. """
if not self: raise NullVectorError()
return math.atan2(self.y, self.x) | python | def get_radians(self):
""" Return the angle between this vector and the positive x-axis
measured in radians. Result will be between -pi and pi. """
if not self: raise NullVectorError()
return math.atan2(self.y, self.x) | [
"def",
"get_radians",
"(",
"self",
")",
":",
"if",
"not",
"self",
":",
"raise",
"NullVectorError",
"(",
")",
"return",
"math",
".",
"atan2",
"(",
"self",
".",
"y",
",",
"self",
".",
"x",
")"
] | Return the angle between this vector and the positive x-axis
measured in radians. Result will be between -pi and pi. | [
"Return",
"the",
"angle",
"between",
"this",
"vector",
"and",
"the",
"positive",
"x",
"-",
"axis",
"measured",
"in",
"radians",
".",
"Result",
"will",
"be",
"between",
"-",
"pi",
"and",
"pi",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L440-L444 |
246,520 | kxgames/vecrec | vecrec/shapes.py | Vector.get_rotated | def get_rotated(self, angle):
""" Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """
result = self.copy()
result.rotate(angle)
return result | python | def get_rotated(self, angle):
""" Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """
result = self.copy()
result.rotate(angle)
return result | [
"def",
"get_rotated",
"(",
"self",
",",
"angle",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"rotate",
"(",
"angle",
")",
"return",
"result"
] | Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. | [
"Return",
"a",
"vector",
"rotated",
"by",
"angle",
"from",
"the",
"given",
"vector",
".",
"Angle",
"measured",
"in",
"radians",
"counter",
"-",
"clockwise",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L468-L472 |
246,521 | kxgames/vecrec | vecrec/shapes.py | Vector.get_rounded | def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | python | def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | [
"def",
"get_rounded",
"(",
"self",
",",
"digits",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"round",
"(",
"digits",
")",
"return",
"result"
] | Return a vector with the elements rounded to the given number of digits. | [
"Return",
"a",
"vector",
"with",
"the",
"elements",
"rounded",
"to",
"the",
"given",
"number",
"of",
"digits",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L474-L478 |
246,522 | kxgames/vecrec | vecrec/shapes.py | Vector.set_radians | def set_radians(self, angle):
""" Set the angle that this vector makes with the x-axis. """
self.x, self.y = math.cos(angle), math.sin(angle) | python | def set_radians(self, angle):
""" Set the angle that this vector makes with the x-axis. """
self.x, self.y = math.cos(angle), math.sin(angle) | [
"def",
"set_radians",
"(",
"self",
",",
"angle",
")",
":",
"self",
".",
"x",
",",
"self",
".",
"y",
"=",
"math",
".",
"cos",
"(",
"angle",
")",
",",
"math",
".",
"sin",
"(",
"angle",
")"
] | Set the angle that this vector makes with the x-axis. | [
"Set",
"the",
"angle",
"that",
"this",
"vector",
"makes",
"with",
"the",
"x",
"-",
"axis",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L496-L498 |
246,523 | kxgames/vecrec | vecrec/shapes.py | Rectangle.grow | def grow(self, *padding):
""" Grow this rectangle by the given padding on all sides. """
try:
lpad, rpad, tpad, bpad = padding
except ValueError:
lpad = rpad = tpad = bpad = padding[0]
self._bottom -= bpad
self._left -= lpad
self._width += lpad + rpad
self._height += tpad + bpad
return self | python | def grow(self, *padding):
""" Grow this rectangle by the given padding on all sides. """
try:
lpad, rpad, tpad, bpad = padding
except ValueError:
lpad = rpad = tpad = bpad = padding[0]
self._bottom -= bpad
self._left -= lpad
self._width += lpad + rpad
self._height += tpad + bpad
return self | [
"def",
"grow",
"(",
"self",
",",
"*",
"padding",
")",
":",
"try",
":",
"lpad",
",",
"rpad",
",",
"tpad",
",",
"bpad",
"=",
"padding",
"except",
"ValueError",
":",
"lpad",
"=",
"rpad",
"=",
"tpad",
"=",
"bpad",
"=",
"padding",
"[",
"0",
"]",
"self",
".",
"_bottom",
"-=",
"bpad",
"self",
".",
"_left",
"-=",
"lpad",
"self",
".",
"_width",
"+=",
"lpad",
"+",
"rpad",
"self",
".",
"_height",
"+=",
"tpad",
"+",
"bpad",
"return",
"self"
] | Grow this rectangle by the given padding on all sides. | [
"Grow",
"this",
"rectangle",
"by",
"the",
"given",
"padding",
"on",
"all",
"sides",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L676-L687 |
246,524 | kxgames/vecrec | vecrec/shapes.py | Rectangle.displace | def displace(self, vector):
""" Displace this rectangle by the given vector. """
self._bottom += vector.y
self._left += vector.x
return self | python | def displace(self, vector):
""" Displace this rectangle by the given vector. """
self._bottom += vector.y
self._left += vector.x
return self | [
"def",
"displace",
"(",
"self",
",",
"vector",
")",
":",
"self",
".",
"_bottom",
"+=",
"vector",
".",
"y",
"self",
".",
"_left",
"+=",
"vector",
".",
"x",
"return",
"self"
] | Displace this rectangle by the given vector. | [
"Displace",
"this",
"rectangle",
"by",
"the",
"given",
"vector",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L703-L707 |
246,525 | kxgames/vecrec | vecrec/shapes.py | Rectangle.round | def round(self, digits=0):
""" Round the dimensions of the given rectangle to the given number of digits. """
self._left = round(self._left, digits)
self._bottom = round(self._bottom, digits)
self._width = round(self._width, digits)
self._height = round(self._height, digits) | python | def round(self, digits=0):
""" Round the dimensions of the given rectangle to the given number of digits. """
self._left = round(self._left, digits)
self._bottom = round(self._bottom, digits)
self._width = round(self._width, digits)
self._height = round(self._height, digits) | [
"def",
"round",
"(",
"self",
",",
"digits",
"=",
"0",
")",
":",
"self",
".",
"_left",
"=",
"round",
"(",
"self",
".",
"_left",
",",
"digits",
")",
"self",
".",
"_bottom",
"=",
"round",
"(",
"self",
".",
"_bottom",
",",
"digits",
")",
"self",
".",
"_width",
"=",
"round",
"(",
"self",
".",
"_width",
",",
"digits",
")",
"self",
".",
"_height",
"=",
"round",
"(",
"self",
".",
"_height",
",",
"digits",
")"
] | Round the dimensions of the given rectangle to the given number of digits. | [
"Round",
"the",
"dimensions",
"of",
"the",
"given",
"rectangle",
"to",
"the",
"given",
"number",
"of",
"digits",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L709-L714 |
246,526 | kxgames/vecrec | vecrec/shapes.py | Rectangle.set | def set(self, shape):
""" Fill this rectangle with the dimensions of the given shape. """
self.bottom, self.left = shape.bottom, shape.left
self.width, self.height = shape.width, shape.height
return self | python | def set(self, shape):
""" Fill this rectangle with the dimensions of the given shape. """
self.bottom, self.left = shape.bottom, shape.left
self.width, self.height = shape.width, shape.height
return self | [
"def",
"set",
"(",
"self",
",",
"shape",
")",
":",
"self",
".",
"bottom",
",",
"self",
".",
"left",
"=",
"shape",
".",
"bottom",
",",
"shape",
".",
"left",
"self",
".",
"width",
",",
"self",
".",
"height",
"=",
"shape",
".",
"width",
",",
"shape",
".",
"height",
"return",
"self"
] | Fill this rectangle with the dimensions of the given shape. | [
"Fill",
"this",
"rectangle",
"with",
"the",
"dimensions",
"of",
"the",
"given",
"shape",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L716-L720 |
246,527 | kxgames/vecrec | vecrec/shapes.py | Rectangle.inside | def inside(self, other):
""" Return true if this rectangle is inside the given shape. """
return ( self.left >= other.left and
self.right <= other.right and
self.top <= other.top and
self.bottom >= other.bottom) | python | def inside(self, other):
""" Return true if this rectangle is inside the given shape. """
return ( self.left >= other.left and
self.right <= other.right and
self.top <= other.top and
self.bottom >= other.bottom) | [
"def",
"inside",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"left",
">=",
"other",
".",
"left",
"and",
"self",
".",
"right",
"<=",
"other",
".",
"right",
"and",
"self",
".",
"top",
"<=",
"other",
".",
"top",
"and",
"self",
".",
"bottom",
">=",
"other",
".",
"bottom",
")"
] | Return true if this rectangle is inside the given shape. | [
"Return",
"true",
"if",
"this",
"rectangle",
"is",
"inside",
"the",
"given",
"shape",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L729-L734 |
246,528 | kxgames/vecrec | vecrec/shapes.py | Rectangle.touching | def touching(self, other):
""" Return true if this rectangle is touching the given shape. """
if self.top < other.bottom: return False
if self.bottom > other.top: return False
if self.left > other.right: return False
if self.right < other.left: return False
return True | python | def touching(self, other):
""" Return true if this rectangle is touching the given shape. """
if self.top < other.bottom: return False
if self.bottom > other.top: return False
if self.left > other.right: return False
if self.right < other.left: return False
return True | [
"def",
"touching",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"top",
"<",
"other",
".",
"bottom",
":",
"return",
"False",
"if",
"self",
".",
"bottom",
">",
"other",
".",
"top",
":",
"return",
"False",
"if",
"self",
".",
"left",
">",
"other",
".",
"right",
":",
"return",
"False",
"if",
"self",
".",
"right",
"<",
"other",
".",
"left",
":",
"return",
"False",
"return",
"True"
] | Return true if this rectangle is touching the given shape. | [
"Return",
"true",
"if",
"this",
"rectangle",
"is",
"touching",
"the",
"given",
"shape",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L742-L750 |
246,529 | kxgames/vecrec | vecrec/shapes.py | Rectangle.contains | def contains(self, other):
""" Return true if the given shape is inside this rectangle. """
return (self.left <= other.left and
self.right >= other.right and
self.top >= other.top and
self.bottom <= other.bottom) | python | def contains(self, other):
""" Return true if the given shape is inside this rectangle. """
return (self.left <= other.left and
self.right >= other.right and
self.top >= other.top and
self.bottom <= other.bottom) | [
"def",
"contains",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"left",
"<=",
"other",
".",
"left",
"and",
"self",
".",
"right",
">=",
"other",
".",
"right",
"and",
"self",
".",
"top",
">=",
"other",
".",
"top",
"and",
"self",
".",
"bottom",
"<=",
"other",
".",
"bottom",
")"
] | Return true if the given shape is inside this rectangle. | [
"Return",
"true",
"if",
"the",
"given",
"shape",
"is",
"inside",
"this",
"rectangle",
"."
] | 18b0841419de21a644b4511e2229af853ed09529 | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L753-L758 |
246,530 | treycucco/bidon | bidon/experimental/finite_state_machine.py | FiniteStateMachine.parse | def parse(self, nodes):
"""Given a stream of node data, try to parse the nodes according to the machine's graph."""
self.last_node_type = self.initial_node_type
for node_number, node in enumerate(nodes):
try:
self.step(node)
except Exception as ex:
raise Exception("An error occurred on node {}".format(node_number)) from ex | python | def parse(self, nodes):
"""Given a stream of node data, try to parse the nodes according to the machine's graph."""
self.last_node_type = self.initial_node_type
for node_number, node in enumerate(nodes):
try:
self.step(node)
except Exception as ex:
raise Exception("An error occurred on node {}".format(node_number)) from ex | [
"def",
"parse",
"(",
"self",
",",
"nodes",
")",
":",
"self",
".",
"last_node_type",
"=",
"self",
".",
"initial_node_type",
"for",
"node_number",
",",
"node",
"in",
"enumerate",
"(",
"nodes",
")",
":",
"try",
":",
"self",
".",
"step",
"(",
"node",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"\"An error occurred on node {}\"",
".",
"format",
"(",
"node_number",
")",
")",
"from",
"ex"
] | Given a stream of node data, try to parse the nodes according to the machine's graph. | [
"Given",
"a",
"stream",
"of",
"node",
"data",
"try",
"to",
"parse",
"the",
"nodes",
"according",
"to",
"the",
"machine",
"s",
"graph",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/experimental/finite_state_machine.py#L42-L49 |
246,531 | limpyd/redis-limpyd-extensions | limpyd_extensions/dynamic/related.py | DynamicRelatedFieldMixin.get_name_for | def get_name_for(self, dynamic_part):
"""
Return the name for the current dynamic field, accepting a limpyd
instance for the dynamic part
"""
dynamic_part = self.from_python(dynamic_part)
return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part) | python | def get_name_for(self, dynamic_part):
"""
Return the name for the current dynamic field, accepting a limpyd
instance for the dynamic part
"""
dynamic_part = self.from_python(dynamic_part)
return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part) | [
"def",
"get_name_for",
"(",
"self",
",",
"dynamic_part",
")",
":",
"dynamic_part",
"=",
"self",
".",
"from_python",
"(",
"dynamic_part",
")",
"return",
"super",
"(",
"DynamicRelatedFieldMixin",
",",
"self",
")",
".",
"get_name_for",
"(",
"dynamic_part",
")"
] | Return the name for the current dynamic field, accepting a limpyd
instance for the dynamic part | [
"Return",
"the",
"name",
"for",
"the",
"current",
"dynamic",
"field",
"accepting",
"a",
"limpyd",
"instance",
"for",
"the",
"dynamic",
"part"
] | 13f34e39efd2f802761457da30ab2a4213b63934 | https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/related.py#L67-L73 |
246,532 | etcher-be/elib_config | elib_config/_value/_config_value_toml.py | ConfigValueTOML.add_to_toml_obj | def add_to_toml_obj(self, toml_obj: tomlkit.container.Container, not_set: str):
"""
Updates the given container in-place with this ConfigValue
:param toml_obj: container to update
:type toml_obj: tomlkit.container.Containers
:param not_set: random UUID used to denote a value that has no default
:type not_set: str
"""
self._toml_add_description(toml_obj)
self._toml_add_value_type(toml_obj)
self._toml_add_comments(toml_obj)
toml_obj.add(tomlkit.comment(''))
self._toml_add_value(toml_obj, not_set) | python | def add_to_toml_obj(self, toml_obj: tomlkit.container.Container, not_set: str):
"""
Updates the given container in-place with this ConfigValue
:param toml_obj: container to update
:type toml_obj: tomlkit.container.Containers
:param not_set: random UUID used to denote a value that has no default
:type not_set: str
"""
self._toml_add_description(toml_obj)
self._toml_add_value_type(toml_obj)
self._toml_add_comments(toml_obj)
toml_obj.add(tomlkit.comment(''))
self._toml_add_value(toml_obj, not_set) | [
"def",
"add_to_toml_obj",
"(",
"self",
",",
"toml_obj",
":",
"tomlkit",
".",
"container",
".",
"Container",
",",
"not_set",
":",
"str",
")",
":",
"self",
".",
"_toml_add_description",
"(",
"toml_obj",
")",
"self",
".",
"_toml_add_value_type",
"(",
"toml_obj",
")",
"self",
".",
"_toml_add_comments",
"(",
"toml_obj",
")",
"toml_obj",
".",
"add",
"(",
"tomlkit",
".",
"comment",
"(",
"''",
")",
")",
"self",
".",
"_toml_add_value",
"(",
"toml_obj",
",",
"not_set",
")"
] | Updates the given container in-place with this ConfigValue
:param toml_obj: container to update
:type toml_obj: tomlkit.container.Containers
:param not_set: random UUID used to denote a value that has no default
:type not_set: str | [
"Updates",
"the",
"given",
"container",
"in",
"-",
"place",
"with",
"this",
"ConfigValue"
] | 5d8c839e84d70126620ab0186dc1f717e5868bd0 | https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_value/_config_value_toml.py#L78-L91 |
246,533 | ulf1/oxyba | oxyba/jackknife_stats.py | jackknife_stats | def jackknife_stats(theta_subs, theta_full, N=None, d=1):
"""Compute Jackknife Estimates, SE, Bias, t-scores, p-values
Parameters:
-----------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e. C=binocoeff(N,d)
subsamples, and M parameters that are returned
by the model.
theta_full : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for the full sample.
It is a <1 x M> vecotr with the M parameters
that are returned by the model.
N : int
The number of observations in the full sample.
Is required for Delete-d Jackknife, i.e. d>1.
(Default is N=None)
d : int
The number of observations to leave out for
each Jackknife subsample, i.e. the subsample
size is N-d. (The default is d=1 for the
"Delete-1 Jackknife" procedure.)
Returns:
--------
pvalues : ndarray
The two-sided P-values of the t-Score for each
Jackknife estimate.
(In Social Sciences pval<0.05 is referred as
acceptable but it is usually better to look
for p-values way closer to Zero. Just remove
or replace a variable/feature with high
pval>=pcritical and run the Jackknife again.)
tscores : ndarray
The t-Score for each Jackknife estimate.
(As rule of thumb a value abs(tscore)>2 indicates
a bad model parameter but jsut check the p-value.)
theta_jack : ndarray
The bias-corrected Jackknife Estimates (model
parameter, metric, coefficient, etc.). Use the
parameters for prediction.
se_jack : ndarray
The Jackknife Standard Error
theta_biased : ndarray
The biased Jackknife Estimate.
Other Variables:
----------------
These variables occur in the source code as
intermediate results.
Q : int
The Number of independent variables of
a model (incl. intercept).
C : int
The number of Jackknife subsamples if d>1.
There are C=binocoeff(N,d) combinations.
"""
# The biased Jackknife Estimate
import numpy as np
theta_biased = np.mean(theta_subs, axis=0)
# Inflation Factor for the Jackknife Standard Error
if d is 1:
if N is None:
N = theta_subs.shape[0]
inflation = (N - 1) / N
elif d > 1:
if N is None:
raise Exception((
"If d>1 then you must provide N (number of "
"observations in the full sample)"))
C = theta_subs.shape[0]
inflation = ((N - d) / d) / C
# The Jackknife Standard Error
se_jack = np.sqrt(
inflation * np.sum((theta_subs - theta_biased)**2, axis=0))
# The bias-corrected Jackknife Estimate
theta_jack = N * theta_full - (N - 1) * theta_biased
# The Jackknife t-Statistics
tscores = theta_jack / se_jack
# Two-sided P-values
import scipy.stats
Q = theta_subs.shape[1]
pvalues = scipy.stats.t.sf(np.abs(tscores), N - Q - d) * 2
# done
return pvalues, tscores, theta_jack, se_jack, theta_biased | python | def jackknife_stats(theta_subs, theta_full, N=None, d=1):
"""Compute Jackknife Estimates, SE, Bias, t-scores, p-values
Parameters:
-----------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e. C=binocoeff(N,d)
subsamples, and M parameters that are returned
by the model.
theta_full : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for the full sample.
It is a <1 x M> vecotr with the M parameters
that are returned by the model.
N : int
The number of observations in the full sample.
Is required for Delete-d Jackknife, i.e. d>1.
(Default is N=None)
d : int
The number of observations to leave out for
each Jackknife subsample, i.e. the subsample
size is N-d. (The default is d=1 for the
"Delete-1 Jackknife" procedure.)
Returns:
--------
pvalues : ndarray
The two-sided P-values of the t-Score for each
Jackknife estimate.
(In Social Sciences pval<0.05 is referred as
acceptable but it is usually better to look
for p-values way closer to Zero. Just remove
or replace a variable/feature with high
pval>=pcritical and run the Jackknife again.)
tscores : ndarray
The t-Score for each Jackknife estimate.
(As rule of thumb a value abs(tscore)>2 indicates
a bad model parameter but jsut check the p-value.)
theta_jack : ndarray
The bias-corrected Jackknife Estimates (model
parameter, metric, coefficient, etc.). Use the
parameters for prediction.
se_jack : ndarray
The Jackknife Standard Error
theta_biased : ndarray
The biased Jackknife Estimate.
Other Variables:
----------------
These variables occur in the source code as
intermediate results.
Q : int
The Number of independent variables of
a model (incl. intercept).
C : int
The number of Jackknife subsamples if d>1.
There are C=binocoeff(N,d) combinations.
"""
# The biased Jackknife Estimate
import numpy as np
theta_biased = np.mean(theta_subs, axis=0)
# Inflation Factor for the Jackknife Standard Error
if d is 1:
if N is None:
N = theta_subs.shape[0]
inflation = (N - 1) / N
elif d > 1:
if N is None:
raise Exception((
"If d>1 then you must provide N (number of "
"observations in the full sample)"))
C = theta_subs.shape[0]
inflation = ((N - d) / d) / C
# The Jackknife Standard Error
se_jack = np.sqrt(
inflation * np.sum((theta_subs - theta_biased)**2, axis=0))
# The bias-corrected Jackknife Estimate
theta_jack = N * theta_full - (N - 1) * theta_biased
# The Jackknife t-Statistics
tscores = theta_jack / se_jack
# Two-sided P-values
import scipy.stats
Q = theta_subs.shape[1]
pvalues = scipy.stats.t.sf(np.abs(tscores), N - Q - d) * 2
# done
return pvalues, tscores, theta_jack, se_jack, theta_biased | [
"def",
"jackknife_stats",
"(",
"theta_subs",
",",
"theta_full",
",",
"N",
"=",
"None",
",",
"d",
"=",
"1",
")",
":",
"# The biased Jackknife Estimate",
"import",
"numpy",
"as",
"np",
"theta_biased",
"=",
"np",
".",
"mean",
"(",
"theta_subs",
",",
"axis",
"=",
"0",
")",
"# Inflation Factor for the Jackknife Standard Error",
"if",
"d",
"is",
"1",
":",
"if",
"N",
"is",
"None",
":",
"N",
"=",
"theta_subs",
".",
"shape",
"[",
"0",
"]",
"inflation",
"=",
"(",
"N",
"-",
"1",
")",
"/",
"N",
"elif",
"d",
">",
"1",
":",
"if",
"N",
"is",
"None",
":",
"raise",
"Exception",
"(",
"(",
"\"If d>1 then you must provide N (number of \"",
"\"observations in the full sample)\"",
")",
")",
"C",
"=",
"theta_subs",
".",
"shape",
"[",
"0",
"]",
"inflation",
"=",
"(",
"(",
"N",
"-",
"d",
")",
"/",
"d",
")",
"/",
"C",
"# The Jackknife Standard Error",
"se_jack",
"=",
"np",
".",
"sqrt",
"(",
"inflation",
"*",
"np",
".",
"sum",
"(",
"(",
"theta_subs",
"-",
"theta_biased",
")",
"**",
"2",
",",
"axis",
"=",
"0",
")",
")",
"# The bias-corrected Jackknife Estimate",
"theta_jack",
"=",
"N",
"*",
"theta_full",
"-",
"(",
"N",
"-",
"1",
")",
"*",
"theta_biased",
"# The Jackknife t-Statistics",
"tscores",
"=",
"theta_jack",
"/",
"se_jack",
"# Two-sided P-values",
"import",
"scipy",
".",
"stats",
"Q",
"=",
"theta_subs",
".",
"shape",
"[",
"1",
"]",
"pvalues",
"=",
"scipy",
".",
"stats",
".",
"t",
".",
"sf",
"(",
"np",
".",
"abs",
"(",
"tscores",
")",
",",
"N",
"-",
"Q",
"-",
"d",
")",
"*",
"2",
"# done",
"return",
"pvalues",
",",
"tscores",
",",
"theta_jack",
",",
"se_jack",
",",
"theta_biased"
] | Compute Jackknife Estimates, SE, Bias, t-scores, p-values
Parameters:
-----------
theta_subs : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for each subsample.
It is a <C x M> matrix, i.e. C=binocoeff(N,d)
subsamples, and M parameters that are returned
by the model.
theta_full : ndarray
The metrics, estimates, parameters, etc. of
the model (see "func") for the full sample.
It is a <1 x M> vecotr with the M parameters
that are returned by the model.
N : int
The number of observations in the full sample.
Is required for Delete-d Jackknife, i.e. d>1.
(Default is N=None)
d : int
The number of observations to leave out for
each Jackknife subsample, i.e. the subsample
size is N-d. (The default is d=1 for the
"Delete-1 Jackknife" procedure.)
Returns:
--------
pvalues : ndarray
The two-sided P-values of the t-Score for each
Jackknife estimate.
(In Social Sciences pval<0.05 is referred as
acceptable but it is usually better to look
for p-values way closer to Zero. Just remove
or replace a variable/feature with high
pval>=pcritical and run the Jackknife again.)
tscores : ndarray
The t-Score for each Jackknife estimate.
(As rule of thumb a value abs(tscore)>2 indicates
a bad model parameter but jsut check the p-value.)
theta_jack : ndarray
The bias-corrected Jackknife Estimates (model
parameter, metric, coefficient, etc.). Use the
parameters for prediction.
se_jack : ndarray
The Jackknife Standard Error
theta_biased : ndarray
The biased Jackknife Estimate.
Other Variables:
----------------
These variables occur in the source code as
intermediate results.
Q : int
The Number of independent variables of
a model (incl. intercept).
C : int
The number of Jackknife subsamples if d>1.
There are C=binocoeff(N,d) combinations. | [
"Compute",
"Jackknife",
"Estimates",
"SE",
"Bias",
"t",
"-",
"scores",
"p",
"-",
"values"
] | b3043116050de275124365cb11e7df91fb40169d | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/jackknife_stats.py#L1-L105 |
246,534 | tylerbutler/propane | propane/strings.py | space_out_camel_case | def space_out_camel_case(stringAsCamelCase):
"""
Adds spaces to a camel case string. Failure to space out string returns the original string.
>>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
'DMLS Services Other BS Text LLC'
"""
pattern = re.compile(r'([A-Z][A-Z][a-z])|([a-z][A-Z])')
if stringAsCamelCase is None:
return None
return pattern.sub(lambda m: m.group()[:1] + " " + m.group()[1:], stringAsCamelCase) | python | def space_out_camel_case(stringAsCamelCase):
"""
Adds spaces to a camel case string. Failure to space out string returns the original string.
>>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
'DMLS Services Other BS Text LLC'
"""
pattern = re.compile(r'([A-Z][A-Z][a-z])|([a-z][A-Z])')
if stringAsCamelCase is None:
return None
return pattern.sub(lambda m: m.group()[:1] + " " + m.group()[1:], stringAsCamelCase) | [
"def",
"space_out_camel_case",
"(",
"stringAsCamelCase",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'([A-Z][A-Z][a-z])|([a-z][A-Z])'",
")",
"if",
"stringAsCamelCase",
"is",
"None",
":",
"return",
"None",
"return",
"pattern",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
")",
"[",
":",
"1",
"]",
"+",
"\" \"",
"+",
"m",
".",
"group",
"(",
")",
"[",
"1",
":",
"]",
",",
"stringAsCamelCase",
")"
] | Adds spaces to a camel case string. Failure to space out string returns the original string.
>>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
'DMLS Services Other BS Text LLC' | [
"Adds",
"spaces",
"to",
"a",
"camel",
"case",
"string",
".",
"Failure",
"to",
"space",
"out",
"string",
"returns",
"the",
"original",
"string",
"."
] | 6c404285ab8d78865b7175a5c8adf8fae12d6be5 | https://github.com/tylerbutler/propane/blob/6c404285ab8d78865b7175a5c8adf8fae12d6be5/propane/strings.py#L9-L21 |
246,535 | tylerbutler/propane | propane/strings.py | slugify | def slugify(text, length_limit=0, delimiter=u'-'):
"""Generates an ASCII-only slug of a string."""
result = []
for word in _punctuation_regex.split(text.lower()):
word = _available_unicode_handlers[0](word)
if word:
result.append(word)
slug = delimiter.join(result)
if length_limit > 0:
return slug[0:length_limit]
return slug | python | def slugify(text, length_limit=0, delimiter=u'-'):
"""Generates an ASCII-only slug of a string."""
result = []
for word in _punctuation_regex.split(text.lower()):
word = _available_unicode_handlers[0](word)
if word:
result.append(word)
slug = delimiter.join(result)
if length_limit > 0:
return slug[0:length_limit]
return slug | [
"def",
"slugify",
"(",
"text",
",",
"length_limit",
"=",
"0",
",",
"delimiter",
"=",
"u'-'",
")",
":",
"result",
"=",
"[",
"]",
"for",
"word",
"in",
"_punctuation_regex",
".",
"split",
"(",
"text",
".",
"lower",
"(",
")",
")",
":",
"word",
"=",
"_available_unicode_handlers",
"[",
"0",
"]",
"(",
"word",
")",
"if",
"word",
":",
"result",
".",
"append",
"(",
"word",
")",
"slug",
"=",
"delimiter",
".",
"join",
"(",
"result",
")",
"if",
"length_limit",
">",
"0",
":",
"return",
"slug",
"[",
"0",
":",
"length_limit",
"]",
"return",
"slug"
] | Generates an ASCII-only slug of a string. | [
"Generates",
"an",
"ASCII",
"-",
"only",
"slug",
"of",
"a",
"string",
"."
] | 6c404285ab8d78865b7175a5c8adf8fae12d6be5 | https://github.com/tylerbutler/propane/blob/6c404285ab8d78865b7175a5c8adf8fae12d6be5/propane/strings.py#L60-L70 |
246,536 | russell/pygments-cl-repl | pygments_cl_repl/__init__.py | sexp_reader.read | def read(self, stream):
"""
Will parse the stream until a complete sexp has been read.
Returns True until state is complete.
"""
stack = self.stack
while True:
if stack[0]: # will be true once one sexp has been parsed
self.rest_string = stream
return False
c = stream.read(1)
if not c:
# no more stream and no complete sexp
return True
reading = type(stack[-1])
self.sexp_string.write(c)
if reading == tuple:
if c in atom_end:
atom = stack.pop()
stack[-1].append(atom)
reading = type(stack[-1])
if reading == list:
if c == '(':
stack.append([])
elif c == ')':
stack[-2].append(stack.pop())
elif c == '"':
stack.append('')
elif c == "'":
continue
elif c in whitespace:
continue
else:
stack.append(tuple())
elif reading == str:
if c == '"':
stack.pop()
# escaped char coming up, so read ahead
elif c == '\\':
self.sexp_string.write(stream.read(1)) | python | def read(self, stream):
"""
Will parse the stream until a complete sexp has been read.
Returns True until state is complete.
"""
stack = self.stack
while True:
if stack[0]: # will be true once one sexp has been parsed
self.rest_string = stream
return False
c = stream.read(1)
if not c:
# no more stream and no complete sexp
return True
reading = type(stack[-1])
self.sexp_string.write(c)
if reading == tuple:
if c in atom_end:
atom = stack.pop()
stack[-1].append(atom)
reading = type(stack[-1])
if reading == list:
if c == '(':
stack.append([])
elif c == ')':
stack[-2].append(stack.pop())
elif c == '"':
stack.append('')
elif c == "'":
continue
elif c in whitespace:
continue
else:
stack.append(tuple())
elif reading == str:
if c == '"':
stack.pop()
# escaped char coming up, so read ahead
elif c == '\\':
self.sexp_string.write(stream.read(1)) | [
"def",
"read",
"(",
"self",
",",
"stream",
")",
":",
"stack",
"=",
"self",
".",
"stack",
"while",
"True",
":",
"if",
"stack",
"[",
"0",
"]",
":",
"# will be true once one sexp has been parsed",
"self",
".",
"rest_string",
"=",
"stream",
"return",
"False",
"c",
"=",
"stream",
".",
"read",
"(",
"1",
")",
"if",
"not",
"c",
":",
"# no more stream and no complete sexp",
"return",
"True",
"reading",
"=",
"type",
"(",
"stack",
"[",
"-",
"1",
"]",
")",
"self",
".",
"sexp_string",
".",
"write",
"(",
"c",
")",
"if",
"reading",
"==",
"tuple",
":",
"if",
"c",
"in",
"atom_end",
":",
"atom",
"=",
"stack",
".",
"pop",
"(",
")",
"stack",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"atom",
")",
"reading",
"=",
"type",
"(",
"stack",
"[",
"-",
"1",
"]",
")",
"if",
"reading",
"==",
"list",
":",
"if",
"c",
"==",
"'('",
":",
"stack",
".",
"append",
"(",
"[",
"]",
")",
"elif",
"c",
"==",
"')'",
":",
"stack",
"[",
"-",
"2",
"]",
".",
"append",
"(",
"stack",
".",
"pop",
"(",
")",
")",
"elif",
"c",
"==",
"'\"'",
":",
"stack",
".",
"append",
"(",
"''",
")",
"elif",
"c",
"==",
"\"'\"",
":",
"continue",
"elif",
"c",
"in",
"whitespace",
":",
"continue",
"else",
":",
"stack",
".",
"append",
"(",
"tuple",
"(",
")",
")",
"elif",
"reading",
"==",
"str",
":",
"if",
"c",
"==",
"'\"'",
":",
"stack",
".",
"pop",
"(",
")",
"# escaped char coming up, so read ahead",
"elif",
"c",
"==",
"'\\\\'",
":",
"self",
".",
"sexp_string",
".",
"write",
"(",
"stream",
".",
"read",
"(",
"1",
")",
")"
] | Will parse the stream until a complete sexp has been read.
Returns True until state is complete. | [
"Will",
"parse",
"the",
"stream",
"until",
"a",
"complete",
"sexp",
"has",
"been",
"read",
".",
"Returns",
"True",
"until",
"state",
"is",
"complete",
"."
] | dff6e3ff0017b934b56f76cd54d48a6e55a52550 | https://github.com/russell/pygments-cl-repl/blob/dff6e3ff0017b934b56f76cd54d48a6e55a52550/pygments_cl_repl/__init__.py#L26-L66 |
246,537 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/filters/aleph_filter.py | name_to_vector | def name_to_vector(name):
"""
Convert `name` to the ASCII vector.
Example:
>>> name_to_vector("ing. Franta Putšálek")
['putsalek', 'franta', 'ing']
Args:
name (str): Name which will be vectorized.
Returns:
list: Vector created from name.
"""
if not isinstance(name, unicode):
name = name.decode("utf-8")
name = name.lower()
name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore')
name = "".join(filter(lambda x: x.isalpha() or x == " ", list(name)))
return sorted(name.split(), key=lambda x: len(x), reverse=True) | python | def name_to_vector(name):
"""
Convert `name` to the ASCII vector.
Example:
>>> name_to_vector("ing. Franta Putšálek")
['putsalek', 'franta', 'ing']
Args:
name (str): Name which will be vectorized.
Returns:
list: Vector created from name.
"""
if not isinstance(name, unicode):
name = name.decode("utf-8")
name = name.lower()
name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore')
name = "".join(filter(lambda x: x.isalpha() or x == " ", list(name)))
return sorted(name.split(), key=lambda x: len(x), reverse=True) | [
"def",
"name_to_vector",
"(",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"unicode",
")",
":",
"name",
"=",
"name",
".",
"decode",
"(",
"\"utf-8\"",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"name",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"name",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"name",
"=",
"\"\"",
".",
"join",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"isalpha",
"(",
")",
"or",
"x",
"==",
"\" \"",
",",
"list",
"(",
"name",
")",
")",
")",
"return",
"sorted",
"(",
"name",
".",
"split",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"len",
"(",
"x",
")",
",",
"reverse",
"=",
"True",
")"
] | Convert `name` to the ASCII vector.
Example:
>>> name_to_vector("ing. Franta Putšálek")
['putsalek', 'franta', 'ing']
Args:
name (str): Name which will be vectorized.
Returns:
list: Vector created from name. | [
"Convert",
"name",
"to",
"the",
"ASCII",
"vector",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/aleph_filter.py#L20-L41 |
246,538 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/filters/aleph_filter.py | compare_names | def compare_names(first, second):
"""
Compare two names in complicated, but more error prone way.
Algorithm is using vector comparison.
Example:
>>> compare_names("Franta Putšálek", "ing. Franta Putšálek")
100.0
>>> compare_names("F. Putšálek", "ing. Franta Putšálek")
50.0
Args:
first (str): Fisst name as string.
second (str): Second name as string.
Returns:
float: Percentage of the similarity.
"""
first = name_to_vector(first)
second = name_to_vector(second)
zipped = zip(first, second)
if not zipped:
return 0
similarity_factor = 0
for fitem, _ in zipped:
if fitem in second:
similarity_factor += 1
return (float(similarity_factor) / len(zipped)) * 100 | python | def compare_names(first, second):
"""
Compare two names in complicated, but more error prone way.
Algorithm is using vector comparison.
Example:
>>> compare_names("Franta Putšálek", "ing. Franta Putšálek")
100.0
>>> compare_names("F. Putšálek", "ing. Franta Putšálek")
50.0
Args:
first (str): Fisst name as string.
second (str): Second name as string.
Returns:
float: Percentage of the similarity.
"""
first = name_to_vector(first)
second = name_to_vector(second)
zipped = zip(first, second)
if not zipped:
return 0
similarity_factor = 0
for fitem, _ in zipped:
if fitem in second:
similarity_factor += 1
return (float(similarity_factor) / len(zipped)) * 100 | [
"def",
"compare_names",
"(",
"first",
",",
"second",
")",
":",
"first",
"=",
"name_to_vector",
"(",
"first",
")",
"second",
"=",
"name_to_vector",
"(",
"second",
")",
"zipped",
"=",
"zip",
"(",
"first",
",",
"second",
")",
"if",
"not",
"zipped",
":",
"return",
"0",
"similarity_factor",
"=",
"0",
"for",
"fitem",
",",
"_",
"in",
"zipped",
":",
"if",
"fitem",
"in",
"second",
":",
"similarity_factor",
"+=",
"1",
"return",
"(",
"float",
"(",
"similarity_factor",
")",
"/",
"len",
"(",
"zipped",
")",
")",
"*",
"100"
] | Compare two names in complicated, but more error prone way.
Algorithm is using vector comparison.
Example:
>>> compare_names("Franta Putšálek", "ing. Franta Putšálek")
100.0
>>> compare_names("F. Putšálek", "ing. Franta Putšálek")
50.0
Args:
first (str): Fisst name as string.
second (str): Second name as string.
Returns:
float: Percentage of the similarity. | [
"Compare",
"two",
"names",
"in",
"complicated",
"but",
"more",
"error",
"prone",
"way",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/aleph_filter.py#L44-L76 |
246,539 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/filters/aleph_filter.py | filter_publication | def filter_publication(publication, cmp_authors=True):
"""
Filter publications based at data from Aleph.
Args:
publication (obj): :class:`.Publication` instance.
Returns:
obj/None: None if the publication was found in Aleph or `publication` \
if not.
"""
query = None
isbn_query = False
# there can be ISBN query or book title query
if publication.optionals and publication.optionals.ISBN:
query = aleph.ISBNQuery(publication.optionals.ISBN)
isbn_query = True
else:
query = aleph.TitleQuery(publication.title)
result = aleph.reactToAMQPMessage(aleph.SearchRequest(query), "")
if not result.records:
return publication # book is not in database
# if there was results with this ISBN, compare titles of the books
# (sometimes, there are different books with same ISBN because of human
# errors)
if isbn_query:
for record in result.records:
epub = record.epublication
# try to match title of the book
if compare_names(epub.nazev, publication.title) >= 80:
return None # book already in database
return publication
# checks whether the details from returned EPublication match Publication's
for record in result.records:
epub = record.epublication
# if the title doens't match, go to next record from aleph
if not compare_names(epub.nazev, publication.title) >= 80:
continue
if not cmp_authors:
return None # book already in database
# compare authors names
for author in epub.autori:
# convert Aleph's author structure to string
author_str = "%s %s %s" % (
author.firstName,
author.lastName,
author.title
)
# normalize author data from `publication`
pub_authors = map(lambda x: x.name, publication.authors)
if type(pub_authors) not in [list, tuple, set]:
pub_authors = [pub_authors]
# try to compare authors from `publication` and Aleph
for pub_author in pub_authors:
if compare_names(author_str, pub_author) >= 50:
return None # book already in database
return publication | python | def filter_publication(publication, cmp_authors=True):
"""
Filter publications based at data from Aleph.
Args:
publication (obj): :class:`.Publication` instance.
Returns:
obj/None: None if the publication was found in Aleph or `publication` \
if not.
"""
query = None
isbn_query = False
# there can be ISBN query or book title query
if publication.optionals and publication.optionals.ISBN:
query = aleph.ISBNQuery(publication.optionals.ISBN)
isbn_query = True
else:
query = aleph.TitleQuery(publication.title)
result = aleph.reactToAMQPMessage(aleph.SearchRequest(query), "")
if not result.records:
return publication # book is not in database
# if there was results with this ISBN, compare titles of the books
# (sometimes, there are different books with same ISBN because of human
# errors)
if isbn_query:
for record in result.records:
epub = record.epublication
# try to match title of the book
if compare_names(epub.nazev, publication.title) >= 80:
return None # book already in database
return publication
# checks whether the details from returned EPublication match Publication's
for record in result.records:
epub = record.epublication
# if the title doens't match, go to next record from aleph
if not compare_names(epub.nazev, publication.title) >= 80:
continue
if not cmp_authors:
return None # book already in database
# compare authors names
for author in epub.autori:
# convert Aleph's author structure to string
author_str = "%s %s %s" % (
author.firstName,
author.lastName,
author.title
)
# normalize author data from `publication`
pub_authors = map(lambda x: x.name, publication.authors)
if type(pub_authors) not in [list, tuple, set]:
pub_authors = [pub_authors]
# try to compare authors from `publication` and Aleph
for pub_author in pub_authors:
if compare_names(author_str, pub_author) >= 50:
return None # book already in database
return publication | [
"def",
"filter_publication",
"(",
"publication",
",",
"cmp_authors",
"=",
"True",
")",
":",
"query",
"=",
"None",
"isbn_query",
"=",
"False",
"# there can be ISBN query or book title query",
"if",
"publication",
".",
"optionals",
"and",
"publication",
".",
"optionals",
".",
"ISBN",
":",
"query",
"=",
"aleph",
".",
"ISBNQuery",
"(",
"publication",
".",
"optionals",
".",
"ISBN",
")",
"isbn_query",
"=",
"True",
"else",
":",
"query",
"=",
"aleph",
".",
"TitleQuery",
"(",
"publication",
".",
"title",
")",
"result",
"=",
"aleph",
".",
"reactToAMQPMessage",
"(",
"aleph",
".",
"SearchRequest",
"(",
"query",
")",
",",
"\"\"",
")",
"if",
"not",
"result",
".",
"records",
":",
"return",
"publication",
"# book is not in database",
"# if there was results with this ISBN, compare titles of the books",
"# (sometimes, there are different books with same ISBN because of human",
"# errors)",
"if",
"isbn_query",
":",
"for",
"record",
"in",
"result",
".",
"records",
":",
"epub",
"=",
"record",
".",
"epublication",
"# try to match title of the book",
"if",
"compare_names",
"(",
"epub",
".",
"nazev",
",",
"publication",
".",
"title",
")",
">=",
"80",
":",
"return",
"None",
"# book already in database",
"return",
"publication",
"# checks whether the details from returned EPublication match Publication's",
"for",
"record",
"in",
"result",
".",
"records",
":",
"epub",
"=",
"record",
".",
"epublication",
"# if the title doens't match, go to next record from aleph",
"if",
"not",
"compare_names",
"(",
"epub",
".",
"nazev",
",",
"publication",
".",
"title",
")",
">=",
"80",
":",
"continue",
"if",
"not",
"cmp_authors",
":",
"return",
"None",
"# book already in database",
"# compare authors names",
"for",
"author",
"in",
"epub",
".",
"autori",
":",
"# convert Aleph's author structure to string",
"author_str",
"=",
"\"%s %s %s\"",
"%",
"(",
"author",
".",
"firstName",
",",
"author",
".",
"lastName",
",",
"author",
".",
"title",
")",
"# normalize author data from `publication`",
"pub_authors",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
",",
"publication",
".",
"authors",
")",
"if",
"type",
"(",
"pub_authors",
")",
"not",
"in",
"[",
"list",
",",
"tuple",
",",
"set",
"]",
":",
"pub_authors",
"=",
"[",
"pub_authors",
"]",
"# try to compare authors from `publication` and Aleph",
"for",
"pub_author",
"in",
"pub_authors",
":",
"if",
"compare_names",
"(",
"author_str",
",",
"pub_author",
")",
">=",
"50",
":",
"return",
"None",
"# book already in database",
"return",
"publication"
] | Filter publications based at data from Aleph.
Args:
publication (obj): :class:`.Publication` instance.
Returns:
obj/None: None if the publication was found in Aleph or `publication` \
if not. | [
"Filter",
"publications",
"based",
"at",
"data",
"from",
"Aleph",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/aleph_filter.py#L79-L148 |
246,540 | totokaka/pySpaceGDN | setup.py | get_long_description | def get_long_description():
""" Read the long description. """
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme:
return readme.read()
return None | python | def get_long_description():
""" Read the long description. """
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme:
return readme.read()
return None | [
"def",
"get_long_description",
"(",
")",
":",
"here",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"here",
",",
"'README.rst'",
")",
")",
"as",
"readme",
":",
"return",
"readme",
".",
"read",
"(",
")",
"return",
"None"
] | Read the long description. | [
"Read",
"the",
"long",
"description",
"."
] | 55c8be8d751e24873e0a7f7e99d2b715442ec878 | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/setup.py#L7-L12 |
246,541 | klmitch/bark | bark/format.py | ParseState.pop_state | def pop_state(self, idx=None):
"""
Pops off the most recent state.
:param idx: If provided, specifies the index at which the next
string begins.
"""
self.state.pop()
if idx is not None:
self.str_begin = idx | python | def pop_state(self, idx=None):
"""
Pops off the most recent state.
:param idx: If provided, specifies the index at which the next
string begins.
"""
self.state.pop()
if idx is not None:
self.str_begin = idx | [
"def",
"pop_state",
"(",
"self",
",",
"idx",
"=",
"None",
")",
":",
"self",
".",
"state",
".",
"pop",
"(",
")",
"if",
"idx",
"is",
"not",
"None",
":",
"self",
".",
"str_begin",
"=",
"idx"
] | Pops off the most recent state.
:param idx: If provided, specifies the index at which the next
string begins. | [
"Pops",
"off",
"the",
"most",
"recent",
"state",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L52-L63 |
246,542 | klmitch/bark | bark/format.py | ParseState.add_text | def add_text(self, end, next=None):
"""
Adds the text from string beginning to the specified ending
index to the format.
:param end: The ending index of the string.
:param next: The next string begin index. If None, the string
index will not be updated.
"""
if self.str_begin != end:
self.fmt.append_text(self.format[self.str_begin:end])
if next is not None:
self.str_begin = next | python | def add_text(self, end, next=None):
"""
Adds the text from string beginning to the specified ending
index to the format.
:param end: The ending index of the string.
:param next: The next string begin index. If None, the string
index will not be updated.
"""
if self.str_begin != end:
self.fmt.append_text(self.format[self.str_begin:end])
if next is not None:
self.str_begin = next | [
"def",
"add_text",
"(",
"self",
",",
"end",
",",
"next",
"=",
"None",
")",
":",
"if",
"self",
".",
"str_begin",
"!=",
"end",
":",
"self",
".",
"fmt",
".",
"append_text",
"(",
"self",
".",
"format",
"[",
"self",
".",
"str_begin",
":",
"end",
"]",
")",
"if",
"next",
"is",
"not",
"None",
":",
"self",
".",
"str_begin",
"=",
"next"
] | Adds the text from string beginning to the specified ending
index to the format.
:param end: The ending index of the string.
:param next: The next string begin index. If None, the string
index will not be updated. | [
"Adds",
"the",
"text",
"from",
"string",
"beginning",
"to",
"the",
"specified",
"ending",
"index",
"to",
"the",
"format",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L82-L96 |
246,543 | klmitch/bark | bark/format.py | ParseState.add_escape | def add_escape(self, idx, char):
"""
Translates and adds the escape sequence.
:param idx: Provides the ending index of the escape sequence.
:param char: The actual character that was escaped.
"""
self.fmt.append_text(self.fmt._unescape.get(
self.format[self.str_begin:idx], char)) | python | def add_escape(self, idx, char):
"""
Translates and adds the escape sequence.
:param idx: Provides the ending index of the escape sequence.
:param char: The actual character that was escaped.
"""
self.fmt.append_text(self.fmt._unescape.get(
self.format[self.str_begin:idx], char)) | [
"def",
"add_escape",
"(",
"self",
",",
"idx",
",",
"char",
")",
":",
"self",
".",
"fmt",
".",
"append_text",
"(",
"self",
".",
"fmt",
".",
"_unescape",
".",
"get",
"(",
"self",
".",
"format",
"[",
"self",
".",
"str_begin",
":",
"idx",
"]",
",",
"char",
")",
")"
] | Translates and adds the escape sequence.
:param idx: Provides the ending index of the escape sequence.
:param char: The actual character that was escaped. | [
"Translates",
"and",
"adds",
"the",
"escape",
"sequence",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L98-L107 |
246,544 | klmitch/bark | bark/format.py | ParseState.set_param | def set_param(self, idx):
"""
Adds the parameter to the conversion modifier.
:param idx: Provides the ending index of the parameter string.
"""
self.modifier.set_param(self.format[self.param_begin:idx]) | python | def set_param(self, idx):
"""
Adds the parameter to the conversion modifier.
:param idx: Provides the ending index of the parameter string.
"""
self.modifier.set_param(self.format[self.param_begin:idx]) | [
"def",
"set_param",
"(",
"self",
",",
"idx",
")",
":",
"self",
".",
"modifier",
".",
"set_param",
"(",
"self",
".",
"format",
"[",
"self",
".",
"param_begin",
":",
"idx",
"]",
")"
] | Adds the parameter to the conversion modifier.
:param idx: Provides the ending index of the parameter string. | [
"Adds",
"the",
"parameter",
"to",
"the",
"conversion",
"modifier",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L109-L116 |
246,545 | klmitch/bark | bark/format.py | ParseState.set_conversion | def set_conversion(self, idx):
"""
Adds the conversion to the format.
:param idx: The ending index of the conversion name.
"""
# First, determine the name
if self.conv_begin:
name = self.format[self.conv_begin:idx]
else:
name = self.format[idx]
# Next, add the status code modifiers, as needed
if self.codes:
self.modifier.set_codes(self.codes, self.reject)
# Append the conversion to the format
self.fmt.append_conv(self.fmt._get_conversion(name, self.modifier))
# Clear the conversion data
self.param_begin = None
self.conv_begin = None
self.modifier = None
self.codes = []
self.reject = False
self.code_last = False | python | def set_conversion(self, idx):
"""
Adds the conversion to the format.
:param idx: The ending index of the conversion name.
"""
# First, determine the name
if self.conv_begin:
name = self.format[self.conv_begin:idx]
else:
name = self.format[idx]
# Next, add the status code modifiers, as needed
if self.codes:
self.modifier.set_codes(self.codes, self.reject)
# Append the conversion to the format
self.fmt.append_conv(self.fmt._get_conversion(name, self.modifier))
# Clear the conversion data
self.param_begin = None
self.conv_begin = None
self.modifier = None
self.codes = []
self.reject = False
self.code_last = False | [
"def",
"set_conversion",
"(",
"self",
",",
"idx",
")",
":",
"# First, determine the name",
"if",
"self",
".",
"conv_begin",
":",
"name",
"=",
"self",
".",
"format",
"[",
"self",
".",
"conv_begin",
":",
"idx",
"]",
"else",
":",
"name",
"=",
"self",
".",
"format",
"[",
"idx",
"]",
"# Next, add the status code modifiers, as needed",
"if",
"self",
".",
"codes",
":",
"self",
".",
"modifier",
".",
"set_codes",
"(",
"self",
".",
"codes",
",",
"self",
".",
"reject",
")",
"# Append the conversion to the format",
"self",
".",
"fmt",
".",
"append_conv",
"(",
"self",
".",
"fmt",
".",
"_get_conversion",
"(",
"name",
",",
"self",
".",
"modifier",
")",
")",
"# Clear the conversion data",
"self",
".",
"param_begin",
"=",
"None",
"self",
".",
"conv_begin",
"=",
"None",
"self",
".",
"modifier",
"=",
"None",
"self",
".",
"codes",
"=",
"[",
"]",
"self",
".",
"reject",
"=",
"False",
"self",
".",
"code_last",
"=",
"False"
] | Adds the conversion to the format.
:param idx: The ending index of the conversion name. | [
"Adds",
"the",
"conversion",
"to",
"the",
"format",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L118-L144 |
246,546 | klmitch/bark | bark/format.py | ParseState.set_code | def set_code(self, idx):
"""
Sets a code to be filtered on for the conversion. Note that
this also sets the 'code_last' attribute and configures to
ignore the remaining characters of the code.
:param idx: The index at which the code _begins_.
:returns: True if the code is valid, False otherwise.
"""
code = self.format[idx:idx + 3]
if len(code) < 3 or not code.isdigit():
return False
self.codes.append(int(code))
self.ignore = 2
self.code_last = True
return True | python | def set_code(self, idx):
"""
Sets a code to be filtered on for the conversion. Note that
this also sets the 'code_last' attribute and configures to
ignore the remaining characters of the code.
:param idx: The index at which the code _begins_.
:returns: True if the code is valid, False otherwise.
"""
code = self.format[idx:idx + 3]
if len(code) < 3 or not code.isdigit():
return False
self.codes.append(int(code))
self.ignore = 2
self.code_last = True
return True | [
"def",
"set_code",
"(",
"self",
",",
"idx",
")",
":",
"code",
"=",
"self",
".",
"format",
"[",
"idx",
":",
"idx",
"+",
"3",
"]",
"if",
"len",
"(",
"code",
")",
"<",
"3",
"or",
"not",
"code",
".",
"isdigit",
"(",
")",
":",
"return",
"False",
"self",
".",
"codes",
".",
"append",
"(",
"int",
"(",
"code",
")",
")",
"self",
".",
"ignore",
"=",
"2",
"self",
".",
"code_last",
"=",
"True",
"return",
"True"
] | Sets a code to be filtered on for the conversion. Note that
this also sets the 'code_last' attribute and configures to
ignore the remaining characters of the code.
:param idx: The index at which the code _begins_.
:returns: True if the code is valid, False otherwise. | [
"Sets",
"a",
"code",
"to",
"be",
"filtered",
"on",
"for",
"the",
"conversion",
".",
"Note",
"that",
"this",
"also",
"sets",
"the",
"code_last",
"attribute",
"and",
"configures",
"to",
"ignore",
"the",
"remaining",
"characters",
"of",
"the",
"code",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L153-L172 |
246,547 | klmitch/bark | bark/format.py | ParseState.end_state | def end_state(self):
"""
Wrap things up and add any final string content.
"""
# Make sure we append any trailing text
if self.str_begin != len(self.format):
if len(self.state) > 1 or self.state[-1] != 'string':
self.fmt.append_text(
"(Bad format string; ended in state %r)" % self.state[-1])
else:
self.fmt.append_text(self.format[self.str_begin:])
# Convenience return
return self.fmt | python | def end_state(self):
"""
Wrap things up and add any final string content.
"""
# Make sure we append any trailing text
if self.str_begin != len(self.format):
if len(self.state) > 1 or self.state[-1] != 'string':
self.fmt.append_text(
"(Bad format string; ended in state %r)" % self.state[-1])
else:
self.fmt.append_text(self.format[self.str_begin:])
# Convenience return
return self.fmt | [
"def",
"end_state",
"(",
"self",
")",
":",
"# Make sure we append any trailing text",
"if",
"self",
".",
"str_begin",
"!=",
"len",
"(",
"self",
".",
"format",
")",
":",
"if",
"len",
"(",
"self",
".",
"state",
")",
">",
"1",
"or",
"self",
".",
"state",
"[",
"-",
"1",
"]",
"!=",
"'string'",
":",
"self",
".",
"fmt",
".",
"append_text",
"(",
"\"(Bad format string; ended in state %r)\"",
"%",
"self",
".",
"state",
"[",
"-",
"1",
"]",
")",
"else",
":",
"self",
".",
"fmt",
".",
"append_text",
"(",
"self",
".",
"format",
"[",
"self",
".",
"str_begin",
":",
"]",
")",
"# Convenience return",
"return",
"self",
".",
"fmt"
] | Wrap things up and add any final string content. | [
"Wrap",
"things",
"up",
"and",
"add",
"any",
"final",
"string",
"content",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L174-L188 |
246,548 | klmitch/bark | bark/format.py | ParseState.conversion | def conversion(self, idx):
"""
Switches into the 'conversion' state, used to parse a %
conversion.
:param idx: The format string index at which the conversion
begins.
"""
self.state.append('conversion')
self.str_begin = idx
self.param_begin = None
self.conv_begin = None
self.modifier = conversions.Modifier()
self.codes = []
self.reject = False
self.code_last = False | python | def conversion(self, idx):
"""
Switches into the 'conversion' state, used to parse a %
conversion.
:param idx: The format string index at which the conversion
begins.
"""
self.state.append('conversion')
self.str_begin = idx
self.param_begin = None
self.conv_begin = None
self.modifier = conversions.Modifier()
self.codes = []
self.reject = False
self.code_last = False | [
"def",
"conversion",
"(",
"self",
",",
"idx",
")",
":",
"self",
".",
"state",
".",
"append",
"(",
"'conversion'",
")",
"self",
".",
"str_begin",
"=",
"idx",
"self",
".",
"param_begin",
"=",
"None",
"self",
".",
"conv_begin",
"=",
"None",
"self",
".",
"modifier",
"=",
"conversions",
".",
"Modifier",
"(",
")",
"self",
".",
"codes",
"=",
"[",
"]",
"self",
".",
"reject",
"=",
"False",
"self",
".",
"code_last",
"=",
"False"
] | Switches into the 'conversion' state, used to parse a %
conversion.
:param idx: The format string index at which the conversion
begins. | [
"Switches",
"into",
"the",
"conversion",
"state",
"used",
"to",
"parse",
"a",
"%",
"conversion",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L190-L206 |
246,549 | klmitch/bark | bark/format.py | Format._get_conversion | def _get_conversion(cls, conv_chr, modifier):
"""
Return a conversion given its character.
:param conv_chr: The letter of the conversion, e.g., "a" for
AddressConversion, etc.
:param modifier: The format modifier applied to this
conversion.
:returns: An instance of bark.conversions.Conversion.
"""
# Do we need to look up the conversion?
if conv_chr not in cls._conversion_cache:
for ep in pkg_resources.iter_entry_points('bark.conversion',
conv_chr):
try:
# Load the conversion class
cls._conversion_cache[conv_chr] = ep.load()
break
except (ImportError, pkg_resources.UnknownExtra):
# Couldn't load it; odd...
continue
else:
# Cache the negative result
cls._conversion_cache[conv_chr] = None
# Handle negative caching
if cls._conversion_cache[conv_chr] is None:
return conversions.StringConversion("(Unknown conversion '%%%s')" %
conv_chr)
# Instantiate the conversion
return cls._conversion_cache[conv_chr](conv_chr, modifier) | python | def _get_conversion(cls, conv_chr, modifier):
"""
Return a conversion given its character.
:param conv_chr: The letter of the conversion, e.g., "a" for
AddressConversion, etc.
:param modifier: The format modifier applied to this
conversion.
:returns: An instance of bark.conversions.Conversion.
"""
# Do we need to look up the conversion?
if conv_chr not in cls._conversion_cache:
for ep in pkg_resources.iter_entry_points('bark.conversion',
conv_chr):
try:
# Load the conversion class
cls._conversion_cache[conv_chr] = ep.load()
break
except (ImportError, pkg_resources.UnknownExtra):
# Couldn't load it; odd...
continue
else:
# Cache the negative result
cls._conversion_cache[conv_chr] = None
# Handle negative caching
if cls._conversion_cache[conv_chr] is None:
return conversions.StringConversion("(Unknown conversion '%%%s')" %
conv_chr)
# Instantiate the conversion
return cls._conversion_cache[conv_chr](conv_chr, modifier) | [
"def",
"_get_conversion",
"(",
"cls",
",",
"conv_chr",
",",
"modifier",
")",
":",
"# Do we need to look up the conversion?",
"if",
"conv_chr",
"not",
"in",
"cls",
".",
"_conversion_cache",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'bark.conversion'",
",",
"conv_chr",
")",
":",
"try",
":",
"# Load the conversion class",
"cls",
".",
"_conversion_cache",
"[",
"conv_chr",
"]",
"=",
"ep",
".",
"load",
"(",
")",
"break",
"except",
"(",
"ImportError",
",",
"pkg_resources",
".",
"UnknownExtra",
")",
":",
"# Couldn't load it; odd...",
"continue",
"else",
":",
"# Cache the negative result",
"cls",
".",
"_conversion_cache",
"[",
"conv_chr",
"]",
"=",
"None",
"# Handle negative caching",
"if",
"cls",
".",
"_conversion_cache",
"[",
"conv_chr",
"]",
"is",
"None",
":",
"return",
"conversions",
".",
"StringConversion",
"(",
"\"(Unknown conversion '%%%s')\"",
"%",
"conv_chr",
")",
"# Instantiate the conversion",
"return",
"cls",
".",
"_conversion_cache",
"[",
"conv_chr",
"]",
"(",
"conv_chr",
",",
"modifier",
")"
] | Return a conversion given its character.
:param conv_chr: The letter of the conversion, e.g., "a" for
AddressConversion, etc.
:param modifier: The format modifier applied to this
conversion.
:returns: An instance of bark.conversions.Conversion. | [
"Return",
"a",
"conversion",
"given",
"its",
"character",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L254-L287 |
246,550 | klmitch/bark | bark/format.py | Format.parse | def parse(cls, format):
"""
Parse a format string. Factory function for the Format class.
:param format: The format string to parse.
:returns: An instance of class Format.
"""
fmt = cls()
# Return an empty Format if format is empty
if not format:
return fmt
# Initialize the state for parsing
state = ParseState(fmt, format)
# Loop through the format string with a state-based parser
for idx, char in enumerate(format):
# Some characters get ignored
if state.check_ignore():
continue
if state == 'string':
if char == '%':
# Handle '%%'
if format[idx:idx + 2] == '%%':
# Add one % to the string context
state.add_text(idx + 1, idx + 2)
state.set_ignore(1)
else:
state.add_text(idx)
state.conversion(idx)
elif char == '\\':
state.add_text(idx)
state.escape(idx)
elif state == 'escape':
state.add_escape(idx + 1, char)
state.pop_state(idx + 1)
elif state == 'param':
if char == '}':
state.set_param(idx)
state.pop_state()
elif state == 'conv':
if char == ')':
state.set_conversion(idx)
state.pop_state() # now in 'conversion'
state.pop_state(idx + 1) # now in 'string'
else: # state == 'conversion'
if char in '<>':
# Allowed for Apache compatibility, but ignored
continue
elif char == '!':
state.set_reject()
continue
elif char == ',' and state.code_last:
# Syntactically allowed ','
continue
elif char.isdigit():
# True if the code is valid
if state.set_code(idx):
continue
elif char == '{' and state.param_begin is None:
state.param(idx + 1)
continue
elif char == '(' and state.conv_begin is None:
state.conv(idx + 1)
continue
# OK, we have a complete conversion
state.set_conversion(idx)
state.pop_state(idx + 1)
# Finish the parse and return the completed format
return state.end_state() | python | def parse(cls, format):
"""
Parse a format string. Factory function for the Format class.
:param format: The format string to parse.
:returns: An instance of class Format.
"""
fmt = cls()
# Return an empty Format if format is empty
if not format:
return fmt
# Initialize the state for parsing
state = ParseState(fmt, format)
# Loop through the format string with a state-based parser
for idx, char in enumerate(format):
# Some characters get ignored
if state.check_ignore():
continue
if state == 'string':
if char == '%':
# Handle '%%'
if format[idx:idx + 2] == '%%':
# Add one % to the string context
state.add_text(idx + 1, idx + 2)
state.set_ignore(1)
else:
state.add_text(idx)
state.conversion(idx)
elif char == '\\':
state.add_text(idx)
state.escape(idx)
elif state == 'escape':
state.add_escape(idx + 1, char)
state.pop_state(idx + 1)
elif state == 'param':
if char == '}':
state.set_param(idx)
state.pop_state()
elif state == 'conv':
if char == ')':
state.set_conversion(idx)
state.pop_state() # now in 'conversion'
state.pop_state(idx + 1) # now in 'string'
else: # state == 'conversion'
if char in '<>':
# Allowed for Apache compatibility, but ignored
continue
elif char == '!':
state.set_reject()
continue
elif char == ',' and state.code_last:
# Syntactically allowed ','
continue
elif char.isdigit():
# True if the code is valid
if state.set_code(idx):
continue
elif char == '{' and state.param_begin is None:
state.param(idx + 1)
continue
elif char == '(' and state.conv_begin is None:
state.conv(idx + 1)
continue
# OK, we have a complete conversion
state.set_conversion(idx)
state.pop_state(idx + 1)
# Finish the parse and return the completed format
return state.end_state() | [
"def",
"parse",
"(",
"cls",
",",
"format",
")",
":",
"fmt",
"=",
"cls",
"(",
")",
"# Return an empty Format if format is empty",
"if",
"not",
"format",
":",
"return",
"fmt",
"# Initialize the state for parsing",
"state",
"=",
"ParseState",
"(",
"fmt",
",",
"format",
")",
"# Loop through the format string with a state-based parser",
"for",
"idx",
",",
"char",
"in",
"enumerate",
"(",
"format",
")",
":",
"# Some characters get ignored",
"if",
"state",
".",
"check_ignore",
"(",
")",
":",
"continue",
"if",
"state",
"==",
"'string'",
":",
"if",
"char",
"==",
"'%'",
":",
"# Handle '%%'",
"if",
"format",
"[",
"idx",
":",
"idx",
"+",
"2",
"]",
"==",
"'%%'",
":",
"# Add one % to the string context",
"state",
".",
"add_text",
"(",
"idx",
"+",
"1",
",",
"idx",
"+",
"2",
")",
"state",
".",
"set_ignore",
"(",
"1",
")",
"else",
":",
"state",
".",
"add_text",
"(",
"idx",
")",
"state",
".",
"conversion",
"(",
"idx",
")",
"elif",
"char",
"==",
"'\\\\'",
":",
"state",
".",
"add_text",
"(",
"idx",
")",
"state",
".",
"escape",
"(",
"idx",
")",
"elif",
"state",
"==",
"'escape'",
":",
"state",
".",
"add_escape",
"(",
"idx",
"+",
"1",
",",
"char",
")",
"state",
".",
"pop_state",
"(",
"idx",
"+",
"1",
")",
"elif",
"state",
"==",
"'param'",
":",
"if",
"char",
"==",
"'}'",
":",
"state",
".",
"set_param",
"(",
"idx",
")",
"state",
".",
"pop_state",
"(",
")",
"elif",
"state",
"==",
"'conv'",
":",
"if",
"char",
"==",
"')'",
":",
"state",
".",
"set_conversion",
"(",
"idx",
")",
"state",
".",
"pop_state",
"(",
")",
"# now in 'conversion'",
"state",
".",
"pop_state",
"(",
"idx",
"+",
"1",
")",
"# now in 'string'",
"else",
":",
"# state == 'conversion'",
"if",
"char",
"in",
"'<>'",
":",
"# Allowed for Apache compatibility, but ignored",
"continue",
"elif",
"char",
"==",
"'!'",
":",
"state",
".",
"set_reject",
"(",
")",
"continue",
"elif",
"char",
"==",
"','",
"and",
"state",
".",
"code_last",
":",
"# Syntactically allowed ','",
"continue",
"elif",
"char",
".",
"isdigit",
"(",
")",
":",
"# True if the code is valid",
"if",
"state",
".",
"set_code",
"(",
"idx",
")",
":",
"continue",
"elif",
"char",
"==",
"'{'",
"and",
"state",
".",
"param_begin",
"is",
"None",
":",
"state",
".",
"param",
"(",
"idx",
"+",
"1",
")",
"continue",
"elif",
"char",
"==",
"'('",
"and",
"state",
".",
"conv_begin",
"is",
"None",
":",
"state",
".",
"conv",
"(",
"idx",
"+",
"1",
")",
"continue",
"# OK, we have a complete conversion",
"state",
".",
"set_conversion",
"(",
"idx",
")",
"state",
".",
"pop_state",
"(",
"idx",
"+",
"1",
")",
"# Finish the parse and return the completed format",
"return",
"state",
".",
"end_state",
"(",
")"
] | Parse a format string. Factory function for the Format class.
:param format: The format string to parse.
:returns: An instance of class Format. | [
"Parse",
"a",
"format",
"string",
".",
"Factory",
"function",
"for",
"the",
"Format",
"class",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L290-L365 |
246,551 | klmitch/bark | bark/format.py | Format.append_text | def append_text(self, text):
"""
Append static text to the Format.
:param text: The text to append.
"""
if (self.conversions and
isinstance(self.conversions[-1],
conversions.StringConversion)):
self.conversions[-1].append(text)
else:
self.conversions.append(conversions.StringConversion(text)) | python | def append_text(self, text):
"""
Append static text to the Format.
:param text: The text to append.
"""
if (self.conversions and
isinstance(self.conversions[-1],
conversions.StringConversion)):
self.conversions[-1].append(text)
else:
self.conversions.append(conversions.StringConversion(text)) | [
"def",
"append_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"(",
"self",
".",
"conversions",
"and",
"isinstance",
"(",
"self",
".",
"conversions",
"[",
"-",
"1",
"]",
",",
"conversions",
".",
"StringConversion",
")",
")",
":",
"self",
".",
"conversions",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"text",
")",
"else",
":",
"self",
".",
"conversions",
".",
"append",
"(",
"conversions",
".",
"StringConversion",
"(",
"text",
")",
")"
] | Append static text to the Format.
:param text: The text to append. | [
"Append",
"static",
"text",
"to",
"the",
"Format",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L381-L393 |
246,552 | klmitch/bark | bark/format.py | Format.prepare | def prepare(self, request):
"""
Performs any preparations necessary for the Format.
:param request: The webob Request object describing the
request.
:returns: A list of dictionary values needed by the convert()
method.
"""
data = []
for conv in self.conversions:
data.append(conv.prepare(request))
return data | python | def prepare(self, request):
"""
Performs any preparations necessary for the Format.
:param request: The webob Request object describing the
request.
:returns: A list of dictionary values needed by the convert()
method.
"""
data = []
for conv in self.conversions:
data.append(conv.prepare(request))
return data | [
"def",
"prepare",
"(",
"self",
",",
"request",
")",
":",
"data",
"=",
"[",
"]",
"for",
"conv",
"in",
"self",
".",
"conversions",
":",
"data",
".",
"append",
"(",
"conv",
".",
"prepare",
"(",
"request",
")",
")",
"return",
"data"
] | Performs any preparations necessary for the Format.
:param request: The webob Request object describing the
request.
:returns: A list of dictionary values needed by the convert()
method. | [
"Performs",
"any",
"preparations",
"necessary",
"for",
"the",
"Format",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L404-L419 |
246,553 | klmitch/bark | bark/format.py | Format.convert | def convert(self, request, response, data):
"""
Performs the desired formatting.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary list returned by the
prepare() method.
:returns: A string, the results of which are the desired
conversion.
"""
result = []
for conv, datum in zip(self.conversions, data):
# Only include conversion if it's allowed
if conv.modifier.accept(response.status_code):
result.append(conv.convert(request, response, datum))
else:
result.append('-')
return ''.join(result) | python | def convert(self, request, response, data):
"""
Performs the desired formatting.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary list returned by the
prepare() method.
:returns: A string, the results of which are the desired
conversion.
"""
result = []
for conv, datum in zip(self.conversions, data):
# Only include conversion if it's allowed
if conv.modifier.accept(response.status_code):
result.append(conv.convert(request, response, datum))
else:
result.append('-')
return ''.join(result) | [
"def",
"convert",
"(",
"self",
",",
"request",
",",
"response",
",",
"data",
")",
":",
"result",
"=",
"[",
"]",
"for",
"conv",
",",
"datum",
"in",
"zip",
"(",
"self",
".",
"conversions",
",",
"data",
")",
":",
"# Only include conversion if it's allowed",
"if",
"conv",
".",
"modifier",
".",
"accept",
"(",
"response",
".",
"status_code",
")",
":",
"result",
".",
"append",
"(",
"conv",
".",
"convert",
"(",
"request",
",",
"response",
",",
"datum",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"'-'",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | Performs the desired formatting.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary list returned by the
prepare() method.
:returns: A string, the results of which are the desired
conversion. | [
"Performs",
"the",
"desired",
"formatting",
"."
] | 6e0e002d55f01fee27e3e45bb86e30af1bfeef36 | https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L421-L444 |
246,554 | insilicolife/micti | MICTI/MARKERS.py | MICTI.FDR_BH | def FDR_BH(self, p):
"""Benjamini-Hochberg p-value correction for multiple hypothesis testing."""
p = np.asfarray(p)
by_descend = p.argsort()[::-1]
by_orig = by_descend.argsort()
steps = float(len(p)) / np.arange(len(p), 0, -1)
q = np.minimum(1, np.minimum.accumulate(steps * p[by_descend]))
return q[by_orig] | python | def FDR_BH(self, p):
"""Benjamini-Hochberg p-value correction for multiple hypothesis testing."""
p = np.asfarray(p)
by_descend = p.argsort()[::-1]
by_orig = by_descend.argsort()
steps = float(len(p)) / np.arange(len(p), 0, -1)
q = np.minimum(1, np.minimum.accumulate(steps * p[by_descend]))
return q[by_orig] | [
"def",
"FDR_BH",
"(",
"self",
",",
"p",
")",
":",
"p",
"=",
"np",
".",
"asfarray",
"(",
"p",
")",
"by_descend",
"=",
"p",
".",
"argsort",
"(",
")",
"[",
":",
":",
"-",
"1",
"]",
"by_orig",
"=",
"by_descend",
".",
"argsort",
"(",
")",
"steps",
"=",
"float",
"(",
"len",
"(",
"p",
")",
")",
"/",
"np",
".",
"arange",
"(",
"len",
"(",
"p",
")",
",",
"0",
",",
"-",
"1",
")",
"q",
"=",
"np",
".",
"minimum",
"(",
"1",
",",
"np",
".",
"minimum",
".",
"accumulate",
"(",
"steps",
"*",
"p",
"[",
"by_descend",
"]",
")",
")",
"return",
"q",
"[",
"by_orig",
"]"
] | Benjamini-Hochberg p-value correction for multiple hypothesis testing. | [
"Benjamini",
"-",
"Hochberg",
"p",
"-",
"value",
"correction",
"for",
"multiple",
"hypothesis",
"testing",
"."
] | f12f46724295b57c4859e6acf7eab580fc355eb1 | https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/MICTI/MARKERS.py#L229-L236 |
246,555 | brentpayne/kennyg | kennyg/sax_handler.py | KennyGSAXHandler.is_valid | def is_valid(self, name=None, debug=False):
"""
Check to see if the current xml path is to be processed.
"""
valid_tags = self.action_tree
invalid = False
for item in self.current_tree:
try:
if item in valid_tags or self.ALL_TAGS in valid_tags:
valid_tags = valid_tags[item if item in valid_tags else self.ALL_TAGS]
else:
valid_tags = None
invalid = True
break
except (KeyError, TypeError) as e: # object is either missing the key or is not a dictionary type
invalid = True
break
if debug:
print name, not invalid and valid_tags is not None
return not invalid and valid_tags is not None | python | def is_valid(self, name=None, debug=False):
"""
Check to see if the current xml path is to be processed.
"""
valid_tags = self.action_tree
invalid = False
for item in self.current_tree:
try:
if item in valid_tags or self.ALL_TAGS in valid_tags:
valid_tags = valid_tags[item if item in valid_tags else self.ALL_TAGS]
else:
valid_tags = None
invalid = True
break
except (KeyError, TypeError) as e: # object is either missing the key or is not a dictionary type
invalid = True
break
if debug:
print name, not invalid and valid_tags is not None
return not invalid and valid_tags is not None | [
"def",
"is_valid",
"(",
"self",
",",
"name",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"valid_tags",
"=",
"self",
".",
"action_tree",
"invalid",
"=",
"False",
"for",
"item",
"in",
"self",
".",
"current_tree",
":",
"try",
":",
"if",
"item",
"in",
"valid_tags",
"or",
"self",
".",
"ALL_TAGS",
"in",
"valid_tags",
":",
"valid_tags",
"=",
"valid_tags",
"[",
"item",
"if",
"item",
"in",
"valid_tags",
"else",
"self",
".",
"ALL_TAGS",
"]",
"else",
":",
"valid_tags",
"=",
"None",
"invalid",
"=",
"True",
"break",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
"as",
"e",
":",
"# object is either missing the key or is not a dictionary type",
"invalid",
"=",
"True",
"break",
"if",
"debug",
":",
"print",
"name",
",",
"not",
"invalid",
"and",
"valid_tags",
"is",
"not",
"None",
"return",
"not",
"invalid",
"and",
"valid_tags",
"is",
"not",
"None"
] | Check to see if the current xml path is to be processed. | [
"Check",
"to",
"see",
"if",
"the",
"current",
"xml",
"path",
"is",
"to",
"be",
"processed",
"."
] | c688dd6d270bb7dcdcce7f08c54eafb1bf3232f2 | https://github.com/brentpayne/kennyg/blob/c688dd6d270bb7dcdcce7f08c54eafb1bf3232f2/kennyg/sax_handler.py#L16-L35 |
246,556 | emencia/emencia-django-forum | forum/forms/crispies.py | category_helper | def category_helper(form_tag=True):
"""
Category's form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
helper.layout = Layout(
Row(
Column(
'title',
css_class='small-12'
),
),
Row(
Column(
'slug',
css_class='small-12 medium-10'
),
Column(
'order',
css_class='small-12 medium-2'
),
),
Row(
Column(
'description',
css_class='small-12'
),
),
Row(
Column(
'visible',
css_class='small-12'
),
),
ButtonHolderPanel(
Submit('submit', _('Submit')),
css_class='text-right',
),
)
return helper | python | def category_helper(form_tag=True):
"""
Category's form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
helper.layout = Layout(
Row(
Column(
'title',
css_class='small-12'
),
),
Row(
Column(
'slug',
css_class='small-12 medium-10'
),
Column(
'order',
css_class='small-12 medium-2'
),
),
Row(
Column(
'description',
css_class='small-12'
),
),
Row(
Column(
'visible',
css_class='small-12'
),
),
ButtonHolderPanel(
Submit('submit', _('Submit')),
css_class='text-right',
),
)
return helper | [
"def",
"category_helper",
"(",
"form_tag",
"=",
"True",
")",
":",
"helper",
"=",
"FormHelper",
"(",
")",
"helper",
".",
"form_action",
"=",
"'.'",
"helper",
".",
"attrs",
"=",
"{",
"'data_abide'",
":",
"''",
"}",
"helper",
".",
"form_tag",
"=",
"form_tag",
"helper",
".",
"layout",
"=",
"Layout",
"(",
"Row",
"(",
"Column",
"(",
"'title'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
"Row",
"(",
"Column",
"(",
"'slug'",
",",
"css_class",
"=",
"'small-12 medium-10'",
")",
",",
"Column",
"(",
"'order'",
",",
"css_class",
"=",
"'small-12 medium-2'",
")",
",",
")",
",",
"Row",
"(",
"Column",
"(",
"'description'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
"Row",
"(",
"Column",
"(",
"'visible'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
"ButtonHolderPanel",
"(",
"Submit",
"(",
"'submit'",
",",
"_",
"(",
"'Submit'",
")",
")",
",",
"css_class",
"=",
"'text-right'",
",",
")",
",",
")",
"return",
"helper"
] | Category's form layout helper | [
"Category",
"s",
"form",
"layout",
"helper"
] | cda74ed7e5822675c340ee5ec71548d981bccd3b | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L9-L53 |
246,557 | emencia/emencia-django-forum | forum/forms/crispies.py | thread_helper | def thread_helper(form_tag=True, edit_mode=False, for_moderator=False):
"""
Thread's form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'subject',
css_class='small-12'
),
),
]
# Category field only in edit form
if edit_mode:
fieldsets.append(
Row(
Column(
'category',
css_class='small-12'
),
),
)
if for_moderator:
fieldsets.append(
Row(
Column(
'sticky',
css_class='small-12 medium-4'
),
Column(
'announce',
css_class='small-12 medium-4'
),
Column(
'closed',
css_class='small-12 medium-4'
),
),
)
# First message is not in edit form
if not edit_mode:
fieldsets.append(
Row(
Column(
'text',
css_class='small-12'
),
),
)
if for_moderator:
fieldsets.append(
Row(
Column(
'visible',
css_class='small-12'
),
),
)
# Threadwatch option is not in edit form
if not edit_mode:
fieldsets.append(
Row(
Column(
'threadwatch',
css_class='small-12'
),
),
)
fieldsets = fieldsets+[
ButtonHolderPanel(
Submit('submit', _('Submit')),
css_class='text-right',
),
]
helper.layout = Layout(*fieldsets)
return helper | python | def thread_helper(form_tag=True, edit_mode=False, for_moderator=False):
"""
Thread's form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'subject',
css_class='small-12'
),
),
]
# Category field only in edit form
if edit_mode:
fieldsets.append(
Row(
Column(
'category',
css_class='small-12'
),
),
)
if for_moderator:
fieldsets.append(
Row(
Column(
'sticky',
css_class='small-12 medium-4'
),
Column(
'announce',
css_class='small-12 medium-4'
),
Column(
'closed',
css_class='small-12 medium-4'
),
),
)
# First message is not in edit form
if not edit_mode:
fieldsets.append(
Row(
Column(
'text',
css_class='small-12'
),
),
)
if for_moderator:
fieldsets.append(
Row(
Column(
'visible',
css_class='small-12'
),
),
)
# Threadwatch option is not in edit form
if not edit_mode:
fieldsets.append(
Row(
Column(
'threadwatch',
css_class='small-12'
),
),
)
fieldsets = fieldsets+[
ButtonHolderPanel(
Submit('submit', _('Submit')),
css_class='text-right',
),
]
helper.layout = Layout(*fieldsets)
return helper | [
"def",
"thread_helper",
"(",
"form_tag",
"=",
"True",
",",
"edit_mode",
"=",
"False",
",",
"for_moderator",
"=",
"False",
")",
":",
"helper",
"=",
"FormHelper",
"(",
")",
"helper",
".",
"form_action",
"=",
"'.'",
"helper",
".",
"attrs",
"=",
"{",
"'data_abide'",
":",
"''",
"}",
"helper",
".",
"form_tag",
"=",
"form_tag",
"fieldsets",
"=",
"[",
"Row",
"(",
"Column",
"(",
"'subject'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
"]",
"# Category field only in edit form",
"if",
"edit_mode",
":",
"fieldsets",
".",
"append",
"(",
"Row",
"(",
"Column",
"(",
"'category'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
")",
"if",
"for_moderator",
":",
"fieldsets",
".",
"append",
"(",
"Row",
"(",
"Column",
"(",
"'sticky'",
",",
"css_class",
"=",
"'small-12 medium-4'",
")",
",",
"Column",
"(",
"'announce'",
",",
"css_class",
"=",
"'small-12 medium-4'",
")",
",",
"Column",
"(",
"'closed'",
",",
"css_class",
"=",
"'small-12 medium-4'",
")",
",",
")",
",",
")",
"# First message is not in edit form",
"if",
"not",
"edit_mode",
":",
"fieldsets",
".",
"append",
"(",
"Row",
"(",
"Column",
"(",
"'text'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
")",
"if",
"for_moderator",
":",
"fieldsets",
".",
"append",
"(",
"Row",
"(",
"Column",
"(",
"'visible'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
")",
"# Threadwatch option is not in edit form",
"if",
"not",
"edit_mode",
":",
"fieldsets",
".",
"append",
"(",
"Row",
"(",
"Column",
"(",
"'threadwatch'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
")",
"fieldsets",
"=",
"fieldsets",
"+",
"[",
"ButtonHolderPanel",
"(",
"Submit",
"(",
"'submit'",
",",
"_",
"(",
"'Submit'",
")",
")",
",",
"css_class",
"=",
"'text-right'",
",",
")",
",",
"]",
"helper",
".",
"layout",
"=",
"Layout",
"(",
"*",
"fieldsets",
")",
"return",
"helper"
] | Thread's form layout helper | [
"Thread",
"s",
"form",
"layout",
"helper"
] | cda74ed7e5822675c340ee5ec71548d981bccd3b | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L57-L145 |
246,558 | emencia/emencia-django-forum | forum/forms/crispies.py | post_helper | def post_helper(form_tag=True, edit_mode=False):
"""
Post's form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'text',
css_class='small-12'
),
),
]
# Threadwatch option is not in edit form
if not edit_mode:
fieldsets.append(
Row(
Column(
'threadwatch',
css_class='small-12'
),
),
)
fieldsets = fieldsets+[
ButtonHolderPanel(
Submit('submit', _('Submit')),
css_class='text-right',
),
]
helper.layout = Layout(*fieldsets)
return helper | python | def post_helper(form_tag=True, edit_mode=False):
"""
Post's form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'text',
css_class='small-12'
),
),
]
# Threadwatch option is not in edit form
if not edit_mode:
fieldsets.append(
Row(
Column(
'threadwatch',
css_class='small-12'
),
),
)
fieldsets = fieldsets+[
ButtonHolderPanel(
Submit('submit', _('Submit')),
css_class='text-right',
),
]
helper.layout = Layout(*fieldsets)
return helper | [
"def",
"post_helper",
"(",
"form_tag",
"=",
"True",
",",
"edit_mode",
"=",
"False",
")",
":",
"helper",
"=",
"FormHelper",
"(",
")",
"helper",
".",
"form_action",
"=",
"'.'",
"helper",
".",
"attrs",
"=",
"{",
"'data_abide'",
":",
"''",
"}",
"helper",
".",
"form_tag",
"=",
"form_tag",
"fieldsets",
"=",
"[",
"Row",
"(",
"Column",
"(",
"'text'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
"]",
"# Threadwatch option is not in edit form",
"if",
"not",
"edit_mode",
":",
"fieldsets",
".",
"append",
"(",
"Row",
"(",
"Column",
"(",
"'threadwatch'",
",",
"css_class",
"=",
"'small-12'",
")",
",",
")",
",",
")",
"fieldsets",
"=",
"fieldsets",
"+",
"[",
"ButtonHolderPanel",
"(",
"Submit",
"(",
"'submit'",
",",
"_",
"(",
"'Submit'",
")",
")",
",",
"css_class",
"=",
"'text-right'",
",",
")",
",",
"]",
"helper",
".",
"layout",
"=",
"Layout",
"(",
"*",
"fieldsets",
")",
"return",
"helper"
] | Post's form layout helper | [
"Post",
"s",
"form",
"layout",
"helper"
] | cda74ed7e5822675c340ee5ec71548d981bccd3b | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L148-L186 |
246,559 | emencia/emencia-django-forum | forum/forms/crispies.py | post_delete_helper | def post_delete_helper(form_tag=True):
"""
Message's delete form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
helper.layout = Layout(
ButtonHolderPanel(
Row(
Column(
'confirm',
css_class='small-12 medium-8'
),
Column(
Submit('submit', _('Submit')),
css_class='small-12 medium-4 text-right'
),
),
),
)
return helper | python | def post_delete_helper(form_tag=True):
"""
Message's delete form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
helper.layout = Layout(
ButtonHolderPanel(
Row(
Column(
'confirm',
css_class='small-12 medium-8'
),
Column(
Submit('submit', _('Submit')),
css_class='small-12 medium-4 text-right'
),
),
),
)
return helper | [
"def",
"post_delete_helper",
"(",
"form_tag",
"=",
"True",
")",
":",
"helper",
"=",
"FormHelper",
"(",
")",
"helper",
".",
"form_action",
"=",
"'.'",
"helper",
".",
"attrs",
"=",
"{",
"'data_abide'",
":",
"''",
"}",
"helper",
".",
"form_tag",
"=",
"form_tag",
"helper",
".",
"layout",
"=",
"Layout",
"(",
"ButtonHolderPanel",
"(",
"Row",
"(",
"Column",
"(",
"'confirm'",
",",
"css_class",
"=",
"'small-12 medium-8'",
")",
",",
"Column",
"(",
"Submit",
"(",
"'submit'",
",",
"_",
"(",
"'Submit'",
")",
")",
",",
"css_class",
"=",
"'small-12 medium-4 text-right'",
")",
",",
")",
",",
")",
",",
")",
"return",
"helper"
] | Message's delete form layout helper | [
"Message",
"s",
"delete",
"form",
"layout",
"helper"
] | cda74ed7e5822675c340ee5ec71548d981bccd3b | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L191-L215 |
246,560 | alexhayes/django-toolkit | django_toolkit/decorators.py | permission_required_raise | def permission_required_raise(perm, login_url=None, raise_exception=True):
"""
A permission_required decorator that raises by default.
"""
return permission_required(perm, login_url=login_url, raise_exception=raise_exception) | python | def permission_required_raise(perm, login_url=None, raise_exception=True):
"""
A permission_required decorator that raises by default.
"""
return permission_required(perm, login_url=login_url, raise_exception=raise_exception) | [
"def",
"permission_required_raise",
"(",
"perm",
",",
"login_url",
"=",
"None",
",",
"raise_exception",
"=",
"True",
")",
":",
"return",
"permission_required",
"(",
"perm",
",",
"login_url",
"=",
"login_url",
",",
"raise_exception",
"=",
"raise_exception",
")"
] | A permission_required decorator that raises by default. | [
"A",
"permission_required",
"decorator",
"that",
"raises",
"by",
"default",
"."
] | b64106392fad596defc915b8235fe6e1d0013b5b | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/decorators.py#L31-L35 |
246,561 | alexhayes/django-toolkit | django_toolkit/celery/decorators.py | ensure_self | def ensure_self(func):
"""
Decorator that can be used to ensure 'self' is the first argument on a task method.
This only needs to be used with task methods that are used as a callback to
a chord or in link_error and is really just a hack to get around https://github.com/celery/celery/issues/2137
Usage:
.. code-block:: python
class Foo(models.Model):
def __init__(self):
self.bar = 1
@task
def first(self):
pass
@task
@ensure_self
def last(self, results=None):
print self.bar
Then the following is performed:
.. code-block:: python
f = Foo()
(f.first.s() | f.last.s(this=f)).apply_async()
# prints 1
The important part here is that 'this' is passed into the last.s subtask.
Hopefully issue 2137 is recognized as an issue and fixed and this hack is
no longer required.
"""
@wraps(func)
def inner(*args, **kwargs):
try:
self = kwargs.pop('this')
if len(args) >= 1 and self == args[0]:
# Make the assumption that the first argument hasn't been passed in twice...
raise KeyError()
return func(self, *args, **kwargs)
except KeyError:
# 'this' wasn't passed, all we can do is assume normal innovation
return func(*args, **kwargs)
return inner | python | def ensure_self(func):
"""
Decorator that can be used to ensure 'self' is the first argument on a task method.
This only needs to be used with task methods that are used as a callback to
a chord or in link_error and is really just a hack to get around https://github.com/celery/celery/issues/2137
Usage:
.. code-block:: python
class Foo(models.Model):
def __init__(self):
self.bar = 1
@task
def first(self):
pass
@task
@ensure_self
def last(self, results=None):
print self.bar
Then the following is performed:
.. code-block:: python
f = Foo()
(f.first.s() | f.last.s(this=f)).apply_async()
# prints 1
The important part here is that 'this' is passed into the last.s subtask.
Hopefully issue 2137 is recognized as an issue and fixed and this hack is
no longer required.
"""
@wraps(func)
def inner(*args, **kwargs):
try:
self = kwargs.pop('this')
if len(args) >= 1 and self == args[0]:
# Make the assumption that the first argument hasn't been passed in twice...
raise KeyError()
return func(self, *args, **kwargs)
except KeyError:
# 'this' wasn't passed, all we can do is assume normal innovation
return func(*args, **kwargs)
return inner | [
"def",
"ensure_self",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
"=",
"kwargs",
".",
"pop",
"(",
"'this'",
")",
"if",
"len",
"(",
"args",
")",
">=",
"1",
"and",
"self",
"==",
"args",
"[",
"0",
"]",
":",
"# Make the assumption that the first argument hasn't been passed in twice...",
"raise",
"KeyError",
"(",
")",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"KeyError",
":",
"# 'this' wasn't passed, all we can do is assume normal innovation",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner"
] | Decorator that can be used to ensure 'self' is the first argument on a task method.
This only needs to be used with task methods that are used as a callback to
a chord or in link_error and is really just a hack to get around https://github.com/celery/celery/issues/2137
Usage:
.. code-block:: python
class Foo(models.Model):
def __init__(self):
self.bar = 1
@task
def first(self):
pass
@task
@ensure_self
def last(self, results=None):
print self.bar
Then the following is performed:
.. code-block:: python
f = Foo()
(f.first.s() | f.last.s(this=f)).apply_async()
# prints 1
The important part here is that 'this' is passed into the last.s subtask.
Hopefully issue 2137 is recognized as an issue and fixed and this hack is
no longer required. | [
"Decorator",
"that",
"can",
"be",
"used",
"to",
"ensure",
"self",
"is",
"the",
"first",
"argument",
"on",
"a",
"task",
"method",
"."
] | b64106392fad596defc915b8235fe6e1d0013b5b | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/celery/decorators.py#L3-L53 |
246,562 | b3j0f/utils | b3j0f/utils/runtime.py | singleton_per_scope | def singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs):
"""Instanciate a singleton per scope."""
result = None
singletons = SINGLETONS_PER_SCOPES.setdefault(_scope, {})
if _renew or _cls not in singletons:
singletons[_cls] = _cls(*args, **kwargs)
result = singletons[_cls]
return result | python | def singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs):
"""Instanciate a singleton per scope."""
result = None
singletons = SINGLETONS_PER_SCOPES.setdefault(_scope, {})
if _renew or _cls not in singletons:
singletons[_cls] = _cls(*args, **kwargs)
result = singletons[_cls]
return result | [
"def",
"singleton_per_scope",
"(",
"_cls",
",",
"_scope",
"=",
"None",
",",
"_renew",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"None",
"singletons",
"=",
"SINGLETONS_PER_SCOPES",
".",
"setdefault",
"(",
"_scope",
",",
"{",
"}",
")",
"if",
"_renew",
"or",
"_cls",
"not",
"in",
"singletons",
":",
"singletons",
"[",
"_cls",
"]",
"=",
"_cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"result",
"=",
"singletons",
"[",
"_cls",
"]",
"return",
"result"
] | Instanciate a singleton per scope. | [
"Instanciate",
"a",
"singleton",
"per",
"scope",
"."
] | 793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff | https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/runtime.py#L70-L82 |
246,563 | b3j0f/utils | b3j0f/utils/runtime.py | _safe_processing | def _safe_processing(nsafefn, source, _globals=None, _locals=None):
"""Do a safe processing of input fn in using SAFE_BUILTINS.
:param fn: function to call with input parameters.
:param source: source object to process with fn.
:param dict _globals: global objects by name.
:param dict _locals: local objects by name.
:return: fn processing result"""
if _globals is None:
_globals = SAFE_BUILTINS
else:
_globals.update(SAFE_BUILTINS)
return nsafefn(source, _globals, _locals) | python | def _safe_processing(nsafefn, source, _globals=None, _locals=None):
"""Do a safe processing of input fn in using SAFE_BUILTINS.
:param fn: function to call with input parameters.
:param source: source object to process with fn.
:param dict _globals: global objects by name.
:param dict _locals: local objects by name.
:return: fn processing result"""
if _globals is None:
_globals = SAFE_BUILTINS
else:
_globals.update(SAFE_BUILTINS)
return nsafefn(source, _globals, _locals) | [
"def",
"_safe_processing",
"(",
"nsafefn",
",",
"source",
",",
"_globals",
"=",
"None",
",",
"_locals",
"=",
"None",
")",
":",
"if",
"_globals",
"is",
"None",
":",
"_globals",
"=",
"SAFE_BUILTINS",
"else",
":",
"_globals",
".",
"update",
"(",
"SAFE_BUILTINS",
")",
"return",
"nsafefn",
"(",
"source",
",",
"_globals",
",",
"_locals",
")"
] | Do a safe processing of input fn in using SAFE_BUILTINS.
:param fn: function to call with input parameters.
:param source: source object to process with fn.
:param dict _globals: global objects by name.
:param dict _locals: local objects by name.
:return: fn processing result | [
"Do",
"a",
"safe",
"processing",
"of",
"input",
"fn",
"in",
"using",
"SAFE_BUILTINS",
"."
] | 793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff | https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/runtime.py#L105-L120 |
246,564 | b3j0f/utils | b3j0f/utils/runtime.py | getcodeobj | def getcodeobj(consts, intcode, newcodeobj, oldcodeobj):
"""Get code object from decompiled code.
:param list consts: constants to add in the result.
:param list intcode: list of byte code to use.
:param newcodeobj: new code object with empty body.
:param oldcodeobj: old code object.
:return: new code object to produce."""
# get code string
if PY3:
codestr = bytes(intcode)
else:
codestr = reduce(lambda x, y: x + y, (chr(b) for b in intcode))
# get vargs
vargs = [
newcodeobj.co_argcount, newcodeobj.co_nlocals, newcodeobj.co_stacksize,
newcodeobj.co_flags, codestr, tuple(consts), newcodeobj.co_names,
newcodeobj.co_varnames, newcodeobj.co_filename, newcodeobj.co_name,
newcodeobj.co_firstlineno, newcodeobj.co_lnotab,
oldcodeobj.co_freevars, newcodeobj.co_cellvars
]
if PY3:
vargs.insert(1, newcodeobj.co_kwonlyargcount)
# instanciate a new newcodeobj object
result = type(newcodeobj)(*vargs)
return result | python | def getcodeobj(consts, intcode, newcodeobj, oldcodeobj):
"""Get code object from decompiled code.
:param list consts: constants to add in the result.
:param list intcode: list of byte code to use.
:param newcodeobj: new code object with empty body.
:param oldcodeobj: old code object.
:return: new code object to produce."""
# get code string
if PY3:
codestr = bytes(intcode)
else:
codestr = reduce(lambda x, y: x + y, (chr(b) for b in intcode))
# get vargs
vargs = [
newcodeobj.co_argcount, newcodeobj.co_nlocals, newcodeobj.co_stacksize,
newcodeobj.co_flags, codestr, tuple(consts), newcodeobj.co_names,
newcodeobj.co_varnames, newcodeobj.co_filename, newcodeobj.co_name,
newcodeobj.co_firstlineno, newcodeobj.co_lnotab,
oldcodeobj.co_freevars, newcodeobj.co_cellvars
]
if PY3:
vargs.insert(1, newcodeobj.co_kwonlyargcount)
# instanciate a new newcodeobj object
result = type(newcodeobj)(*vargs)
return result | [
"def",
"getcodeobj",
"(",
"consts",
",",
"intcode",
",",
"newcodeobj",
",",
"oldcodeobj",
")",
":",
"# get code string",
"if",
"PY3",
":",
"codestr",
"=",
"bytes",
"(",
"intcode",
")",
"else",
":",
"codestr",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"(",
"chr",
"(",
"b",
")",
"for",
"b",
"in",
"intcode",
")",
")",
"# get vargs",
"vargs",
"=",
"[",
"newcodeobj",
".",
"co_argcount",
",",
"newcodeobj",
".",
"co_nlocals",
",",
"newcodeobj",
".",
"co_stacksize",
",",
"newcodeobj",
".",
"co_flags",
",",
"codestr",
",",
"tuple",
"(",
"consts",
")",
",",
"newcodeobj",
".",
"co_names",
",",
"newcodeobj",
".",
"co_varnames",
",",
"newcodeobj",
".",
"co_filename",
",",
"newcodeobj",
".",
"co_name",
",",
"newcodeobj",
".",
"co_firstlineno",
",",
"newcodeobj",
".",
"co_lnotab",
",",
"oldcodeobj",
".",
"co_freevars",
",",
"newcodeobj",
".",
"co_cellvars",
"]",
"if",
"PY3",
":",
"vargs",
".",
"insert",
"(",
"1",
",",
"newcodeobj",
".",
"co_kwonlyargcount",
")",
"# instanciate a new newcodeobj object",
"result",
"=",
"type",
"(",
"newcodeobj",
")",
"(",
"*",
"vargs",
")",
"return",
"result"
] | Get code object from decompiled code.
:param list consts: constants to add in the result.
:param list intcode: list of byte code to use.
:param newcodeobj: new code object with empty body.
:param oldcodeobj: old code object.
:return: new code object to produce. | [
"Get",
"code",
"object",
"from",
"decompiled",
"code",
"."
] | 793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff | https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/runtime.py#L279-L309 |
246,565 | b3j0f/utils | b3j0f/utils/runtime.py | bind_all | def bind_all(morc, builtin_only=False, stoplist=None, verbose=None):
"""Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True.
:param morc: module or class to transform.
:param bool builtin_only: only transform builtin objects.
:param list stoplist: attribute names to not transform.
:param function verbose: logger function which takes in parameter a message
"""
if stoplist is None:
stoplist = []
def _bind_all(morc, builtin_only=False, stoplist=None, verbose=False):
"""Internal bind all decorator function.
"""
if stoplist is None:
stoplist = []
if isinstance(morc, (ModuleType, type)):
for k, val in list(vars(morc).items()):
if isinstance(val, FunctionType):
newv = _make_constants(
val, builtin_only, stoplist, verbose
)
setattr(morc, k, newv)
elif isinstance(val, type):
_bind_all(val, builtin_only, stoplist, verbose)
if isinstance(morc, dict): # allow: bind_all(globals())
for k, val in list(morc.items()):
if isinstance(val, FunctionType):
newv = _make_constants(val, builtin_only, stoplist, verbose)
morc[k] = newv
elif isinstance(val, type):
_bind_all(val, builtin_only, stoplist, verbose)
else:
_bind_all(morc, builtin_only, stoplist, verbose) | python | def bind_all(morc, builtin_only=False, stoplist=None, verbose=None):
"""Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True.
:param morc: module or class to transform.
:param bool builtin_only: only transform builtin objects.
:param list stoplist: attribute names to not transform.
:param function verbose: logger function which takes in parameter a message
"""
if stoplist is None:
stoplist = []
def _bind_all(morc, builtin_only=False, stoplist=None, verbose=False):
"""Internal bind all decorator function.
"""
if stoplist is None:
stoplist = []
if isinstance(morc, (ModuleType, type)):
for k, val in list(vars(morc).items()):
if isinstance(val, FunctionType):
newv = _make_constants(
val, builtin_only, stoplist, verbose
)
setattr(morc, k, newv)
elif isinstance(val, type):
_bind_all(val, builtin_only, stoplist, verbose)
if isinstance(morc, dict): # allow: bind_all(globals())
for k, val in list(morc.items()):
if isinstance(val, FunctionType):
newv = _make_constants(val, builtin_only, stoplist, verbose)
morc[k] = newv
elif isinstance(val, type):
_bind_all(val, builtin_only, stoplist, verbose)
else:
_bind_all(morc, builtin_only, stoplist, verbose) | [
"def",
"bind_all",
"(",
"morc",
",",
"builtin_only",
"=",
"False",
",",
"stoplist",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"stoplist",
"is",
"None",
":",
"stoplist",
"=",
"[",
"]",
"def",
"_bind_all",
"(",
"morc",
",",
"builtin_only",
"=",
"False",
",",
"stoplist",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"\"\"\"Internal bind all decorator function.\n \"\"\"",
"if",
"stoplist",
"is",
"None",
":",
"stoplist",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"morc",
",",
"(",
"ModuleType",
",",
"type",
")",
")",
":",
"for",
"k",
",",
"val",
"in",
"list",
"(",
"vars",
"(",
"morc",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"FunctionType",
")",
":",
"newv",
"=",
"_make_constants",
"(",
"val",
",",
"builtin_only",
",",
"stoplist",
",",
"verbose",
")",
"setattr",
"(",
"morc",
",",
"k",
",",
"newv",
")",
"elif",
"isinstance",
"(",
"val",
",",
"type",
")",
":",
"_bind_all",
"(",
"val",
",",
"builtin_only",
",",
"stoplist",
",",
"verbose",
")",
"if",
"isinstance",
"(",
"morc",
",",
"dict",
")",
":",
"# allow: bind_all(globals())",
"for",
"k",
",",
"val",
"in",
"list",
"(",
"morc",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"FunctionType",
")",
":",
"newv",
"=",
"_make_constants",
"(",
"val",
",",
"builtin_only",
",",
"stoplist",
",",
"verbose",
")",
"morc",
"[",
"k",
"]",
"=",
"newv",
"elif",
"isinstance",
"(",
"val",
",",
"type",
")",
":",
"_bind_all",
"(",
"val",
",",
"builtin_only",
",",
"stoplist",
",",
"verbose",
")",
"else",
":",
"_bind_all",
"(",
"morc",
",",
"builtin_only",
",",
"stoplist",
",",
"verbose",
")"
] | Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True.
:param morc: module or class to transform.
:param bool builtin_only: only transform builtin objects.
:param list stoplist: attribute names to not transform.
:param function verbose: logger function which takes in parameter a message | [
"Recursively",
"apply",
"constant",
"binding",
"to",
"functions",
"in",
"a",
"module",
"or",
"class",
"."
] | 793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff | https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/runtime.py#L315-L355 |
246,566 | b3j0f/utils | b3j0f/utils/runtime.py | make_constants | def make_constants(builtin_only=False, stoplist=None, verbose=None):
"""Return a decorator for optimizing global references.
Replaces global references with their currently defined values.
If not defined, the dynamic (runtime) global lookup is left undisturbed.
If builtin_only is True, then only builtins are optimized.
Variable names in the stoplist are also left undisturbed.
Also, folds constant attr lookups and tuples of constants.
If verbose is True, prints each substitution as is occurs.
:param bool builtin_only: only transform builtin objects.
:param list stoplist: attribute names to not transform.
:param function verbose: logger function which takes in parameter a message
"""
if stoplist is None:
stoplist = []
if isinstance(builtin_only, type(make_constants)):
raise ValueError("The bind_constants decorator must have arguments.")
return lambda func: _make_constants(func, builtin_only, stoplist, verbose) | python | def make_constants(builtin_only=False, stoplist=None, verbose=None):
"""Return a decorator for optimizing global references.
Replaces global references with their currently defined values.
If not defined, the dynamic (runtime) global lookup is left undisturbed.
If builtin_only is True, then only builtins are optimized.
Variable names in the stoplist are also left undisturbed.
Also, folds constant attr lookups and tuples of constants.
If verbose is True, prints each substitution as is occurs.
:param bool builtin_only: only transform builtin objects.
:param list stoplist: attribute names to not transform.
:param function verbose: logger function which takes in parameter a message
"""
if stoplist is None:
stoplist = []
if isinstance(builtin_only, type(make_constants)):
raise ValueError("The bind_constants decorator must have arguments.")
return lambda func: _make_constants(func, builtin_only, stoplist, verbose) | [
"def",
"make_constants",
"(",
"builtin_only",
"=",
"False",
",",
"stoplist",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"stoplist",
"is",
"None",
":",
"stoplist",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"builtin_only",
",",
"type",
"(",
"make_constants",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"The bind_constants decorator must have arguments.\"",
")",
"return",
"lambda",
"func",
":",
"_make_constants",
"(",
"func",
",",
"builtin_only",
",",
"stoplist",
",",
"verbose",
")"
] | Return a decorator for optimizing global references.
Replaces global references with their currently defined values.
If not defined, the dynamic (runtime) global lookup is left undisturbed.
If builtin_only is True, then only builtins are optimized.
Variable names in the stoplist are also left undisturbed.
Also, folds constant attr lookups and tuples of constants.
If verbose is True, prints each substitution as is occurs.
:param bool builtin_only: only transform builtin objects.
:param list stoplist: attribute names to not transform.
:param function verbose: logger function which takes in parameter a message | [
"Return",
"a",
"decorator",
"for",
"optimizing",
"global",
"references",
"."
] | 793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff | https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/runtime.py#L359-L380 |
246,567 | naphatkrit/easyci | easyci/locking.py | init | def init(vcs):
"""Initialize the locking module for a repository
"""
path = os.path.join(vcs.private_dir(), 'locks')
if not os.path.exists(path):
os.mkdir(path) | python | def init(vcs):
"""Initialize the locking module for a repository
"""
path = os.path.join(vcs.private_dir(), 'locks')
if not os.path.exists(path):
os.mkdir(path) | [
"def",
"init",
"(",
"vcs",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vcs",
".",
"private_dir",
"(",
")",
",",
"'locks'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"mkdir",
"(",
"path",
")"
] | Initialize the locking module for a repository | [
"Initialize",
"the",
"locking",
"module",
"for",
"a",
"repository"
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/locking.py#L24-L29 |
246,568 | naphatkrit/easyci | easyci/locking.py | lock | def lock(vcs, lock_object, wait=True):
"""A context manager that grabs the lock and releases it when done.
This blocks until the lock can be acquired.
Args:
vcs (easyci.vcs.base.Vcs)
lock_object (Lock)
wait (boolean) - whether to wait for the lock or error out
Raises:
Timeout
"""
if wait:
timeout = -1
else:
timeout = 0
lock_path = _get_lock_path(vcs, lock_object)
lock = filelock.FileLock(lock_path)
with lock.acquire(timeout=timeout):
yield | python | def lock(vcs, lock_object, wait=True):
"""A context manager that grabs the lock and releases it when done.
This blocks until the lock can be acquired.
Args:
vcs (easyci.vcs.base.Vcs)
lock_object (Lock)
wait (boolean) - whether to wait for the lock or error out
Raises:
Timeout
"""
if wait:
timeout = -1
else:
timeout = 0
lock_path = _get_lock_path(vcs, lock_object)
lock = filelock.FileLock(lock_path)
with lock.acquire(timeout=timeout):
yield | [
"def",
"lock",
"(",
"vcs",
",",
"lock_object",
",",
"wait",
"=",
"True",
")",
":",
"if",
"wait",
":",
"timeout",
"=",
"-",
"1",
"else",
":",
"timeout",
"=",
"0",
"lock_path",
"=",
"_get_lock_path",
"(",
"vcs",
",",
"lock_object",
")",
"lock",
"=",
"filelock",
".",
"FileLock",
"(",
"lock_path",
")",
"with",
"lock",
".",
"acquire",
"(",
"timeout",
"=",
"timeout",
")",
":",
"yield"
] | A context manager that grabs the lock and releases it when done.
This blocks until the lock can be acquired.
Args:
vcs (easyci.vcs.base.Vcs)
lock_object (Lock)
wait (boolean) - whether to wait for the lock or error out
Raises:
Timeout | [
"A",
"context",
"manager",
"that",
"grabs",
"the",
"lock",
"and",
"releases",
"it",
"when",
"done",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/locking.py#L33-L53 |
246,569 | minhhoit/yacms | yacms/utils/urls.py | home_slug | def home_slug():
"""
Returns the slug arg defined for the ``home`` urlpattern, which
is the definitive source of the ``url`` field defined for an
editable homepage object.
"""
prefix = get_script_prefix()
slug = reverse("home")
if slug.startswith(prefix):
slug = '/' + slug[len(prefix):]
try:
return resolve(slug).kwargs["slug"]
except KeyError:
return slug | python | def home_slug():
"""
Returns the slug arg defined for the ``home`` urlpattern, which
is the definitive source of the ``url`` field defined for an
editable homepage object.
"""
prefix = get_script_prefix()
slug = reverse("home")
if slug.startswith(prefix):
slug = '/' + slug[len(prefix):]
try:
return resolve(slug).kwargs["slug"]
except KeyError:
return slug | [
"def",
"home_slug",
"(",
")",
":",
"prefix",
"=",
"get_script_prefix",
"(",
")",
"slug",
"=",
"reverse",
"(",
"\"home\"",
")",
"if",
"slug",
".",
"startswith",
"(",
"prefix",
")",
":",
"slug",
"=",
"'/'",
"+",
"slug",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"try",
":",
"return",
"resolve",
"(",
"slug",
")",
".",
"kwargs",
"[",
"\"slug\"",
"]",
"except",
"KeyError",
":",
"return",
"slug"
] | Returns the slug arg defined for the ``home`` urlpattern, which
is the definitive source of the ``url`` field defined for an
editable homepage object. | [
"Returns",
"the",
"slug",
"arg",
"defined",
"for",
"the",
"home",
"urlpattern",
"which",
"is",
"the",
"definitive",
"source",
"of",
"the",
"url",
"field",
"defined",
"for",
"an",
"editable",
"homepage",
"object",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/urls.py#L32-L45 |
246,570 | minhhoit/yacms | yacms/utils/urls.py | unique_slug | def unique_slug(queryset, slug_field, slug):
"""
Ensures a slug is unique for the given queryset, appending
an integer to its end until the slug is unique.
"""
i = 0
while True:
if i > 0:
if i > 1:
slug = slug.rsplit("-", 1)[0]
slug = "%s-%s" % (slug, i)
try:
queryset.get(**{slug_field: slug})
except ObjectDoesNotExist:
break
i += 1
return slug | python | def unique_slug(queryset, slug_field, slug):
"""
Ensures a slug is unique for the given queryset, appending
an integer to its end until the slug is unique.
"""
i = 0
while True:
if i > 0:
if i > 1:
slug = slug.rsplit("-", 1)[0]
slug = "%s-%s" % (slug, i)
try:
queryset.get(**{slug_field: slug})
except ObjectDoesNotExist:
break
i += 1
return slug | [
"def",
"unique_slug",
"(",
"queryset",
",",
"slug_field",
",",
"slug",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"if",
"i",
">",
"0",
":",
"if",
"i",
">",
"1",
":",
"slug",
"=",
"slug",
".",
"rsplit",
"(",
"\"-\"",
",",
"1",
")",
"[",
"0",
"]",
"slug",
"=",
"\"%s-%s\"",
"%",
"(",
"slug",
",",
"i",
")",
"try",
":",
"queryset",
".",
"get",
"(",
"*",
"*",
"{",
"slug_field",
":",
"slug",
"}",
")",
"except",
"ObjectDoesNotExist",
":",
"break",
"i",
"+=",
"1",
"return",
"slug"
] | Ensures a slug is unique for the given queryset, appending
an integer to its end until the slug is unique. | [
"Ensures",
"a",
"slug",
"is",
"unique",
"for",
"the",
"given",
"queryset",
"appending",
"an",
"integer",
"to",
"its",
"end",
"until",
"the",
"slug",
"is",
"unique",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/urls.py#L72-L88 |
246,571 | minhhoit/yacms | yacms/utils/urls.py | next_url | def next_url(request):
"""
Returns URL to redirect to from the ``next`` param in the request.
"""
next = request.GET.get("next", request.POST.get("next", ""))
host = request.get_host()
return next if next and is_safe_url(next, host=host) else None | python | def next_url(request):
"""
Returns URL to redirect to from the ``next`` param in the request.
"""
next = request.GET.get("next", request.POST.get("next", ""))
host = request.get_host()
return next if next and is_safe_url(next, host=host) else None | [
"def",
"next_url",
"(",
"request",
")",
":",
"next",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"next\"",
",",
"request",
".",
"POST",
".",
"get",
"(",
"\"next\"",
",",
"\"\"",
")",
")",
"host",
"=",
"request",
".",
"get_host",
"(",
")",
"return",
"next",
"if",
"next",
"and",
"is_safe_url",
"(",
"next",
",",
"host",
"=",
"host",
")",
"else",
"None"
] | Returns URL to redirect to from the ``next`` param in the request. | [
"Returns",
"URL",
"to",
"redirect",
"to",
"from",
"the",
"next",
"param",
"in",
"the",
"request",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/urls.py#L91-L97 |
246,572 | minhhoit/yacms | yacms/utils/urls.py | path_to_slug | def path_to_slug(path):
"""
Removes everything from the given URL path, including
language code and ``PAGES_SLUG`` if any is set, returning
a slug that would match a ``Page`` instance's slug.
"""
from yacms.urls import PAGES_SLUG
lang_code = translation.get_language_from_path(path)
for prefix in (lang_code, settings.SITE_PREFIX, PAGES_SLUG):
if prefix:
path = path.replace(prefix, "", 1)
return clean_slashes(path) or "/" | python | def path_to_slug(path):
"""
Removes everything from the given URL path, including
language code and ``PAGES_SLUG`` if any is set, returning
a slug that would match a ``Page`` instance's slug.
"""
from yacms.urls import PAGES_SLUG
lang_code = translation.get_language_from_path(path)
for prefix in (lang_code, settings.SITE_PREFIX, PAGES_SLUG):
if prefix:
path = path.replace(prefix, "", 1)
return clean_slashes(path) or "/" | [
"def",
"path_to_slug",
"(",
"path",
")",
":",
"from",
"yacms",
".",
"urls",
"import",
"PAGES_SLUG",
"lang_code",
"=",
"translation",
".",
"get_language_from_path",
"(",
"path",
")",
"for",
"prefix",
"in",
"(",
"lang_code",
",",
"settings",
".",
"SITE_PREFIX",
",",
"PAGES_SLUG",
")",
":",
"if",
"prefix",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"prefix",
",",
"\"\"",
",",
"1",
")",
"return",
"clean_slashes",
"(",
"path",
")",
"or",
"\"/\""
] | Removes everything from the given URL path, including
language code and ``PAGES_SLUG`` if any is set, returning
a slug that would match a ``Page`` instance's slug. | [
"Removes",
"everything",
"from",
"the",
"given",
"URL",
"path",
"including",
"language",
"code",
"and",
"PAGES_SLUG",
"if",
"any",
"is",
"set",
"returning",
"a",
"slug",
"that",
"would",
"match",
"a",
"Page",
"instance",
"s",
"slug",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/urls.py#L125-L136 |
246,573 | vedarthk/exreporter | exreporter/contrib/django_middlewares.py | ExreporterGithubMiddleware.process_exception | def process_exception(self, request, exception):
"""Report exceptions from requests via Exreporter.
"""
gc = GithubCredentials(
user=settings.EXREPORTER_GITHUB_USER,
repo=settings.EXREPORTER_GITHUB_REPO,
auth_token=settings.EXREPORTER_GITHUB_AUTH_TOKEN)
gs = GithubStore(credentials=gc)
reporter = ExReporter(
store=gs, labels=settings.EXREPORTER_GITHUB_LABELS)
reporter.report() | python | def process_exception(self, request, exception):
"""Report exceptions from requests via Exreporter.
"""
gc = GithubCredentials(
user=settings.EXREPORTER_GITHUB_USER,
repo=settings.EXREPORTER_GITHUB_REPO,
auth_token=settings.EXREPORTER_GITHUB_AUTH_TOKEN)
gs = GithubStore(credentials=gc)
reporter = ExReporter(
store=gs, labels=settings.EXREPORTER_GITHUB_LABELS)
reporter.report() | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"gc",
"=",
"GithubCredentials",
"(",
"user",
"=",
"settings",
".",
"EXREPORTER_GITHUB_USER",
",",
"repo",
"=",
"settings",
".",
"EXREPORTER_GITHUB_REPO",
",",
"auth_token",
"=",
"settings",
".",
"EXREPORTER_GITHUB_AUTH_TOKEN",
")",
"gs",
"=",
"GithubStore",
"(",
"credentials",
"=",
"gc",
")",
"reporter",
"=",
"ExReporter",
"(",
"store",
"=",
"gs",
",",
"labels",
"=",
"settings",
".",
"EXREPORTER_GITHUB_LABELS",
")",
"reporter",
".",
"report",
"(",
")"
] | Report exceptions from requests via Exreporter. | [
"Report",
"exceptions",
"from",
"requests",
"via",
"Exreporter",
"."
] | 8adf445477341d43a13d3baa2551e1c0f68229bb | https://github.com/vedarthk/exreporter/blob/8adf445477341d43a13d3baa2551e1c0f68229bb/exreporter/contrib/django_middlewares.py#L29-L40 |
246,574 | florianpaquet/mease | mease/backends/redis.py | RedisBackendMixin.connect | def connect(self):
"""
Connects to publisher
"""
self.client = redis.Redis(
host=self.host, port=self.port, password=self.password) | python | def connect(self):
"""
Connects to publisher
"""
self.client = redis.Redis(
host=self.host, port=self.port, password=self.password) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"redis",
".",
"Redis",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"password",
"=",
"self",
".",
"password",
")"
] | Connects to publisher | [
"Connects",
"to",
"publisher"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/redis.py#L31-L36 |
246,575 | florianpaquet/mease | mease/backends/redis.py | RedisSubscriber.connect | def connect(self):
"""
Connects to Redis
"""
logger.info("Connecting to Redis on {host}:{port}...".format(
host=self.host, port=self.port))
super(RedisSubscriber, self).connect()
logger.info("Successfully connected to Redis")
# Subscribe to channel
self.pubsub = self.client.pubsub()
self.pubsub.subscribe(self.channel)
logger.info("Subscribed to [{channel}] Redis channel".format(
channel=self.channel))
# Start listening
t = Thread(target=self.listen)
t.setDaemon(True)
t.start() | python | def connect(self):
"""
Connects to Redis
"""
logger.info("Connecting to Redis on {host}:{port}...".format(
host=self.host, port=self.port))
super(RedisSubscriber, self).connect()
logger.info("Successfully connected to Redis")
# Subscribe to channel
self.pubsub = self.client.pubsub()
self.pubsub.subscribe(self.channel)
logger.info("Subscribed to [{channel}] Redis channel".format(
channel=self.channel))
# Start listening
t = Thread(target=self.listen)
t.setDaemon(True)
t.start() | [
"def",
"connect",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Connecting to Redis on {host}:{port}...\"",
".",
"format",
"(",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
")",
")",
"super",
"(",
"RedisSubscriber",
",",
"self",
")",
".",
"connect",
"(",
")",
"logger",
".",
"info",
"(",
"\"Successfully connected to Redis\"",
")",
"# Subscribe to channel",
"self",
".",
"pubsub",
"=",
"self",
".",
"client",
".",
"pubsub",
"(",
")",
"self",
".",
"pubsub",
".",
"subscribe",
"(",
"self",
".",
"channel",
")",
"logger",
".",
"info",
"(",
"\"Subscribed to [{channel}] Redis channel\"",
".",
"format",
"(",
"channel",
"=",
"self",
".",
"channel",
")",
")",
"# Start listening",
"t",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"listen",
")",
"t",
".",
"setDaemon",
"(",
"True",
")",
"t",
".",
"start",
"(",
")"
] | Connects to Redis | [
"Connects",
"to",
"Redis"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/redis.py#L61-L81 |
246,576 | florianpaquet/mease | mease/backends/redis.py | RedisSubscriber.listen | def listen(self):
"""
Listen for messages
"""
for message in self.pubsub.listen():
if message['type'] == 'message':
message_type, client_id, client_storage, args, kwargs = self.unpack(
message['data'])
self.dispatch_message(
message_type, client_id, client_storage, args, kwargs) | python | def listen(self):
"""
Listen for messages
"""
for message in self.pubsub.listen():
if message['type'] == 'message':
message_type, client_id, client_storage, args, kwargs = self.unpack(
message['data'])
self.dispatch_message(
message_type, client_id, client_storage, args, kwargs) | [
"def",
"listen",
"(",
"self",
")",
":",
"for",
"message",
"in",
"self",
".",
"pubsub",
".",
"listen",
"(",
")",
":",
"if",
"message",
"[",
"'type'",
"]",
"==",
"'message'",
":",
"message_type",
",",
"client_id",
",",
"client_storage",
",",
"args",
",",
"kwargs",
"=",
"self",
".",
"unpack",
"(",
"message",
"[",
"'data'",
"]",
")",
"self",
".",
"dispatch_message",
"(",
"message_type",
",",
"client_id",
",",
"client_storage",
",",
"args",
",",
"kwargs",
")"
] | Listen for messages | [
"Listen",
"for",
"messages"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/redis.py#L83-L93 |
246,577 | florianpaquet/mease | mease/backends/redis.py | RedisSubscriber.exit | def exit(self):
"""
Closes the connection
"""
self.pubsub.unsubscribe()
self.client.connection_pool.disconnect()
logger.info("Connection to Redis closed") | python | def exit(self):
"""
Closes the connection
"""
self.pubsub.unsubscribe()
self.client.connection_pool.disconnect()
logger.info("Connection to Redis closed") | [
"def",
"exit",
"(",
"self",
")",
":",
"self",
".",
"pubsub",
".",
"unsubscribe",
"(",
")",
"self",
".",
"client",
".",
"connection_pool",
".",
"disconnect",
"(",
")",
"logger",
".",
"info",
"(",
"\"Connection to Redis closed\"",
")"
] | Closes the connection | [
"Closes",
"the",
"connection"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/redis.py#L95-L102 |
246,578 | florianpaquet/mease | mease/backends/redis.py | RedisBackend.get_kwargs | def get_kwargs(self):
"""
Returns kwargs for both publisher and subscriber classes
"""
return {
'host': self.host,
'port': self.port,
'channel': self.channel,
'password': self.password
} | python | def get_kwargs(self):
"""
Returns kwargs for both publisher and subscriber classes
"""
return {
'host': self.host,
'port': self.port,
'channel': self.channel,
'password': self.password
} | [
"def",
"get_kwargs",
"(",
"self",
")",
":",
"return",
"{",
"'host'",
":",
"self",
".",
"host",
",",
"'port'",
":",
"self",
".",
"port",
",",
"'channel'",
":",
"self",
".",
"channel",
",",
"'password'",
":",
"self",
".",
"password",
"}"
] | Returns kwargs for both publisher and subscriber classes | [
"Returns",
"kwargs",
"for",
"both",
"publisher",
"and",
"subscriber",
"classes"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/redis.py#L121-L130 |
246,579 | eagleamon/pynetio | setup.py | read | def read(fname):
" read the passed file "
if exists(fname):
return open(join(dirname(__file__), fname)).read() | python | def read(fname):
" read the passed file "
if exists(fname):
return open(join(dirname(__file__), fname)).read() | [
"def",
"read",
"(",
"fname",
")",
":",
"if",
"exists",
"(",
"fname",
")",
":",
"return",
"open",
"(",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"fname",
")",
")",
".",
"read",
"(",
")"
] | read the passed file | [
"read",
"the",
"passed",
"file"
] | 3bc212cae18608de0214b964e395877d3ca4aa7b | https://github.com/eagleamon/pynetio/blob/3bc212cae18608de0214b964e395877d3ca4aa7b/setup.py#L7-L10 |
246,580 | monkeython/scriba | scriba/schemes/scriba_pop.py | read | def read(url, **args):
"""Get the object from a ftp URL."""
all_ = args.pop('all', False)
password = args.pop('password', '')
if not password:
raise ValueError('password')
try:
username, __ = url.username.split(';')
except ValueError:
username = url.username
if not username:
username = os.environ.get('USERNAME')
username = os.environ.get('LOGNAME', username)
username = os.environ.get('USER', username)
client = poplib.POP3(url.hostname, url.port or poplib.POP3_PORT,
args.pop('timeout', socket._GLOBAL_DEFAULT_TIMEOUT))
response, count, __ = client.apop(username, password)
if 'OK' not in response:
raise BadPOP3Response(response)
if count == 0:
raise ValueError('count: 0')
collection = []
for id_ in range(count if all_ is True else 1):
response, lines, __ = client.retr(id_ + 1)
if 'OK' not in response:
raise BadPOP3Response(response)
client.dele(id_ + 1)
message = email.message_from_string('\n'.join(lines))
content_type = message.get_content_type()
filename = message.get_filename('')
encoding = message['Content-Encoding']
content = message.get_payload(decode=True)
content = content_encodings.get(encoding).decode(content)
content = content_types.get(content_type).parse(content)
collection.append((filename, content))
client.quit()
return collection if len(collection) > 0 else collection[0][1] | python | def read(url, **args):
"""Get the object from a ftp URL."""
all_ = args.pop('all', False)
password = args.pop('password', '')
if not password:
raise ValueError('password')
try:
username, __ = url.username.split(';')
except ValueError:
username = url.username
if not username:
username = os.environ.get('USERNAME')
username = os.environ.get('LOGNAME', username)
username = os.environ.get('USER', username)
client = poplib.POP3(url.hostname, url.port or poplib.POP3_PORT,
args.pop('timeout', socket._GLOBAL_DEFAULT_TIMEOUT))
response, count, __ = client.apop(username, password)
if 'OK' not in response:
raise BadPOP3Response(response)
if count == 0:
raise ValueError('count: 0')
collection = []
for id_ in range(count if all_ is True else 1):
response, lines, __ = client.retr(id_ + 1)
if 'OK' not in response:
raise BadPOP3Response(response)
client.dele(id_ + 1)
message = email.message_from_string('\n'.join(lines))
content_type = message.get_content_type()
filename = message.get_filename('')
encoding = message['Content-Encoding']
content = message.get_payload(decode=True)
content = content_encodings.get(encoding).decode(content)
content = content_types.get(content_type).parse(content)
collection.append((filename, content))
client.quit()
return collection if len(collection) > 0 else collection[0][1] | [
"def",
"read",
"(",
"url",
",",
"*",
"*",
"args",
")",
":",
"all_",
"=",
"args",
".",
"pop",
"(",
"'all'",
",",
"False",
")",
"password",
"=",
"args",
".",
"pop",
"(",
"'password'",
",",
"''",
")",
"if",
"not",
"password",
":",
"raise",
"ValueError",
"(",
"'password'",
")",
"try",
":",
"username",
",",
"__",
"=",
"url",
".",
"username",
".",
"split",
"(",
"';'",
")",
"except",
"ValueError",
":",
"username",
"=",
"url",
".",
"username",
"if",
"not",
"username",
":",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'USERNAME'",
")",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'LOGNAME'",
",",
"username",
")",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'USER'",
",",
"username",
")",
"client",
"=",
"poplib",
".",
"POP3",
"(",
"url",
".",
"hostname",
",",
"url",
".",
"port",
"or",
"poplib",
".",
"POP3_PORT",
",",
"args",
".",
"pop",
"(",
"'timeout'",
",",
"socket",
".",
"_GLOBAL_DEFAULT_TIMEOUT",
")",
")",
"response",
",",
"count",
",",
"__",
"=",
"client",
".",
"apop",
"(",
"username",
",",
"password",
")",
"if",
"'OK'",
"not",
"in",
"response",
":",
"raise",
"BadPOP3Response",
"(",
"response",
")",
"if",
"count",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'count: 0'",
")",
"collection",
"=",
"[",
"]",
"for",
"id_",
"in",
"range",
"(",
"count",
"if",
"all_",
"is",
"True",
"else",
"1",
")",
":",
"response",
",",
"lines",
",",
"__",
"=",
"client",
".",
"retr",
"(",
"id_",
"+",
"1",
")",
"if",
"'OK'",
"not",
"in",
"response",
":",
"raise",
"BadPOP3Response",
"(",
"response",
")",
"client",
".",
"dele",
"(",
"id_",
"+",
"1",
")",
"message",
"=",
"email",
".",
"message_from_string",
"(",
"'\\n'",
".",
"join",
"(",
"lines",
")",
")",
"content_type",
"=",
"message",
".",
"get_content_type",
"(",
")",
"filename",
"=",
"message",
".",
"get_filename",
"(",
"''",
")",
"encoding",
"=",
"message",
"[",
"'Content-Encoding'",
"]",
"content",
"=",
"message",
".",
"get_payload",
"(",
"decode",
"=",
"True",
")",
"content",
"=",
"content_encodings",
".",
"get",
"(",
"encoding",
")",
".",
"decode",
"(",
"content",
")",
"content",
"=",
"content_types",
".",
"get",
"(",
"content_type",
")",
".",
"parse",
"(",
"content",
")",
"collection",
".",
"append",
"(",
"(",
"filename",
",",
"content",
")",
")",
"client",
".",
"quit",
"(",
")",
"return",
"collection",
"if",
"len",
"(",
"collection",
")",
">",
"0",
"else",
"collection",
"[",
"0",
"]",
"[",
"1",
"]"
] | Get the object from a ftp URL. | [
"Get",
"the",
"object",
"from",
"a",
"ftp",
"URL",
"."
] | fb8e7636ed07c3d035433fdd153599ac8b24dfc4 | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_pop.py#L19-L55 |
246,581 | opinkerfi/nago | nago/extensions/checkresults.py | get | def get():
""" Get all nagios status information from a local nagios instance
"""
livestatus = mk_livestatus()
hosts = livestatus.get_hosts()
services = livestatus.get_services()
result = {}
result['hosts'] = hosts
result['services'] = services
return result | python | def get():
""" Get all nagios status information from a local nagios instance
"""
livestatus = mk_livestatus()
hosts = livestatus.get_hosts()
services = livestatus.get_services()
result = {}
result['hosts'] = hosts
result['services'] = services
return result | [
"def",
"get",
"(",
")",
":",
"livestatus",
"=",
"mk_livestatus",
"(",
")",
"hosts",
"=",
"livestatus",
".",
"get_hosts",
"(",
")",
"services",
"=",
"livestatus",
".",
"get_services",
"(",
")",
"result",
"=",
"{",
"}",
"result",
"[",
"'hosts'",
"]",
"=",
"hosts",
"result",
"[",
"'services'",
"]",
"=",
"services",
"return",
"result"
] | Get all nagios status information from a local nagios instance | [
"Get",
"all",
"nagios",
"status",
"information",
"from",
"a",
"local",
"nagios",
"instance"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/checkresults.py#L19-L28 |
246,582 | opinkerfi/nago | nago/extensions/checkresults.py | send | def send(remote_host=None):
""" Send local nagios data to a remote nago instance """
my_data = get()
if not remote_host:
remote_host = nago.extensions.settings.get('server')
remote_node = nago.core.get_node(remote_host)
remote_node.send_command('checkresults', 'post', **my_data)
return "checkresults sent to %s" % remote_host | python | def send(remote_host=None):
""" Send local nagios data to a remote nago instance """
my_data = get()
if not remote_host:
remote_host = nago.extensions.settings.get('server')
remote_node = nago.core.get_node(remote_host)
remote_node.send_command('checkresults', 'post', **my_data)
return "checkresults sent to %s" % remote_host | [
"def",
"send",
"(",
"remote_host",
"=",
"None",
")",
":",
"my_data",
"=",
"get",
"(",
")",
"if",
"not",
"remote_host",
":",
"remote_host",
"=",
"nago",
".",
"extensions",
".",
"settings",
".",
"get",
"(",
"'server'",
")",
"remote_node",
"=",
"nago",
".",
"core",
".",
"get_node",
"(",
"remote_host",
")",
"remote_node",
".",
"send_command",
"(",
"'checkresults'",
",",
"'post'",
",",
"*",
"*",
"my_data",
")",
"return",
"\"checkresults sent to %s\"",
"%",
"remote_host"
] | Send local nagios data to a remote nago instance | [
"Send",
"local",
"nagios",
"data",
"to",
"a",
"remote",
"nago",
"instance"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/checkresults.py#L72-L79 |
246,583 | opinkerfi/nago | nago/extensions/checkresults.py | _format_checkresult | def _format_checkresult(**kwargs):
""" Returns a string in a nagios "checkresults" compatible format """
o = {}
o['check_type'] = '1'
o['check_options'] = '0'
o['scheduled_check'] = '1'
o['reschedule_check'] = '1'
o['latency'] = '0.0'
o['start_time'] = '%5f' % time.time()
o['finish_time'] = '%5f' % time.time()
o['early_timeout'] = '0'
o['exited_ok'] = '1'
o['long_plugin_output'] = ''
o['performance_data'] = ''
o.update(locals())
o.update(kwargs)
del o['kwargs']
del o['o']
template = _host_check_result
# Escape all linebreaks if we have them
for k, v in o.items():
if isinstance(v, basestring) and '\n' in v:
o[k] = v.replace('\n', '\\n')
# Livestatus returns slightly different output than status.dat
# Lets normalize everything to status.dat format
if 'name' in o and not 'host_name' in o:
o['host_name'] = o['name']
if 'state' in o and not 'return_code' in o:
o['return_code'] = o['state']
if 'description' in o and not 'service_description' in o:
o['service_description'] = o['description']
if not o['performance_data'] and 'perf_data' in o:
o['performance_data'] = o['perf_data']
# If this is a service (as opposed to host) lets add service_description field in out putput
if 'service_description' in o:
template += "service_description={service_description}\n"
if not o['performance_data'].endswith('\\n'):
o['performance_data'] += '\\n'
# Format the string and return
return template.format(**o) + '\n' | python | def _format_checkresult(**kwargs):
""" Returns a string in a nagios "checkresults" compatible format """
o = {}
o['check_type'] = '1'
o['check_options'] = '0'
o['scheduled_check'] = '1'
o['reschedule_check'] = '1'
o['latency'] = '0.0'
o['start_time'] = '%5f' % time.time()
o['finish_time'] = '%5f' % time.time()
o['early_timeout'] = '0'
o['exited_ok'] = '1'
o['long_plugin_output'] = ''
o['performance_data'] = ''
o.update(locals())
o.update(kwargs)
del o['kwargs']
del o['o']
template = _host_check_result
# Escape all linebreaks if we have them
for k, v in o.items():
if isinstance(v, basestring) and '\n' in v:
o[k] = v.replace('\n', '\\n')
# Livestatus returns slightly different output than status.dat
# Lets normalize everything to status.dat format
if 'name' in o and not 'host_name' in o:
o['host_name'] = o['name']
if 'state' in o and not 'return_code' in o:
o['return_code'] = o['state']
if 'description' in o and not 'service_description' in o:
o['service_description'] = o['description']
if not o['performance_data'] and 'perf_data' in o:
o['performance_data'] = o['perf_data']
# If this is a service (as opposed to host) lets add service_description field in out putput
if 'service_description' in o:
template += "service_description={service_description}\n"
if not o['performance_data'].endswith('\\n'):
o['performance_data'] += '\\n'
# Format the string and return
return template.format(**o) + '\n' | [
"def",
"_format_checkresult",
"(",
"*",
"*",
"kwargs",
")",
":",
"o",
"=",
"{",
"}",
"o",
"[",
"'check_type'",
"]",
"=",
"'1'",
"o",
"[",
"'check_options'",
"]",
"=",
"'0'",
"o",
"[",
"'scheduled_check'",
"]",
"=",
"'1'",
"o",
"[",
"'reschedule_check'",
"]",
"=",
"'1'",
"o",
"[",
"'latency'",
"]",
"=",
"'0.0'",
"o",
"[",
"'start_time'",
"]",
"=",
"'%5f'",
"%",
"time",
".",
"time",
"(",
")",
"o",
"[",
"'finish_time'",
"]",
"=",
"'%5f'",
"%",
"time",
".",
"time",
"(",
")",
"o",
"[",
"'early_timeout'",
"]",
"=",
"'0'",
"o",
"[",
"'exited_ok'",
"]",
"=",
"'1'",
"o",
"[",
"'long_plugin_output'",
"]",
"=",
"''",
"o",
"[",
"'performance_data'",
"]",
"=",
"''",
"o",
".",
"update",
"(",
"locals",
"(",
")",
")",
"o",
".",
"update",
"(",
"kwargs",
")",
"del",
"o",
"[",
"'kwargs'",
"]",
"del",
"o",
"[",
"'o'",
"]",
"template",
"=",
"_host_check_result",
"# Escape all linebreaks if we have them",
"for",
"k",
",",
"v",
"in",
"o",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"basestring",
")",
"and",
"'\\n'",
"in",
"v",
":",
"o",
"[",
"k",
"]",
"=",
"v",
".",
"replace",
"(",
"'\\n'",
",",
"'\\\\n'",
")",
"# Livestatus returns slightly different output than status.dat",
"# Lets normalize everything to status.dat format",
"if",
"'name'",
"in",
"o",
"and",
"not",
"'host_name'",
"in",
"o",
":",
"o",
"[",
"'host_name'",
"]",
"=",
"o",
"[",
"'name'",
"]",
"if",
"'state'",
"in",
"o",
"and",
"not",
"'return_code'",
"in",
"o",
":",
"o",
"[",
"'return_code'",
"]",
"=",
"o",
"[",
"'state'",
"]",
"if",
"'description'",
"in",
"o",
"and",
"not",
"'service_description'",
"in",
"o",
":",
"o",
"[",
"'service_description'",
"]",
"=",
"o",
"[",
"'description'",
"]",
"if",
"not",
"o",
"[",
"'performance_data'",
"]",
"and",
"'perf_data'",
"in",
"o",
":",
"o",
"[",
"'performance_data'",
"]",
"=",
"o",
"[",
"'perf_data'",
"]",
"# If this is a service (as opposed to host) lets add service_description field in out putput",
"if",
"'service_description'",
"in",
"o",
":",
"template",
"+=",
"\"service_description={service_description}\\n\"",
"if",
"not",
"o",
"[",
"'performance_data'",
"]",
".",
"endswith",
"(",
"'\\\\n'",
")",
":",
"o",
"[",
"'performance_data'",
"]",
"+=",
"'\\\\n'",
"# Format the string and return",
"return",
"template",
".",
"format",
"(",
"*",
"*",
"o",
")",
"+",
"'\\n'"
] | Returns a string in a nagios "checkresults" compatible format | [
"Returns",
"a",
"string",
"in",
"a",
"nagios",
"checkresults",
"compatible",
"format"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/checkresults.py#L89-L132 |
246,584 | tempodb/tempodb-python | tempodb/protocol/objects.py | DataPoint.from_data | def from_data(self, time, value, series_id=None, key=None, tz=None):
"""Create a DataPoint object from data, rather than a JSON object or
string. This should be used by user code to construct DataPoints from
Python-based data like Datetime objects and floats.
The series_id and key arguments are only necessary if you are doing a
multi write, in which case those arguments can be used to specify which
series the DataPoint belongs to.
If needed, the tz argument should be an Olsen database compliant string
specifying the time zone for this DataPoint. This argument is most
often used internally when reading data from TempoDB.
:param time: the point in time for this reading
:type time: ISO8601 string or Datetime
:param value: the value for this reading
:type value: int or float
:param string series_id: (optional) a series ID for this point
:param string key: (optional) a key for this point
:param string tz: (optional) a timezone for this point
:rtype: :class:`DataPoint`"""
t = check_time_param(time)
if type(value) in [float, int]:
v = value
else:
raise ValueError('Values must be int or float. Got "%s".' %
str(value))
j = {
't': t,
'v': v,
'id': series_id,
'key': key
}
return DataPoint(j, None, tz=tz) | python | def from_data(self, time, value, series_id=None, key=None, tz=None):
"""Create a DataPoint object from data, rather than a JSON object or
string. This should be used by user code to construct DataPoints from
Python-based data like Datetime objects and floats.
The series_id and key arguments are only necessary if you are doing a
multi write, in which case those arguments can be used to specify which
series the DataPoint belongs to.
If needed, the tz argument should be an Olsen database compliant string
specifying the time zone for this DataPoint. This argument is most
often used internally when reading data from TempoDB.
:param time: the point in time for this reading
:type time: ISO8601 string or Datetime
:param value: the value for this reading
:type value: int or float
:param string series_id: (optional) a series ID for this point
:param string key: (optional) a key for this point
:param string tz: (optional) a timezone for this point
:rtype: :class:`DataPoint`"""
t = check_time_param(time)
if type(value) in [float, int]:
v = value
else:
raise ValueError('Values must be int or float. Got "%s".' %
str(value))
j = {
't': t,
'v': v,
'id': series_id,
'key': key
}
return DataPoint(j, None, tz=tz) | [
"def",
"from_data",
"(",
"self",
",",
"time",
",",
"value",
",",
"series_id",
"=",
"None",
",",
"key",
"=",
"None",
",",
"tz",
"=",
"None",
")",
":",
"t",
"=",
"check_time_param",
"(",
"time",
")",
"if",
"type",
"(",
"value",
")",
"in",
"[",
"float",
",",
"int",
"]",
":",
"v",
"=",
"value",
"else",
":",
"raise",
"ValueError",
"(",
"'Values must be int or float. Got \"%s\".'",
"%",
"str",
"(",
"value",
")",
")",
"j",
"=",
"{",
"'t'",
":",
"t",
",",
"'v'",
":",
"v",
",",
"'id'",
":",
"series_id",
",",
"'key'",
":",
"key",
"}",
"return",
"DataPoint",
"(",
"j",
",",
"None",
",",
"tz",
"=",
"tz",
")"
] | Create a DataPoint object from data, rather than a JSON object or
string. This should be used by user code to construct DataPoints from
Python-based data like Datetime objects and floats.
The series_id and key arguments are only necessary if you are doing a
multi write, in which case those arguments can be used to specify which
series the DataPoint belongs to.
If needed, the tz argument should be an Olsen database compliant string
specifying the time zone for this DataPoint. This argument is most
often used internally when reading data from TempoDB.
:param time: the point in time for this reading
:type time: ISO8601 string or Datetime
:param value: the value for this reading
:type value: int or float
:param string series_id: (optional) a series ID for this point
:param string key: (optional) a key for this point
:param string tz: (optional) a timezone for this point
:rtype: :class:`DataPoint` | [
"Create",
"a",
"DataPoint",
"object",
"from",
"data",
"rather",
"than",
"a",
"JSON",
"object",
"or",
"string",
".",
"This",
"should",
"be",
"used",
"by",
"user",
"code",
"to",
"construct",
"DataPoints",
"from",
"Python",
"-",
"based",
"data",
"like",
"Datetime",
"objects",
"and",
"floats",
"."
] | 8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3 | https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/protocol/objects.py#L277-L312 |
246,585 | jmgilman/Neolib | neolib/pyamf/util/pure.py | StringIOProxy.truncate | def truncate(self, size=0):
"""
Truncates the stream to the specified length.
@param size: The length of the stream, in bytes.
@type size: C{int}
"""
if size == 0:
self._buffer = StringIO()
self._len_changed = True
return
cur_pos = self.tell()
self.seek(0)
buf = self.read(size)
self._buffer = StringIO()
self._buffer.write(buf)
self.seek(cur_pos)
self._len_changed = True | python | def truncate(self, size=0):
"""
Truncates the stream to the specified length.
@param size: The length of the stream, in bytes.
@type size: C{int}
"""
if size == 0:
self._buffer = StringIO()
self._len_changed = True
return
cur_pos = self.tell()
self.seek(0)
buf = self.read(size)
self._buffer = StringIO()
self._buffer.write(buf)
self.seek(cur_pos)
self._len_changed = True | [
"def",
"truncate",
"(",
"self",
",",
"size",
"=",
"0",
")",
":",
"if",
"size",
"==",
"0",
":",
"self",
".",
"_buffer",
"=",
"StringIO",
"(",
")",
"self",
".",
"_len_changed",
"=",
"True",
"return",
"cur_pos",
"=",
"self",
".",
"tell",
"(",
")",
"self",
".",
"seek",
"(",
"0",
")",
"buf",
"=",
"self",
".",
"read",
"(",
"size",
")",
"self",
".",
"_buffer",
"=",
"StringIO",
"(",
")",
"self",
".",
"_buffer",
".",
"write",
"(",
"buf",
")",
"self",
".",
"seek",
"(",
"cur_pos",
")",
"self",
".",
"_len_changed",
"=",
"True"
] | Truncates the stream to the specified length.
@param size: The length of the stream, in bytes.
@type size: C{int} | [
"Truncates",
"the",
"stream",
"to",
"the",
"specified",
"length",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L94-L114 |
246,586 | jmgilman/Neolib | neolib/pyamf/util/pure.py | StringIOProxy._get_len | def _get_len(self):
"""
Return total number of bytes in buffer.
"""
if hasattr(self._buffer, 'len'):
self._len = self._buffer.len
return
old_pos = self._buffer.tell()
self._buffer.seek(0, 2)
self._len = self._buffer.tell()
self._buffer.seek(old_pos) | python | def _get_len(self):
"""
Return total number of bytes in buffer.
"""
if hasattr(self._buffer, 'len'):
self._len = self._buffer.len
return
old_pos = self._buffer.tell()
self._buffer.seek(0, 2)
self._len = self._buffer.tell()
self._buffer.seek(old_pos) | [
"def",
"_get_len",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_buffer",
",",
"'len'",
")",
":",
"self",
".",
"_len",
"=",
"self",
".",
"_buffer",
".",
"len",
"return",
"old_pos",
"=",
"self",
".",
"_buffer",
".",
"tell",
"(",
")",
"self",
".",
"_buffer",
".",
"seek",
"(",
"0",
",",
"2",
")",
"self",
".",
"_len",
"=",
"self",
".",
"_buffer",
".",
"tell",
"(",
")",
"self",
".",
"_buffer",
".",
"seek",
"(",
"old_pos",
")"
] | Return total number of bytes in buffer. | [
"Return",
"total",
"number",
"of",
"bytes",
"in",
"buffer",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L125-L138 |
246,587 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn._is_big_endian | def _is_big_endian(self):
"""
Whether the current endian is big endian.
"""
if self.endian == DataTypeMixIn.ENDIAN_NATIVE:
return SYSTEM_ENDIAN == DataTypeMixIn.ENDIAN_BIG
return self.endian in (DataTypeMixIn.ENDIAN_BIG, DataTypeMixIn.ENDIAN_NETWORK) | python | def _is_big_endian(self):
"""
Whether the current endian is big endian.
"""
if self.endian == DataTypeMixIn.ENDIAN_NATIVE:
return SYSTEM_ENDIAN == DataTypeMixIn.ENDIAN_BIG
return self.endian in (DataTypeMixIn.ENDIAN_BIG, DataTypeMixIn.ENDIAN_NETWORK) | [
"def",
"_is_big_endian",
"(",
"self",
")",
":",
"if",
"self",
".",
"endian",
"==",
"DataTypeMixIn",
".",
"ENDIAN_NATIVE",
":",
"return",
"SYSTEM_ENDIAN",
"==",
"DataTypeMixIn",
".",
"ENDIAN_BIG",
"return",
"self",
".",
"endian",
"in",
"(",
"DataTypeMixIn",
".",
"ENDIAN_BIG",
",",
"DataTypeMixIn",
".",
"ENDIAN_NETWORK",
")"
] | Whether the current endian is big endian. | [
"Whether",
"the",
"current",
"endian",
"is",
"big",
"endian",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L203-L210 |
246,588 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.write_ushort | def write_ushort(self, s):
"""
Writes a 2 byte unsigned integer to the stream.
@param s: 2 byte unsigned integer
@type s: C{int}
@raise TypeError: Unexpected type for int C{s}.
@raise OverflowError: Not in range.
"""
if type(s) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(s),))
if not 0 <= s <= 65535:
raise OverflowError("Not in range, %d" % s)
self.write(struct.pack("%sH" % self.endian, s)) | python | def write_ushort(self, s):
"""
Writes a 2 byte unsigned integer to the stream.
@param s: 2 byte unsigned integer
@type s: C{int}
@raise TypeError: Unexpected type for int C{s}.
@raise OverflowError: Not in range.
"""
if type(s) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(s),))
if not 0 <= s <= 65535:
raise OverflowError("Not in range, %d" % s)
self.write(struct.pack("%sH" % self.endian, s)) | [
"def",
"write_ushort",
"(",
"self",
",",
"s",
")",
":",
"if",
"type",
"(",
"s",
")",
"not",
"in",
"python",
".",
"int_types",
":",
"raise",
"TypeError",
"(",
"'expected an int (got:%r)'",
"%",
"(",
"type",
"(",
"s",
")",
",",
")",
")",
"if",
"not",
"0",
"<=",
"s",
"<=",
"65535",
":",
"raise",
"OverflowError",
"(",
"\"Not in range, %d\"",
"%",
"s",
")",
"self",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"%sH\"",
"%",
"self",
".",
"endian",
",",
"s",
")",
")"
] | Writes a 2 byte unsigned integer to the stream.
@param s: 2 byte unsigned integer
@type s: C{int}
@raise TypeError: Unexpected type for int C{s}.
@raise OverflowError: Not in range. | [
"Writes",
"a",
"2",
"byte",
"unsigned",
"integer",
"to",
"the",
"stream",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L264-L279 |
246,589 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.write_ulong | def write_ulong(self, l):
"""
Writes a 4 byte unsigned integer to the stream.
@param l: 4 byte unsigned integer
@type l: C{int}
@raise TypeError: Unexpected type for int C{l}.
@raise OverflowError: Not in range.
"""
if type(l) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(l),))
if not 0 <= l <= 4294967295:
raise OverflowError("Not in range, %d" % l)
self.write(struct.pack("%sL" % self.endian, l)) | python | def write_ulong(self, l):
"""
Writes a 4 byte unsigned integer to the stream.
@param l: 4 byte unsigned integer
@type l: C{int}
@raise TypeError: Unexpected type for int C{l}.
@raise OverflowError: Not in range.
"""
if type(l) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(l),))
if not 0 <= l <= 4294967295:
raise OverflowError("Not in range, %d" % l)
self.write(struct.pack("%sL" % self.endian, l)) | [
"def",
"write_ulong",
"(",
"self",
",",
"l",
")",
":",
"if",
"type",
"(",
"l",
")",
"not",
"in",
"python",
".",
"int_types",
":",
"raise",
"TypeError",
"(",
"'expected an int (got:%r)'",
"%",
"(",
"type",
"(",
"l",
")",
",",
")",
")",
"if",
"not",
"0",
"<=",
"l",
"<=",
"4294967295",
":",
"raise",
"OverflowError",
"(",
"\"Not in range, %d\"",
"%",
"l",
")",
"self",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"%sL\"",
"%",
"self",
".",
"endian",
",",
"l",
")",
")"
] | Writes a 4 byte unsigned integer to the stream.
@param l: 4 byte unsigned integer
@type l: C{int}
@raise TypeError: Unexpected type for int C{l}.
@raise OverflowError: Not in range. | [
"Writes",
"a",
"4",
"byte",
"unsigned",
"integer",
"to",
"the",
"stream",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L310-L325 |
246,590 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.read_24bit_uint | def read_24bit_uint(self):
"""
Reads a 24 bit unsigned integer from the stream.
@since: 0.4
"""
order = None
if not self._is_big_endian():
order = [0, 8, 16]
else:
order = [16, 8, 0]
n = 0
for x in order:
n += (self.read_uchar() << x)
return n | python | def read_24bit_uint(self):
"""
Reads a 24 bit unsigned integer from the stream.
@since: 0.4
"""
order = None
if not self._is_big_endian():
order = [0, 8, 16]
else:
order = [16, 8, 0]
n = 0
for x in order:
n += (self.read_uchar() << x)
return n | [
"def",
"read_24bit_uint",
"(",
"self",
")",
":",
"order",
"=",
"None",
"if",
"not",
"self",
".",
"_is_big_endian",
"(",
")",
":",
"order",
"=",
"[",
"0",
",",
"8",
",",
"16",
"]",
"else",
":",
"order",
"=",
"[",
"16",
",",
"8",
",",
"0",
"]",
"n",
"=",
"0",
"for",
"x",
"in",
"order",
":",
"n",
"+=",
"(",
"self",
".",
"read_uchar",
"(",
")",
"<<",
"x",
")",
"return",
"n"
] | Reads a 24 bit unsigned integer from the stream.
@since: 0.4 | [
"Reads",
"a",
"24",
"bit",
"unsigned",
"integer",
"from",
"the",
"stream",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L350-L368 |
246,591 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.write_24bit_uint | def write_24bit_uint(self, n):
"""
Writes a 24 bit unsigned integer to the stream.
@since: 0.4
@param n: 24 bit unsigned integer
@type n: C{int}
@raise TypeError: Unexpected type for int C{n}.
@raise OverflowError: Not in range.
"""
if type(n) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(n),))
if not 0 <= n <= 0xffffff:
raise OverflowError("n is out of range")
order = None
if not self._is_big_endian():
order = [0, 8, 16]
else:
order = [16, 8, 0]
for x in order:
self.write_uchar((n >> x) & 0xff) | python | def write_24bit_uint(self, n):
"""
Writes a 24 bit unsigned integer to the stream.
@since: 0.4
@param n: 24 bit unsigned integer
@type n: C{int}
@raise TypeError: Unexpected type for int C{n}.
@raise OverflowError: Not in range.
"""
if type(n) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(n),))
if not 0 <= n <= 0xffffff:
raise OverflowError("n is out of range")
order = None
if not self._is_big_endian():
order = [0, 8, 16]
else:
order = [16, 8, 0]
for x in order:
self.write_uchar((n >> x) & 0xff) | [
"def",
"write_24bit_uint",
"(",
"self",
",",
"n",
")",
":",
"if",
"type",
"(",
"n",
")",
"not",
"in",
"python",
".",
"int_types",
":",
"raise",
"TypeError",
"(",
"'expected an int (got:%r)'",
"%",
"(",
"type",
"(",
"n",
")",
",",
")",
")",
"if",
"not",
"0",
"<=",
"n",
"<=",
"0xffffff",
":",
"raise",
"OverflowError",
"(",
"\"n is out of range\"",
")",
"order",
"=",
"None",
"if",
"not",
"self",
".",
"_is_big_endian",
"(",
")",
":",
"order",
"=",
"[",
"0",
",",
"8",
",",
"16",
"]",
"else",
":",
"order",
"=",
"[",
"16",
",",
"8",
",",
"0",
"]",
"for",
"x",
"in",
"order",
":",
"self",
".",
"write_uchar",
"(",
"(",
"n",
">>",
"x",
")",
"&",
"0xff",
")"
] | Writes a 24 bit unsigned integer to the stream.
@since: 0.4
@param n: 24 bit unsigned integer
@type n: C{int}
@raise TypeError: Unexpected type for int C{n}.
@raise OverflowError: Not in range. | [
"Writes",
"a",
"24",
"bit",
"unsigned",
"integer",
"to",
"the",
"stream",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L370-L394 |
246,592 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.write_double | def write_double(self, d):
"""
Writes an 8 byte float to the stream.
@param d: 8 byte float
@type d: C{float}
@raise TypeError: Unexpected type for float C{d}.
"""
if not type(d) is float:
raise TypeError('expected a float (got:%r)' % (type(d),))
self.write(struct.pack("%sd" % self.endian, d)) | python | def write_double(self, d):
"""
Writes an 8 byte float to the stream.
@param d: 8 byte float
@type d: C{float}
@raise TypeError: Unexpected type for float C{d}.
"""
if not type(d) is float:
raise TypeError('expected a float (got:%r)' % (type(d),))
self.write(struct.pack("%sd" % self.endian, d)) | [
"def",
"write_double",
"(",
"self",
",",
"d",
")",
":",
"if",
"not",
"type",
"(",
"d",
")",
"is",
"float",
":",
"raise",
"TypeError",
"(",
"'expected a float (got:%r)'",
"%",
"(",
"type",
"(",
"d",
")",
",",
")",
")",
"self",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"%sd\"",
"%",
"self",
".",
"endian",
",",
"d",
")",
")"
] | Writes an 8 byte float to the stream.
@param d: 8 byte float
@type d: C{float}
@raise TypeError: Unexpected type for float C{d}. | [
"Writes",
"an",
"8",
"byte",
"float",
"to",
"the",
"stream",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L445-L456 |
246,593 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.write_float | def write_float(self, f):
"""
Writes a 4 byte float to the stream.
@param f: 4 byte float
@type f: C{float}
@raise TypeError: Unexpected type for float C{f}.
"""
if type(f) is not float:
raise TypeError('expected a float (got:%r)' % (type(f),))
self.write(struct.pack("%sf" % self.endian, f)) | python | def write_float(self, f):
"""
Writes a 4 byte float to the stream.
@param f: 4 byte float
@type f: C{float}
@raise TypeError: Unexpected type for float C{f}.
"""
if type(f) is not float:
raise TypeError('expected a float (got:%r)' % (type(f),))
self.write(struct.pack("%sf" % self.endian, f)) | [
"def",
"write_float",
"(",
"self",
",",
"f",
")",
":",
"if",
"type",
"(",
"f",
")",
"is",
"not",
"float",
":",
"raise",
"TypeError",
"(",
"'expected a float (got:%r)'",
"%",
"(",
"type",
"(",
"f",
")",
",",
")",
")",
"self",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"%sf\"",
"%",
"self",
".",
"endian",
",",
"f",
")",
")"
] | Writes a 4 byte float to the stream.
@param f: 4 byte float
@type f: C{float}
@raise TypeError: Unexpected type for float C{f}. | [
"Writes",
"a",
"4",
"byte",
"float",
"to",
"the",
"stream",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L464-L475 |
246,594 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.read_utf8_string | def read_utf8_string(self, length):
"""
Reads a UTF-8 string from the stream.
@rtype: C{unicode}
"""
s = struct.unpack("%s%ds" % (self.endian, length), self.read(length))[0]
return s.decode('utf-8') | python | def read_utf8_string(self, length):
"""
Reads a UTF-8 string from the stream.
@rtype: C{unicode}
"""
s = struct.unpack("%s%ds" % (self.endian, length), self.read(length))[0]
return s.decode('utf-8') | [
"def",
"read_utf8_string",
"(",
"self",
",",
"length",
")",
":",
"s",
"=",
"struct",
".",
"unpack",
"(",
"\"%s%ds\"",
"%",
"(",
"self",
".",
"endian",
",",
"length",
")",
",",
"self",
".",
"read",
"(",
"length",
")",
")",
"[",
"0",
"]",
"return",
"s",
".",
"decode",
"(",
"'utf-8'",
")"
] | Reads a UTF-8 string from the stream.
@rtype: C{unicode} | [
"Reads",
"a",
"UTF",
"-",
"8",
"string",
"from",
"the",
"stream",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L477-L485 |
246,595 | jmgilman/Neolib | neolib/pyamf/util/pure.py | DataTypeMixIn.write_utf8_string | def write_utf8_string(self, u):
"""
Writes a unicode object to the stream in UTF-8.
@param u: unicode object
@raise TypeError: Unexpected type for str C{u}.
"""
if not isinstance(u, python.str_types):
raise TypeError('Expected %r, got %r' % (python.str_types, u))
bytes = u
if isinstance(bytes, unicode):
bytes = u.encode("utf8")
self.write(struct.pack("%s%ds" % (self.endian, len(bytes)), bytes)) | python | def write_utf8_string(self, u):
"""
Writes a unicode object to the stream in UTF-8.
@param u: unicode object
@raise TypeError: Unexpected type for str C{u}.
"""
if not isinstance(u, python.str_types):
raise TypeError('Expected %r, got %r' % (python.str_types, u))
bytes = u
if isinstance(bytes, unicode):
bytes = u.encode("utf8")
self.write(struct.pack("%s%ds" % (self.endian, len(bytes)), bytes)) | [
"def",
"write_utf8_string",
"(",
"self",
",",
"u",
")",
":",
"if",
"not",
"isinstance",
"(",
"u",
",",
"python",
".",
"str_types",
")",
":",
"raise",
"TypeError",
"(",
"'Expected %r, got %r'",
"%",
"(",
"python",
".",
"str_types",
",",
"u",
")",
")",
"bytes",
"=",
"u",
"if",
"isinstance",
"(",
"bytes",
",",
"unicode",
")",
":",
"bytes",
"=",
"u",
".",
"encode",
"(",
"\"utf8\"",
")",
"self",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"%s%ds\"",
"%",
"(",
"self",
".",
"endian",
",",
"len",
"(",
"bytes",
")",
")",
",",
"bytes",
")",
")"
] | Writes a unicode object to the stream in UTF-8.
@param u: unicode object
@raise TypeError: Unexpected type for str C{u}. | [
"Writes",
"a",
"unicode",
"object",
"to",
"the",
"stream",
"in",
"UTF",
"-",
"8",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L487-L502 |
246,596 | jmgilman/Neolib | neolib/pyamf/util/pure.py | BufferedByteStream.read | def read(self, length=-1):
"""
Reads up to the specified number of bytes from the stream into
the specified byte array of specified length.
@raise IOError: Attempted to read past the end of the buffer.
"""
if length == -1 and self.at_eof():
raise IOError(
'Attempted to read from the buffer but already at the end')
elif length > 0 and self.tell() + length > len(self):
raise IOError('Attempted to read %d bytes from the buffer but '
'only %d remain' % (length, len(self) - self.tell()))
return StringIOProxy.read(self, length) | python | def read(self, length=-1):
"""
Reads up to the specified number of bytes from the stream into
the specified byte array of specified length.
@raise IOError: Attempted to read past the end of the buffer.
"""
if length == -1 and self.at_eof():
raise IOError(
'Attempted to read from the buffer but already at the end')
elif length > 0 and self.tell() + length > len(self):
raise IOError('Attempted to read %d bytes from the buffer but '
'only %d remain' % (length, len(self) - self.tell()))
return StringIOProxy.read(self, length) | [
"def",
"read",
"(",
"self",
",",
"length",
"=",
"-",
"1",
")",
":",
"if",
"length",
"==",
"-",
"1",
"and",
"self",
".",
"at_eof",
"(",
")",
":",
"raise",
"IOError",
"(",
"'Attempted to read from the buffer but already at the end'",
")",
"elif",
"length",
">",
"0",
"and",
"self",
".",
"tell",
"(",
")",
"+",
"length",
">",
"len",
"(",
"self",
")",
":",
"raise",
"IOError",
"(",
"'Attempted to read %d bytes from the buffer but '",
"'only %d remain'",
"%",
"(",
"length",
",",
"len",
"(",
"self",
")",
"-",
"self",
".",
"tell",
"(",
")",
")",
")",
"return",
"StringIOProxy",
".",
"read",
"(",
"self",
",",
"length",
")"
] | Reads up to the specified number of bytes from the stream into
the specified byte array of specified length.
@raise IOError: Attempted to read past the end of the buffer. | [
"Reads",
"up",
"to",
"the",
"specified",
"number",
"of",
"bytes",
"from",
"the",
"stream",
"into",
"the",
"specified",
"byte",
"array",
"of",
"specified",
"length",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L522-L536 |
246,597 | jmgilman/Neolib | neolib/pyamf/util/pure.py | BufferedByteStream.append | def append(self, data):
"""
Append data to the end of the stream. The pointer will not move if
this operation is successful.
@param data: The data to append to the stream.
@type data: C{str} or C{unicode}
@raise TypeError: data is not C{str} or C{unicode}
"""
t = self.tell()
# seek to the end of the stream
self.seek(0, 2)
if hasattr(data, 'getvalue'):
self.write_utf8_string(data.getvalue())
else:
self.write_utf8_string(data)
self.seek(t) | python | def append(self, data):
"""
Append data to the end of the stream. The pointer will not move if
this operation is successful.
@param data: The data to append to the stream.
@type data: C{str} or C{unicode}
@raise TypeError: data is not C{str} or C{unicode}
"""
t = self.tell()
# seek to the end of the stream
self.seek(0, 2)
if hasattr(data, 'getvalue'):
self.write_utf8_string(data.getvalue())
else:
self.write_utf8_string(data)
self.seek(t) | [
"def",
"append",
"(",
"self",
",",
"data",
")",
":",
"t",
"=",
"self",
".",
"tell",
"(",
")",
"# seek to the end of the stream",
"self",
".",
"seek",
"(",
"0",
",",
"2",
")",
"if",
"hasattr",
"(",
"data",
",",
"'getvalue'",
")",
":",
"self",
".",
"write_utf8_string",
"(",
"data",
".",
"getvalue",
"(",
")",
")",
"else",
":",
"self",
".",
"write_utf8_string",
"(",
"data",
")",
"self",
".",
"seek",
"(",
"t",
")"
] | Append data to the end of the stream. The pointer will not move if
this operation is successful.
@param data: The data to append to the stream.
@type data: C{str} or C{unicode}
@raise TypeError: data is not C{str} or C{unicode} | [
"Append",
"data",
"to",
"the",
"end",
"of",
"the",
"stream",
".",
"The",
"pointer",
"will",
"not",
"move",
"if",
"this",
"operation",
"is",
"successful",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L582-L601 |
246,598 | gersolar/goescalibration | goescalibration/channels/channel_01.py | calibration | def calibration(date, satellite):
"""
Return the calibration dictionary.
Keyword arguments:
satellite -- the name of the satellite.
date -- the datetime of an image.
"""
counts_shift = CountsShift()
space_measurement = SpaceMeasurement()
prelaunch = PreLaunch()
postlaunch = PostLaunch()
return {
'counts_shift': counts_shift.coefficient(satellite),
'space_measurement': space_measurement.coefficient(satellite),
'prelaunch': prelaunch.coefficient(satellite),
'postlaunch': postlaunch.coefficient(date, satellite)
} | python | def calibration(date, satellite):
"""
Return the calibration dictionary.
Keyword arguments:
satellite -- the name of the satellite.
date -- the datetime of an image.
"""
counts_shift = CountsShift()
space_measurement = SpaceMeasurement()
prelaunch = PreLaunch()
postlaunch = PostLaunch()
return {
'counts_shift': counts_shift.coefficient(satellite),
'space_measurement': space_measurement.coefficient(satellite),
'prelaunch': prelaunch.coefficient(satellite),
'postlaunch': postlaunch.coefficient(date, satellite)
} | [
"def",
"calibration",
"(",
"date",
",",
"satellite",
")",
":",
"counts_shift",
"=",
"CountsShift",
"(",
")",
"space_measurement",
"=",
"SpaceMeasurement",
"(",
")",
"prelaunch",
"=",
"PreLaunch",
"(",
")",
"postlaunch",
"=",
"PostLaunch",
"(",
")",
"return",
"{",
"'counts_shift'",
":",
"counts_shift",
".",
"coefficient",
"(",
"satellite",
")",
",",
"'space_measurement'",
":",
"space_measurement",
".",
"coefficient",
"(",
"satellite",
")",
",",
"'prelaunch'",
":",
"prelaunch",
".",
"coefficient",
"(",
"satellite",
")",
",",
"'postlaunch'",
":",
"postlaunch",
".",
"coefficient",
"(",
"date",
",",
"satellite",
")",
"}"
] | Return the calibration dictionary.
Keyword arguments:
satellite -- the name of the satellite.
date -- the datetime of an image. | [
"Return",
"the",
"calibration",
"dictionary",
"."
] | aab7f3e3cede9694e90048ceeaea74566578bc75 | https://github.com/gersolar/goescalibration/blob/aab7f3e3cede9694e90048ceeaea74566578bc75/goescalibration/channels/channel_01.py#L107-L124 |
246,599 | sci-bots/mpm | mpm/bin/install_dependencies.py | install_dependencies | def install_dependencies(plugins_directory, ostream=sys.stdout):
'''
Run ``on_plugin_install`` script for each plugin directory found in
specified plugins directory.
Parameters
----------
plugins_directory : str
File system path to directory containing zero or more plugin
subdirectories.
ostream : file-like
Output stream for status messages (default: ``sys.stdout``).
'''
plugin_directories = plugins_directory.realpath().dirs()
print >> ostream, 50 * '*'
print >> ostream, 'Processing plugins:'
print >> ostream, '\n'.join([' - {}'.format(p)
for p in plugin_directories])
print >> ostream, '\n' + 50 * '-' + '\n'
for plugin_dir_i in plugin_directories:
try:
on_plugin_install(plugin_dir_i, ostream=ostream)
except RuntimeError, exception:
print exception
print >> ostream, '\n' + 50 * '-' + '\n' | python | def install_dependencies(plugins_directory, ostream=sys.stdout):
'''
Run ``on_plugin_install`` script for each plugin directory found in
specified plugins directory.
Parameters
----------
plugins_directory : str
File system path to directory containing zero or more plugin
subdirectories.
ostream : file-like
Output stream for status messages (default: ``sys.stdout``).
'''
plugin_directories = plugins_directory.realpath().dirs()
print >> ostream, 50 * '*'
print >> ostream, 'Processing plugins:'
print >> ostream, '\n'.join([' - {}'.format(p)
for p in plugin_directories])
print >> ostream, '\n' + 50 * '-' + '\n'
for plugin_dir_i in plugin_directories:
try:
on_plugin_install(plugin_dir_i, ostream=ostream)
except RuntimeError, exception:
print exception
print >> ostream, '\n' + 50 * '-' + '\n' | [
"def",
"install_dependencies",
"(",
"plugins_directory",
",",
"ostream",
"=",
"sys",
".",
"stdout",
")",
":",
"plugin_directories",
"=",
"plugins_directory",
".",
"realpath",
"(",
")",
".",
"dirs",
"(",
")",
"print",
">>",
"ostream",
",",
"50",
"*",
"'*'",
"print",
">>",
"ostream",
",",
"'Processing plugins:'",
"print",
">>",
"ostream",
",",
"'\\n'",
".",
"join",
"(",
"[",
"' - {}'",
".",
"format",
"(",
"p",
")",
"for",
"p",
"in",
"plugin_directories",
"]",
")",
"print",
">>",
"ostream",
",",
"'\\n'",
"+",
"50",
"*",
"'-'",
"+",
"'\\n'",
"for",
"plugin_dir_i",
"in",
"plugin_directories",
":",
"try",
":",
"on_plugin_install",
"(",
"plugin_dir_i",
",",
"ostream",
"=",
"ostream",
")",
"except",
"RuntimeError",
",",
"exception",
":",
"print",
"exception",
"print",
">>",
"ostream",
",",
"'\\n'",
"+",
"50",
"*",
"'-'",
"+",
"'\\n'"
] | Run ``on_plugin_install`` script for each plugin directory found in
specified plugins directory.
Parameters
----------
plugins_directory : str
File system path to directory containing zero or more plugin
subdirectories.
ostream : file-like
Output stream for status messages (default: ``sys.stdout``). | [
"Run",
"on_plugin_install",
"script",
"for",
"each",
"plugin",
"directory",
"found",
"in",
"specified",
"plugins",
"directory",
"."
] | a69651cda4b37ee6b17df4fe0809249e7f4dc536 | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/bin/install_dependencies.py#L37-L63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.