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
|
---|---|---|---|---|---|---|---|---|---|---|---|
247,700 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.show_bgp_peer | def show_bgp_peer(self, peer_id, **_params):
"""Fetches information of a certain BGP peer."""
return self.get(self.bgp_peer_path % peer_id,
params=_params) | python | def show_bgp_peer(self, peer_id, **_params):
"""Fetches information of a certain BGP peer."""
return self.get(self.bgp_peer_path % peer_id,
params=_params) | [
"def",
"show_bgp_peer",
"(",
"self",
",",
"peer_id",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"bgp_peer_path",
"%",
"peer_id",
",",
"params",
"=",
"_params",
")"
] | Fetches information of a certain BGP peer. | [
"Fetches",
"information",
"of",
"a",
"certain",
"BGP",
"peer",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1759-L1762 |
247,701 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.update_bgp_peer | def update_bgp_peer(self, bgp_peer_id, body=None):
"""Update a BGP peer."""
return self.put(self.bgp_peer_path % bgp_peer_id, body=body) | python | def update_bgp_peer(self, bgp_peer_id, body=None):
"""Update a BGP peer."""
return self.put(self.bgp_peer_path % bgp_peer_id, body=body) | [
"def",
"update_bgp_peer",
"(",
"self",
",",
"bgp_peer_id",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"bgp_peer_path",
"%",
"bgp_peer_id",
",",
"body",
"=",
"body",
")"
] | Update a BGP peer. | [
"Update",
"a",
"BGP",
"peer",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1768-L1770 |
247,702 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.list_network_ip_availabilities | def list_network_ip_availabilities(self, retrieve_all=True, **_params):
"""Fetches IP availibility information for all networks"""
return self.list('network_ip_availabilities',
self.network_ip_availabilities_path,
retrieve_all, **_params) | python | def list_network_ip_availabilities(self, retrieve_all=True, **_params):
"""Fetches IP availibility information for all networks"""
return self.list('network_ip_availabilities',
self.network_ip_availabilities_path,
retrieve_all, **_params) | [
"def",
"list_network_ip_availabilities",
"(",
"self",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'network_ip_availabilities'",
",",
"self",
".",
"network_ip_availabilities_path",
",",
"retrieve_all",
",",
"*",
"*",
"_params",
")"
] | Fetches IP availibility information for all networks | [
"Fetches",
"IP",
"availibility",
"information",
"for",
"all",
"networks"
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1776-L1780 |
247,703 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.show_network_ip_availability | def show_network_ip_availability(self, network, **_params):
"""Fetches IP availability information for a specified network"""
return self.get(self.network_ip_availability_path % (network),
params=_params) | python | def show_network_ip_availability(self, network, **_params):
"""Fetches IP availability information for a specified network"""
return self.get(self.network_ip_availability_path % (network),
params=_params) | [
"def",
"show_network_ip_availability",
"(",
"self",
",",
"network",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"network_ip_availability_path",
"%",
"(",
"network",
")",
",",
"params",
"=",
"_params",
")"
] | Fetches IP availability information for a specified network | [
"Fetches",
"IP",
"availability",
"information",
"for",
"a",
"specified",
"network"
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1782-L1785 |
247,704 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.add_tag | def add_tag(self, resource_type, resource_id, tag, **_params):
"""Add a tag on the resource."""
return self.put(self.tag_path % (resource_type, resource_id, tag)) | python | def add_tag(self, resource_type, resource_id, tag, **_params):
"""Add a tag on the resource."""
return self.put(self.tag_path % (resource_type, resource_id, tag)) | [
"def",
"add_tag",
"(",
"self",
",",
"resource_type",
",",
"resource_id",
",",
"tag",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"tag_path",
"%",
"(",
"resource_type",
",",
"resource_id",
",",
"tag",
")",
")"
] | Add a tag on the resource. | [
"Add",
"a",
"tag",
"on",
"the",
"resource",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1787-L1789 |
247,705 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.replace_tag | def replace_tag(self, resource_type, resource_id, body, **_params):
"""Replace tags on the resource."""
return self.put(self.tags_path % (resource_type, resource_id), body) | python | def replace_tag(self, resource_type, resource_id, body, **_params):
"""Replace tags on the resource."""
return self.put(self.tags_path % (resource_type, resource_id), body) | [
"def",
"replace_tag",
"(",
"self",
",",
"resource_type",
",",
"resource_id",
",",
"body",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"tags_path",
"%",
"(",
"resource_type",
",",
"resource_id",
")",
",",
"body",
")"
] | Replace tags on the resource. | [
"Replace",
"tags",
"on",
"the",
"resource",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1791-L1793 |
247,706 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.remove_tag | def remove_tag(self, resource_type, resource_id, tag, **_params):
"""Remove a tag on the resource."""
return self.delete(self.tag_path % (resource_type, resource_id, tag)) | python | def remove_tag(self, resource_type, resource_id, tag, **_params):
"""Remove a tag on the resource."""
return self.delete(self.tag_path % (resource_type, resource_id, tag)) | [
"def",
"remove_tag",
"(",
"self",
",",
"resource_type",
",",
"resource_id",
",",
"tag",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"delete",
"(",
"self",
".",
"tag_path",
"%",
"(",
"resource_type",
",",
"resource_id",
",",
"tag",
")",
")"
] | Remove a tag on the resource. | [
"Remove",
"a",
"tag",
"on",
"the",
"resource",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1795-L1797 |
247,707 | rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | Client.remove_tag_all | def remove_tag_all(self, resource_type, resource_id, **_params):
"""Remove all tags on the resource."""
return self.delete(self.tags_path % (resource_type, resource_id)) | python | def remove_tag_all(self, resource_type, resource_id, **_params):
"""Remove all tags on the resource."""
return self.delete(self.tags_path % (resource_type, resource_id)) | [
"def",
"remove_tag_all",
"(",
"self",
",",
"resource_type",
",",
"resource_id",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"delete",
"(",
"self",
".",
"tags_path",
"%",
"(",
"resource_type",
",",
"resource_id",
")",
")"
] | Remove all tags on the resource. | [
"Remove",
"all",
"tags",
"on",
"the",
"resource",
"."
] | 5a5009a8fe078e3aa1d582176669f1b28ab26bef | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1799-L1801 |
247,708 | alexhayes/django-toolkit | django_toolkit/url/shorten.py | shorten_url | def shorten_url(url, length=32, strip_www=True, strip_path=True, ellipsis=False):
"""
Shorten a URL by chopping out the middle.
For example if supplied with http://subdomain.example.com.au and length 16
the following would be returned.
sub...le.com.au
"""
if '://' not in url:
# Ensure we have a protocol
url = 'http://%s' % url
parsed_url = urlparse(url)
ext = tldextract.extract(parsed_url.netloc)
if ext.subdomain and (not strip_www or (strip_www and ext.subdomain != 'www')):
shortened = u'%s.%s' % (ext.subdomain, ext.domain)
else:
shortened = u'%s' % ext.domain
if ext.tld:
shortened = u'%s.%s' % (shortened, ext.tld)
if not strip_path:
if parsed_url.path:
shortened += parsed_url.path
if len(shortened) <= length:
return shortened
else:
domain = shortened
i = length + 1 - 3
left = right = int(i/2)
if not i % 2:
right -= 1
if ellipsis:
shortened = u"%s\u2026%s" % (domain[:left], domain[-right:])
else:
shortened = '%s...%s' % (domain[:left], domain[-right:])
return shortened | python | def shorten_url(url, length=32, strip_www=True, strip_path=True, ellipsis=False):
"""
Shorten a URL by chopping out the middle.
For example if supplied with http://subdomain.example.com.au and length 16
the following would be returned.
sub...le.com.au
"""
if '://' not in url:
# Ensure we have a protocol
url = 'http://%s' % url
parsed_url = urlparse(url)
ext = tldextract.extract(parsed_url.netloc)
if ext.subdomain and (not strip_www or (strip_www and ext.subdomain != 'www')):
shortened = u'%s.%s' % (ext.subdomain, ext.domain)
else:
shortened = u'%s' % ext.domain
if ext.tld:
shortened = u'%s.%s' % (shortened, ext.tld)
if not strip_path:
if parsed_url.path:
shortened += parsed_url.path
if len(shortened) <= length:
return shortened
else:
domain = shortened
i = length + 1 - 3
left = right = int(i/2)
if not i % 2:
right -= 1
if ellipsis:
shortened = u"%s\u2026%s" % (domain[:left], domain[-right:])
else:
shortened = '%s...%s' % (domain[:left], domain[-right:])
return shortened | [
"def",
"shorten_url",
"(",
"url",
",",
"length",
"=",
"32",
",",
"strip_www",
"=",
"True",
",",
"strip_path",
"=",
"True",
",",
"ellipsis",
"=",
"False",
")",
":",
"if",
"'://'",
"not",
"in",
"url",
":",
"# Ensure we have a protocol",
"url",
"=",
"'http://%s'",
"%",
"url",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"ext",
"=",
"tldextract",
".",
"extract",
"(",
"parsed_url",
".",
"netloc",
")",
"if",
"ext",
".",
"subdomain",
"and",
"(",
"not",
"strip_www",
"or",
"(",
"strip_www",
"and",
"ext",
".",
"subdomain",
"!=",
"'www'",
")",
")",
":",
"shortened",
"=",
"u'%s.%s'",
"%",
"(",
"ext",
".",
"subdomain",
",",
"ext",
".",
"domain",
")",
"else",
":",
"shortened",
"=",
"u'%s'",
"%",
"ext",
".",
"domain",
"if",
"ext",
".",
"tld",
":",
"shortened",
"=",
"u'%s.%s'",
"%",
"(",
"shortened",
",",
"ext",
".",
"tld",
")",
"if",
"not",
"strip_path",
":",
"if",
"parsed_url",
".",
"path",
":",
"shortened",
"+=",
"parsed_url",
".",
"path",
"if",
"len",
"(",
"shortened",
")",
"<=",
"length",
":",
"return",
"shortened",
"else",
":",
"domain",
"=",
"shortened",
"i",
"=",
"length",
"+",
"1",
"-",
"3",
"left",
"=",
"right",
"=",
"int",
"(",
"i",
"/",
"2",
")",
"if",
"not",
"i",
"%",
"2",
":",
"right",
"-=",
"1",
"if",
"ellipsis",
":",
"shortened",
"=",
"u\"%s\\u2026%s\"",
"%",
"(",
"domain",
"[",
":",
"left",
"]",
",",
"domain",
"[",
"-",
"right",
":",
"]",
")",
"else",
":",
"shortened",
"=",
"'%s...%s'",
"%",
"(",
"domain",
"[",
":",
"left",
"]",
",",
"domain",
"[",
"-",
"right",
":",
"]",
")",
"return",
"shortened"
] | Shorten a URL by chopping out the middle.
For example if supplied with http://subdomain.example.com.au and length 16
the following would be returned.
sub...le.com.au | [
"Shorten",
"a",
"URL",
"by",
"chopping",
"out",
"the",
"middle",
"."
] | b64106392fad596defc915b8235fe6e1d0013b5b | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/url/shorten.py#L12-L52 |
247,709 | alexhayes/django-toolkit | django_toolkit/url/shorten.py | netloc_no_www | def netloc_no_www(url):
"""
For a given URL return the netloc with any www. striped.
"""
ext = tldextract.extract(url)
if ext.subdomain and ext.subdomain != 'www':
return '%s.%s.%s' % (ext.subdomain, ext.domain, ext.tld)
else:
return '%s.%s' % (ext.domain, ext.tld) | python | def netloc_no_www(url):
"""
For a given URL return the netloc with any www. striped.
"""
ext = tldextract.extract(url)
if ext.subdomain and ext.subdomain != 'www':
return '%s.%s.%s' % (ext.subdomain, ext.domain, ext.tld)
else:
return '%s.%s' % (ext.domain, ext.tld) | [
"def",
"netloc_no_www",
"(",
"url",
")",
":",
"ext",
"=",
"tldextract",
".",
"extract",
"(",
"url",
")",
"if",
"ext",
".",
"subdomain",
"and",
"ext",
".",
"subdomain",
"!=",
"'www'",
":",
"return",
"'%s.%s.%s'",
"%",
"(",
"ext",
".",
"subdomain",
",",
"ext",
".",
"domain",
",",
"ext",
".",
"tld",
")",
"else",
":",
"return",
"'%s.%s'",
"%",
"(",
"ext",
".",
"domain",
",",
"ext",
".",
"tld",
")"
] | For a given URL return the netloc with any www. striped. | [
"For",
"a",
"given",
"URL",
"return",
"the",
"netloc",
"with",
"any",
"www",
".",
"striped",
"."
] | b64106392fad596defc915b8235fe6e1d0013b5b | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/url/shorten.py#L55-L63 |
247,710 | eallik/spinoff | geventreactor/__init__.py | deferToGreenletPool | def deferToGreenletPool(*args, **kwargs):
"""Call function using a greenlet from the given pool and return the result as a Deferred"""
reactor = args[0]
pool = args[1]
func = args[2]
d = defer.Deferred()
def task():
try:
reactor.callFromGreenlet(d.callback, func(*args[3:], **kwargs))
except:
reactor.callFromGreenlet(d.errback, failure.Failure())
pool.add(spawn(task))
return d | python | def deferToGreenletPool(*args, **kwargs):
"""Call function using a greenlet from the given pool and return the result as a Deferred"""
reactor = args[0]
pool = args[1]
func = args[2]
d = defer.Deferred()
def task():
try:
reactor.callFromGreenlet(d.callback, func(*args[3:], **kwargs))
except:
reactor.callFromGreenlet(d.errback, failure.Failure())
pool.add(spawn(task))
return d | [
"def",
"deferToGreenletPool",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"reactor",
"=",
"args",
"[",
"0",
"]",
"pool",
"=",
"args",
"[",
"1",
"]",
"func",
"=",
"args",
"[",
"2",
"]",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"def",
"task",
"(",
")",
":",
"try",
":",
"reactor",
".",
"callFromGreenlet",
"(",
"d",
".",
"callback",
",",
"func",
"(",
"*",
"args",
"[",
"3",
":",
"]",
",",
"*",
"*",
"kwargs",
")",
")",
"except",
":",
"reactor",
".",
"callFromGreenlet",
"(",
"d",
".",
"errback",
",",
"failure",
".",
"Failure",
"(",
")",
")",
"pool",
".",
"add",
"(",
"spawn",
"(",
"task",
")",
")",
"return",
"d"
] | Call function using a greenlet from the given pool and return the result as a Deferred | [
"Call",
"function",
"using",
"a",
"greenlet",
"from",
"the",
"given",
"pool",
"and",
"return",
"the",
"result",
"as",
"a",
"Deferred"
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L52-L65 |
247,711 | eallik/spinoff | geventreactor/__init__.py | deferToGreenlet | def deferToGreenlet(*args, **kwargs):
"""Call function using a greenlet and return the result as a Deferred"""
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
return deferToGreenletPool(reactor, reactor.getGreenletPool(), *args, **kwargs) | python | def deferToGreenlet(*args, **kwargs):
"""Call function using a greenlet and return the result as a Deferred"""
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
return deferToGreenletPool(reactor, reactor.getGreenletPool(), *args, **kwargs) | [
"def",
"deferToGreenlet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"assert",
"reactor",
".",
"greenlet",
"==",
"getcurrent",
"(",
")",
",",
"\"must invoke this in the reactor greenlet\"",
"return",
"deferToGreenletPool",
"(",
"reactor",
",",
"reactor",
".",
"getGreenletPool",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call function using a greenlet and return the result as a Deferred | [
"Call",
"function",
"using",
"a",
"greenlet",
"and",
"return",
"the",
"result",
"as",
"a",
"Deferred"
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L68-L72 |
247,712 | eallik/spinoff | geventreactor/__init__.py | callMultipleInGreenlet | def callMultipleInGreenlet(tupleList):
"""Call a list of functions in the same thread"""
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
reactor.callInGreenlet(_runMultiple, tupleList) | python | def callMultipleInGreenlet(tupleList):
"""Call a list of functions in the same thread"""
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
reactor.callInGreenlet(_runMultiple, tupleList) | [
"def",
"callMultipleInGreenlet",
"(",
"tupleList",
")",
":",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"assert",
"reactor",
".",
"greenlet",
"==",
"getcurrent",
"(",
")",
",",
"\"must invoke this in the reactor greenlet\"",
"reactor",
".",
"callInGreenlet",
"(",
"_runMultiple",
",",
"tupleList",
")"
] | Call a list of functions in the same thread | [
"Call",
"a",
"list",
"of",
"functions",
"in",
"the",
"same",
"thread"
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L75-L79 |
247,713 | eallik/spinoff | geventreactor/__init__.py | waitForGreenlet | def waitForGreenlet(g):
"""Link greenlet completion to Deferred"""
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
d = defer.Deferred()
def cb(g):
try:
d.callback(g.get())
except:
d.errback(failure.Failure())
g.link(d)
return d | python | def waitForGreenlet(g):
"""Link greenlet completion to Deferred"""
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
d = defer.Deferred()
def cb(g):
try:
d.callback(g.get())
except:
d.errback(failure.Failure())
g.link(d)
return d | [
"def",
"waitForGreenlet",
"(",
"g",
")",
":",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"assert",
"reactor",
".",
"greenlet",
"==",
"getcurrent",
"(",
")",
",",
"\"must invoke this in the reactor greenlet\"",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"def",
"cb",
"(",
"g",
")",
":",
"try",
":",
"d",
".",
"callback",
"(",
"g",
".",
"get",
"(",
")",
")",
"except",
":",
"d",
".",
"errback",
"(",
"failure",
".",
"Failure",
"(",
")",
")",
"g",
".",
"link",
"(",
"d",
")",
"return",
"d"
] | Link greenlet completion to Deferred | [
"Link",
"greenlet",
"completion",
"to",
"Deferred"
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L82-L95 |
247,714 | eallik/spinoff | geventreactor/__init__.py | waitForDeferred | def waitForDeferred(d, result=None):
"""Block current greenlet for Deferred, waiting until result is not a Deferred or a failure is encountered"""
from twisted.internet import reactor
assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
if result is None:
result = AsyncResult()
def cb(res):
if isinstance(res, defer.Deferred):
waitForDeferred(res, result)
else:
result.set(res)
def eb(res):
result.set_exception(res)
d.addCallbacks(cb, eb)
try:
return result.get()
except failure.Failure, ex:
ex.raiseException() | python | def waitForDeferred(d, result=None):
"""Block current greenlet for Deferred, waiting until result is not a Deferred or a failure is encountered"""
from twisted.internet import reactor
assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
if result is None:
result = AsyncResult()
def cb(res):
if isinstance(res, defer.Deferred):
waitForDeferred(res, result)
else:
result.set(res)
def eb(res):
result.set_exception(res)
d.addCallbacks(cb, eb)
try:
return result.get()
except failure.Failure, ex:
ex.raiseException() | [
"def",
"waitForDeferred",
"(",
"d",
",",
"result",
"=",
"None",
")",
":",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"assert",
"reactor",
".",
"greenlet",
"!=",
"getcurrent",
"(",
")",
",",
"\"can't invoke this in the reactor greenlet\"",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"AsyncResult",
"(",
")",
"def",
"cb",
"(",
"res",
")",
":",
"if",
"isinstance",
"(",
"res",
",",
"defer",
".",
"Deferred",
")",
":",
"waitForDeferred",
"(",
"res",
",",
"result",
")",
"else",
":",
"result",
".",
"set",
"(",
"res",
")",
"def",
"eb",
"(",
"res",
")",
":",
"result",
".",
"set_exception",
"(",
"res",
")",
"d",
".",
"addCallbacks",
"(",
"cb",
",",
"eb",
")",
"try",
":",
"return",
"result",
".",
"get",
"(",
")",
"except",
"failure",
".",
"Failure",
",",
"ex",
":",
"ex",
".",
"raiseException",
"(",
")"
] | Block current greenlet for Deferred, waiting until result is not a Deferred or a failure is encountered | [
"Block",
"current",
"greenlet",
"for",
"Deferred",
"waiting",
"until",
"result",
"is",
"not",
"a",
"Deferred",
"or",
"a",
"failure",
"is",
"encountered"
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L98-L118 |
247,715 | eallik/spinoff | geventreactor/__init__.py | blockingCallFromGreenlet | def blockingCallFromGreenlet(*args, **kwargs):
"""Call function in reactor greenlet and block current greenlet waiting for the result"""
reactor = args[0]
assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
func = args[1]
result = AsyncResult()
def task():
try:
result.set(func(*args[2:], **kwargs))
except Exception, ex:
result.set_exception(ex)
reactor.callFromGreenlet(task)
value = result.get()
if isinstance(value, defer.Deferred):
return waitForDeferred(value)
else:
return value | python | def blockingCallFromGreenlet(*args, **kwargs):
"""Call function in reactor greenlet and block current greenlet waiting for the result"""
reactor = args[0]
assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
func = args[1]
result = AsyncResult()
def task():
try:
result.set(func(*args[2:], **kwargs))
except Exception, ex:
result.set_exception(ex)
reactor.callFromGreenlet(task)
value = result.get()
if isinstance(value, defer.Deferred):
return waitForDeferred(value)
else:
return value | [
"def",
"blockingCallFromGreenlet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"reactor",
"=",
"args",
"[",
"0",
"]",
"assert",
"reactor",
".",
"greenlet",
"!=",
"getcurrent",
"(",
")",
",",
"\"can't invoke this in the reactor greenlet\"",
"func",
"=",
"args",
"[",
"1",
"]",
"result",
"=",
"AsyncResult",
"(",
")",
"def",
"task",
"(",
")",
":",
"try",
":",
"result",
".",
"set",
"(",
"func",
"(",
"*",
"args",
"[",
"2",
":",
"]",
",",
"*",
"*",
"kwargs",
")",
")",
"except",
"Exception",
",",
"ex",
":",
"result",
".",
"set_exception",
"(",
"ex",
")",
"reactor",
".",
"callFromGreenlet",
"(",
"task",
")",
"value",
"=",
"result",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"defer",
".",
"Deferred",
")",
":",
"return",
"waitForDeferred",
"(",
"value",
")",
"else",
":",
"return",
"value"
] | Call function in reactor greenlet and block current greenlet waiting for the result | [
"Call",
"function",
"in",
"reactor",
"greenlet",
"and",
"block",
"current",
"greenlet",
"waiting",
"for",
"the",
"result"
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L121-L139 |
247,716 | eallik/spinoff | geventreactor/__init__.py | GeventReactor.mainLoop | def mainLoop(self):
"""This main loop yields to gevent until the end, handling function calls along the way."""
self.greenlet = gevent.getcurrent()
callqueue = self._callqueue
seconds = self.seconds
try:
while 1:
self._wait = 0
now = seconds()
if len(callqueue) > 0:
self._wake = delay = callqueue[0].time
delay -= now
else:
self._wake = now + 300
delay = 300
try:
self._wait = 1
try:
self._threadCallNotification.get(timeout=delay if delay > 0 else 0)
except Empty:
pass
else:
raise Reschedule
self._wait = 0
except Reschedule:
if self.threadCallQueue:
total = len(self.threadCallQueue)
count = 0
for fn, args, kwargs in self.threadCallQueue:
try:
fn(*args, **kwargs)
except:
log.err()
count += 1
if count == total:
break
del self.threadCallQueue[:count]
if self.threadCallQueue:
self.wakeUp()
continue
now = seconds()
while 1:
try:
c = callqueue[0]
except IndexError:
break
if c.time <= now:
del callqueue[0]
try:
c()
except GreenletExit:
raise
except:
log.msg('Unexpected error in main loop.')
log.err()
else:
break
except (GreenletExit, KeyboardInterrupt):
pass
log.msg('Main loop terminated.')
self.fireSystemEvent('shutdown') | python | def mainLoop(self):
"""This main loop yields to gevent until the end, handling function calls along the way."""
self.greenlet = gevent.getcurrent()
callqueue = self._callqueue
seconds = self.seconds
try:
while 1:
self._wait = 0
now = seconds()
if len(callqueue) > 0:
self._wake = delay = callqueue[0].time
delay -= now
else:
self._wake = now + 300
delay = 300
try:
self._wait = 1
try:
self._threadCallNotification.get(timeout=delay if delay > 0 else 0)
except Empty:
pass
else:
raise Reschedule
self._wait = 0
except Reschedule:
if self.threadCallQueue:
total = len(self.threadCallQueue)
count = 0
for fn, args, kwargs in self.threadCallQueue:
try:
fn(*args, **kwargs)
except:
log.err()
count += 1
if count == total:
break
del self.threadCallQueue[:count]
if self.threadCallQueue:
self.wakeUp()
continue
now = seconds()
while 1:
try:
c = callqueue[0]
except IndexError:
break
if c.time <= now:
del callqueue[0]
try:
c()
except GreenletExit:
raise
except:
log.msg('Unexpected error in main loop.')
log.err()
else:
break
except (GreenletExit, KeyboardInterrupt):
pass
log.msg('Main loop terminated.')
self.fireSystemEvent('shutdown') | [
"def",
"mainLoop",
"(",
"self",
")",
":",
"self",
".",
"greenlet",
"=",
"gevent",
".",
"getcurrent",
"(",
")",
"callqueue",
"=",
"self",
".",
"_callqueue",
"seconds",
"=",
"self",
".",
"seconds",
"try",
":",
"while",
"1",
":",
"self",
".",
"_wait",
"=",
"0",
"now",
"=",
"seconds",
"(",
")",
"if",
"len",
"(",
"callqueue",
")",
">",
"0",
":",
"self",
".",
"_wake",
"=",
"delay",
"=",
"callqueue",
"[",
"0",
"]",
".",
"time",
"delay",
"-=",
"now",
"else",
":",
"self",
".",
"_wake",
"=",
"now",
"+",
"300",
"delay",
"=",
"300",
"try",
":",
"self",
".",
"_wait",
"=",
"1",
"try",
":",
"self",
".",
"_threadCallNotification",
".",
"get",
"(",
"timeout",
"=",
"delay",
"if",
"delay",
">",
"0",
"else",
"0",
")",
"except",
"Empty",
":",
"pass",
"else",
":",
"raise",
"Reschedule",
"self",
".",
"_wait",
"=",
"0",
"except",
"Reschedule",
":",
"if",
"self",
".",
"threadCallQueue",
":",
"total",
"=",
"len",
"(",
"self",
".",
"threadCallQueue",
")",
"count",
"=",
"0",
"for",
"fn",
",",
"args",
",",
"kwargs",
"in",
"self",
".",
"threadCallQueue",
":",
"try",
":",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"log",
".",
"err",
"(",
")",
"count",
"+=",
"1",
"if",
"count",
"==",
"total",
":",
"break",
"del",
"self",
".",
"threadCallQueue",
"[",
":",
"count",
"]",
"if",
"self",
".",
"threadCallQueue",
":",
"self",
".",
"wakeUp",
"(",
")",
"continue",
"now",
"=",
"seconds",
"(",
")",
"while",
"1",
":",
"try",
":",
"c",
"=",
"callqueue",
"[",
"0",
"]",
"except",
"IndexError",
":",
"break",
"if",
"c",
".",
"time",
"<=",
"now",
":",
"del",
"callqueue",
"[",
"0",
"]",
"try",
":",
"c",
"(",
")",
"except",
"GreenletExit",
":",
"raise",
"except",
":",
"log",
".",
"msg",
"(",
"'Unexpected error in main loop.'",
")",
"log",
".",
"err",
"(",
")",
"else",
":",
"break",
"except",
"(",
"GreenletExit",
",",
"KeyboardInterrupt",
")",
":",
"pass",
"log",
".",
"msg",
"(",
"'Main loop terminated.'",
")",
"self",
".",
"fireSystemEvent",
"(",
"'shutdown'",
")"
] | This main loop yields to gevent until the end, handling function calls along the way. | [
"This",
"main",
"loop",
"yields",
"to",
"gevent",
"until",
"the",
"end",
"handling",
"function",
"calls",
"along",
"the",
"way",
"."
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L357-L417 |
247,717 | eallik/spinoff | geventreactor/__init__.py | GeventReactor.removeReader | def removeReader(self, selectable):
"""Remove a FileDescriptor for notification of data available to read."""
try:
if selectable.disconnected:
self._reads[selectable].kill(block=False)
del self._reads[selectable]
else:
self._reads[selectable].pause()
except KeyError:
pass | python | def removeReader(self, selectable):
"""Remove a FileDescriptor for notification of data available to read."""
try:
if selectable.disconnected:
self._reads[selectable].kill(block=False)
del self._reads[selectable]
else:
self._reads[selectable].pause()
except KeyError:
pass | [
"def",
"removeReader",
"(",
"self",
",",
"selectable",
")",
":",
"try",
":",
"if",
"selectable",
".",
"disconnected",
":",
"self",
".",
"_reads",
"[",
"selectable",
"]",
".",
"kill",
"(",
"block",
"=",
"False",
")",
"del",
"self",
".",
"_reads",
"[",
"selectable",
"]",
"else",
":",
"self",
".",
"_reads",
"[",
"selectable",
"]",
".",
"pause",
"(",
")",
"except",
"KeyError",
":",
"pass"
] | Remove a FileDescriptor for notification of data available to read. | [
"Remove",
"a",
"FileDescriptor",
"for",
"notification",
"of",
"data",
"available",
"to",
"read",
"."
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L435-L444 |
247,718 | eallik/spinoff | geventreactor/__init__.py | GeventReactor.removeWriter | def removeWriter(self, selectable):
"""Remove a FileDescriptor for notification of data available to write."""
try:
if selectable.disconnected:
self._writes[selectable].kill(block=False)
del self._writes[selectable]
else:
self._writes[selectable].pause()
except KeyError:
pass | python | def removeWriter(self, selectable):
"""Remove a FileDescriptor for notification of data available to write."""
try:
if selectable.disconnected:
self._writes[selectable].kill(block=False)
del self._writes[selectable]
else:
self._writes[selectable].pause()
except KeyError:
pass | [
"def",
"removeWriter",
"(",
"self",
",",
"selectable",
")",
":",
"try",
":",
"if",
"selectable",
".",
"disconnected",
":",
"self",
".",
"_writes",
"[",
"selectable",
"]",
".",
"kill",
"(",
"block",
"=",
"False",
")",
"del",
"self",
".",
"_writes",
"[",
"selectable",
"]",
"else",
":",
"self",
".",
"_writes",
"[",
"selectable",
"]",
".",
"pause",
"(",
")",
"except",
"KeyError",
":",
"pass"
] | Remove a FileDescriptor for notification of data available to write. | [
"Remove",
"a",
"FileDescriptor",
"for",
"notification",
"of",
"data",
"available",
"to",
"write",
"."
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/geventreactor/__init__.py#L446-L455 |
247,719 | wonderb0lt/sounddrizzle | sounddrizzle.py | resolve | def resolve(track_url):
"""
Resolves the URL to an actual track from the SoundCloud API.
If the track resolves to more than one possible track, it takes the first search result.
:returns: The track dictionary from the SoundCloud API
"""
try:
path = urlparse.urlparse(track_url).path
tracks = client.get('/tracks', q=path)
if tracks:
return tracks[0]
else:
raise ValueError('Track not found for URL {}'.format(track_url))
except Exception as e:
raise ValueError('Error obtaining track by url: {}'.format(str(e))) | python | def resolve(track_url):
"""
Resolves the URL to an actual track from the SoundCloud API.
If the track resolves to more than one possible track, it takes the first search result.
:returns: The track dictionary from the SoundCloud API
"""
try:
path = urlparse.urlparse(track_url).path
tracks = client.get('/tracks', q=path)
if tracks:
return tracks[0]
else:
raise ValueError('Track not found for URL {}'.format(track_url))
except Exception as e:
raise ValueError('Error obtaining track by url: {}'.format(str(e))) | [
"def",
"resolve",
"(",
"track_url",
")",
":",
"try",
":",
"path",
"=",
"urlparse",
".",
"urlparse",
"(",
"track_url",
")",
".",
"path",
"tracks",
"=",
"client",
".",
"get",
"(",
"'/tracks'",
",",
"q",
"=",
"path",
")",
"if",
"tracks",
":",
"return",
"tracks",
"[",
"0",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Track not found for URL {}'",
".",
"format",
"(",
"track_url",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"'Error obtaining track by url: {}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")"
] | Resolves the URL to an actual track from the SoundCloud API.
If the track resolves to more than one possible track, it takes the first search result.
:returns: The track dictionary from the SoundCloud API | [
"Resolves",
"the",
"URL",
"to",
"an",
"actual",
"track",
"from",
"the",
"SoundCloud",
"API",
"."
] | e668e2e56e2a267329afa1d510556dd296fb8026 | https://github.com/wonderb0lt/sounddrizzle/blob/e668e2e56e2a267329afa1d510556dd296fb8026/sounddrizzle.py#L38-L55 |
247,720 | wonderb0lt/sounddrizzle | sounddrizzle.py | download | def download(url, target_file, chunk_size=4096):
"""
Simple requests downloader
"""
r = requests.get(url, stream=True)
with open(target_file, 'w+') as out:
# And this is why I love Armin Ronacher:
with click.progressbar(r.iter_content(chunk_size=chunk_size),
int(r.headers['Content-Length'])/chunk_size,
label='Downloading...') as chunks:
for chunk in chunks:
out.write(chunk) | python | def download(url, target_file, chunk_size=4096):
"""
Simple requests downloader
"""
r = requests.get(url, stream=True)
with open(target_file, 'w+') as out:
# And this is why I love Armin Ronacher:
with click.progressbar(r.iter_content(chunk_size=chunk_size),
int(r.headers['Content-Length'])/chunk_size,
label='Downloading...') as chunks:
for chunk in chunks:
out.write(chunk) | [
"def",
"download",
"(",
"url",
",",
"target_file",
",",
"chunk_size",
"=",
"4096",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"with",
"open",
"(",
"target_file",
",",
"'w+'",
")",
"as",
"out",
":",
"# And this is why I love Armin Ronacher:",
"with",
"click",
".",
"progressbar",
"(",
"r",
".",
"iter_content",
"(",
"chunk_size",
"=",
"chunk_size",
")",
",",
"int",
"(",
"r",
".",
"headers",
"[",
"'Content-Length'",
"]",
")",
"/",
"chunk_size",
",",
"label",
"=",
"'Downloading...'",
")",
"as",
"chunks",
":",
"for",
"chunk",
"in",
"chunks",
":",
"out",
".",
"write",
"(",
"chunk",
")"
] | Simple requests downloader | [
"Simple",
"requests",
"downloader"
] | e668e2e56e2a267329afa1d510556dd296fb8026 | https://github.com/wonderb0lt/sounddrizzle/blob/e668e2e56e2a267329afa1d510556dd296fb8026/sounddrizzle.py#L68-L80 |
247,721 | wonderb0lt/sounddrizzle | sounddrizzle.py | add_metadata | def add_metadata(track_file, track_data):
"""
Adds artist and title from the track data, and downloads the cover and embeds it in the MP3 tags.
"""
# This needs some exception handling!
# We don't always know what type the cover is!
mp3 = mutagen.mp3.MP3(track_file)
mp3['TPE1'] = mutagen.id3.TPE1(encoding=3, text=track_data.user['username'])
mp3['TIT2'] = mutagen.id3.TIT2(encoding=3, text=track_data.title)
cover_bytes = requests.get(track_data.artwork_url, stream=True).raw.read()
mp3.tags.add(mutagen.id3.APIC(encoding=3, mime='image/jpeg', type=3, desc='Front cover', data=cover_bytes))
mp3.save() | python | def add_metadata(track_file, track_data):
"""
Adds artist and title from the track data, and downloads the cover and embeds it in the MP3 tags.
"""
# This needs some exception handling!
# We don't always know what type the cover is!
mp3 = mutagen.mp3.MP3(track_file)
mp3['TPE1'] = mutagen.id3.TPE1(encoding=3, text=track_data.user['username'])
mp3['TIT2'] = mutagen.id3.TIT2(encoding=3, text=track_data.title)
cover_bytes = requests.get(track_data.artwork_url, stream=True).raw.read()
mp3.tags.add(mutagen.id3.APIC(encoding=3, mime='image/jpeg', type=3, desc='Front cover', data=cover_bytes))
mp3.save() | [
"def",
"add_metadata",
"(",
"track_file",
",",
"track_data",
")",
":",
"# This needs some exception handling!",
"# We don't always know what type the cover is!",
"mp3",
"=",
"mutagen",
".",
"mp3",
".",
"MP3",
"(",
"track_file",
")",
"mp3",
"[",
"'TPE1'",
"]",
"=",
"mutagen",
".",
"id3",
".",
"TPE1",
"(",
"encoding",
"=",
"3",
",",
"text",
"=",
"track_data",
".",
"user",
"[",
"'username'",
"]",
")",
"mp3",
"[",
"'TIT2'",
"]",
"=",
"mutagen",
".",
"id3",
".",
"TIT2",
"(",
"encoding",
"=",
"3",
",",
"text",
"=",
"track_data",
".",
"title",
")",
"cover_bytes",
"=",
"requests",
".",
"get",
"(",
"track_data",
".",
"artwork_url",
",",
"stream",
"=",
"True",
")",
".",
"raw",
".",
"read",
"(",
")",
"mp3",
".",
"tags",
".",
"add",
"(",
"mutagen",
".",
"id3",
".",
"APIC",
"(",
"encoding",
"=",
"3",
",",
"mime",
"=",
"'image/jpeg'",
",",
"type",
"=",
"3",
",",
"desc",
"=",
"'Front cover'",
",",
"data",
"=",
"cover_bytes",
")",
")",
"mp3",
".",
"save",
"(",
")"
] | Adds artist and title from the track data, and downloads the cover and embeds it in the MP3 tags. | [
"Adds",
"artist",
"and",
"title",
"from",
"the",
"track",
"data",
"and",
"downloads",
"the",
"cover",
"and",
"embeds",
"it",
"in",
"the",
"MP3",
"tags",
"."
] | e668e2e56e2a267329afa1d510556dd296fb8026 | https://github.com/wonderb0lt/sounddrizzle/blob/e668e2e56e2a267329afa1d510556dd296fb8026/sounddrizzle.py#L83-L97 |
247,722 | ulf1/oxyba | oxyba/linreg_ridge_gd.py | linreg_ridge_gd | def linreg_ridge_gd(y, X, lam, algorithm='L-BFGS-B', debug=False):
"""Ridge Regression with Gradient Optimization methods
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm : str
Optional. The algorithm used in scipy.optimize.minimize
and 'L-BFGS-B' (Limited BFGS) as default.
Eligible algorithms are 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B',
'TNC', and 'SLSQP' as these use the supplied gradient function.
This is an unconstrained optimization problem. Thus, the 'L-BFGS-B',
'TNC' and 'SLSQP' options does not make use of constraints.
'TNC' (Truncated Newton) seems to be suited to for larger datasets
and 'L-BFGS-B' (Limited BFGS) if computing powever becomes an issue.
debug : bool
Optional.
Returns:
--------
beta : ndarray
Estimated regression coefficients.
results : scipy.optimize.optimize.OptimizeResult
Optional. If debug=True then only scipy's
optimization result variable is returned.
"""
import numpy as np
import scipy.optimize as sopt
def objective_pssr(theta, y, X, lam):
return np.sum((y - np.dot(X, theta))**2) + lam * np.sum(theta**2)
def gradient_pssr(theta, y, X, lam):
return -2.0 * np.dot(X.T, (y - np.dot(X, theta))) + 2.0 * lam * theta
# check eligible algorithm
if algorithm not in ('CG', 'BFGS', 'Newton-CG',
'L-BFGS-B', 'TNC', 'SLSQP'):
raise Exception('Optimization Algorithm not supported.')
# set start values
theta0 = np.ones((X.shape[1],))
# run solver
results = sopt.minimize(
objective_pssr,
theta0,
jac=gradient_pssr,
args=(y, X, lam),
method=algorithm,
options={'disp': False})
# debug?
if debug:
return results
# done
return results.x | python | def linreg_ridge_gd(y, X, lam, algorithm='L-BFGS-B', debug=False):
"""Ridge Regression with Gradient Optimization methods
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm : str
Optional. The algorithm used in scipy.optimize.minimize
and 'L-BFGS-B' (Limited BFGS) as default.
Eligible algorithms are 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B',
'TNC', and 'SLSQP' as these use the supplied gradient function.
This is an unconstrained optimization problem. Thus, the 'L-BFGS-B',
'TNC' and 'SLSQP' options does not make use of constraints.
'TNC' (Truncated Newton) seems to be suited to for larger datasets
and 'L-BFGS-B' (Limited BFGS) if computing powever becomes an issue.
debug : bool
Optional.
Returns:
--------
beta : ndarray
Estimated regression coefficients.
results : scipy.optimize.optimize.OptimizeResult
Optional. If debug=True then only scipy's
optimization result variable is returned.
"""
import numpy as np
import scipy.optimize as sopt
def objective_pssr(theta, y, X, lam):
return np.sum((y - np.dot(X, theta))**2) + lam * np.sum(theta**2)
def gradient_pssr(theta, y, X, lam):
return -2.0 * np.dot(X.T, (y - np.dot(X, theta))) + 2.0 * lam * theta
# check eligible algorithm
if algorithm not in ('CG', 'BFGS', 'Newton-CG',
'L-BFGS-B', 'TNC', 'SLSQP'):
raise Exception('Optimization Algorithm not supported.')
# set start values
theta0 = np.ones((X.shape[1],))
# run solver
results = sopt.minimize(
objective_pssr,
theta0,
jac=gradient_pssr,
args=(y, X, lam),
method=algorithm,
options={'disp': False})
# debug?
if debug:
return results
# done
return results.x | [
"def",
"linreg_ridge_gd",
"(",
"y",
",",
"X",
",",
"lam",
",",
"algorithm",
"=",
"'L-BFGS-B'",
",",
"debug",
"=",
"False",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"optimize",
"as",
"sopt",
"def",
"objective_pssr",
"(",
"theta",
",",
"y",
",",
"X",
",",
"lam",
")",
":",
"return",
"np",
".",
"sum",
"(",
"(",
"y",
"-",
"np",
".",
"dot",
"(",
"X",
",",
"theta",
")",
")",
"**",
"2",
")",
"+",
"lam",
"*",
"np",
".",
"sum",
"(",
"theta",
"**",
"2",
")",
"def",
"gradient_pssr",
"(",
"theta",
",",
"y",
",",
"X",
",",
"lam",
")",
":",
"return",
"-",
"2.0",
"*",
"np",
".",
"dot",
"(",
"X",
".",
"T",
",",
"(",
"y",
"-",
"np",
".",
"dot",
"(",
"X",
",",
"theta",
")",
")",
")",
"+",
"2.0",
"*",
"lam",
"*",
"theta",
"# check eligible algorithm",
"if",
"algorithm",
"not",
"in",
"(",
"'CG'",
",",
"'BFGS'",
",",
"'Newton-CG'",
",",
"'L-BFGS-B'",
",",
"'TNC'",
",",
"'SLSQP'",
")",
":",
"raise",
"Exception",
"(",
"'Optimization Algorithm not supported.'",
")",
"# set start values",
"theta0",
"=",
"np",
".",
"ones",
"(",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
",",
")",
")",
"# run solver",
"results",
"=",
"sopt",
".",
"minimize",
"(",
"objective_pssr",
",",
"theta0",
",",
"jac",
"=",
"gradient_pssr",
",",
"args",
"=",
"(",
"y",
",",
"X",
",",
"lam",
")",
",",
"method",
"=",
"algorithm",
",",
"options",
"=",
"{",
"'disp'",
":",
"False",
"}",
")",
"# debug?",
"if",
"debug",
":",
"return",
"results",
"# done",
"return",
"results",
".",
"x"
] | Ridge Regression with Gradient Optimization methods
Parameters:
-----------
y : ndarray
target variable with N observations
X : ndarray
The <N x C> design matrix with C independent
variables, features, factors, etc.
algorithm : str
Optional. The algorithm used in scipy.optimize.minimize
and 'L-BFGS-B' (Limited BFGS) as default.
Eligible algorithms are 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B',
'TNC', and 'SLSQP' as these use the supplied gradient function.
This is an unconstrained optimization problem. Thus, the 'L-BFGS-B',
'TNC' and 'SLSQP' options does not make use of constraints.
'TNC' (Truncated Newton) seems to be suited to for larger datasets
and 'L-BFGS-B' (Limited BFGS) if computing powever becomes an issue.
debug : bool
Optional.
Returns:
--------
beta : ndarray
Estimated regression coefficients.
results : scipy.optimize.optimize.OptimizeResult
Optional. If debug=True then only scipy's
optimization result variable is returned. | [
"Ridge",
"Regression",
"with",
"Gradient",
"Optimization",
"methods"
] | b3043116050de275124365cb11e7df91fb40169d | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/linreg_ridge_gd.py#L2-L70 |
247,723 | mccutchen/triangulizor | triangulizor/triangulizor.py | triangulize | def triangulize(image, tile_size):
"""Processes the given image by breaking it down into tiles of the given
size and applying a triangular effect to each tile. Returns the processed
image as a PIL Image object.
The image can be given as anything suitable for passing to `Image.open`
(ie, the path to an image or as a file-like object containing image data).
If tile_size is 0, the tile size will be guessed based on the image
size. It will also be adjusted to be divisible by 2 if it is not already.
"""
if isinstance(image, basestring) or hasattr(image, 'read'):
image = Image.open(image)
assert isinstance(tile_size, int)
# Make sure we have a usable tile size, by guessing based on image size
# and making sure it's a multiple of two.
if tile_size == 0:
tile_size = guess_tile_size(image)
if tile_size % 2 != 0:
tile_size = (tile_size / 2) * 2
logging.info('Input image size: %r', image.size)
logging.info('Tile size: %r', tile_size)
# Preprocess image to make sure it's at a size we can handle
image = prep_image(image, tile_size)
logging.info('Prepped image size: %r', image.size)
# Get pixmap (for direct pixel access) and draw objects for the image.
pix = image.load()
draw = ImageDraw.Draw(image)
# Process the image, tile by tile
for x, y in iter_tiles(image, tile_size):
process_tile(x, y, tile_size, pix, draw, image)
return image | python | def triangulize(image, tile_size):
"""Processes the given image by breaking it down into tiles of the given
size and applying a triangular effect to each tile. Returns the processed
image as a PIL Image object.
The image can be given as anything suitable for passing to `Image.open`
(ie, the path to an image or as a file-like object containing image data).
If tile_size is 0, the tile size will be guessed based on the image
size. It will also be adjusted to be divisible by 2 if it is not already.
"""
if isinstance(image, basestring) or hasattr(image, 'read'):
image = Image.open(image)
assert isinstance(tile_size, int)
# Make sure we have a usable tile size, by guessing based on image size
# and making sure it's a multiple of two.
if tile_size == 0:
tile_size = guess_tile_size(image)
if tile_size % 2 != 0:
tile_size = (tile_size / 2) * 2
logging.info('Input image size: %r', image.size)
logging.info('Tile size: %r', tile_size)
# Preprocess image to make sure it's at a size we can handle
image = prep_image(image, tile_size)
logging.info('Prepped image size: %r', image.size)
# Get pixmap (for direct pixel access) and draw objects for the image.
pix = image.load()
draw = ImageDraw.Draw(image)
# Process the image, tile by tile
for x, y in iter_tiles(image, tile_size):
process_tile(x, y, tile_size, pix, draw, image)
return image | [
"def",
"triangulize",
"(",
"image",
",",
"tile_size",
")",
":",
"if",
"isinstance",
"(",
"image",
",",
"basestring",
")",
"or",
"hasattr",
"(",
"image",
",",
"'read'",
")",
":",
"image",
"=",
"Image",
".",
"open",
"(",
"image",
")",
"assert",
"isinstance",
"(",
"tile_size",
",",
"int",
")",
"# Make sure we have a usable tile size, by guessing based on image size",
"# and making sure it's a multiple of two.",
"if",
"tile_size",
"==",
"0",
":",
"tile_size",
"=",
"guess_tile_size",
"(",
"image",
")",
"if",
"tile_size",
"%",
"2",
"!=",
"0",
":",
"tile_size",
"=",
"(",
"tile_size",
"/",
"2",
")",
"*",
"2",
"logging",
".",
"info",
"(",
"'Input image size: %r'",
",",
"image",
".",
"size",
")",
"logging",
".",
"info",
"(",
"'Tile size: %r'",
",",
"tile_size",
")",
"# Preprocess image to make sure it's at a size we can handle",
"image",
"=",
"prep_image",
"(",
"image",
",",
"tile_size",
")",
"logging",
".",
"info",
"(",
"'Prepped image size: %r'",
",",
"image",
".",
"size",
")",
"# Get pixmap (for direct pixel access) and draw objects for the image.",
"pix",
"=",
"image",
".",
"load",
"(",
")",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"image",
")",
"# Process the image, tile by tile",
"for",
"x",
",",
"y",
"in",
"iter_tiles",
"(",
"image",
",",
"tile_size",
")",
":",
"process_tile",
"(",
"x",
",",
"y",
",",
"tile_size",
",",
"pix",
",",
"draw",
",",
"image",
")",
"return",
"image"
] | Processes the given image by breaking it down into tiles of the given
size and applying a triangular effect to each tile. Returns the processed
image as a PIL Image object.
The image can be given as anything suitable for passing to `Image.open`
(ie, the path to an image or as a file-like object containing image data).
If tile_size is 0, the tile size will be guessed based on the image
size. It will also be adjusted to be divisible by 2 if it is not already. | [
"Processes",
"the",
"given",
"image",
"by",
"breaking",
"it",
"down",
"into",
"tiles",
"of",
"the",
"given",
"size",
"and",
"applying",
"a",
"triangular",
"effect",
"to",
"each",
"tile",
".",
"Returns",
"the",
"processed",
"image",
"as",
"a",
"PIL",
"Image",
"object",
"."
] | 8be58de01327f87af33ce7df8077d1582e75c005 | https://github.com/mccutchen/triangulizor/blob/8be58de01327f87af33ce7df8077d1582e75c005/triangulizor/triangulizor.py#L22-L58 |
247,724 | mccutchen/triangulizor | triangulizor/triangulizor.py | process_tile | def process_tile(tile_x, tile_y, tile_size, pix, draw, image):
"""Process a tile whose top left corner is at the given x and y
coordinates.
"""
logging.debug('Processing tile (%d, %d)', tile_x, tile_y)
# Calculate average color for each "triangle" in the given tile
n, e, s, w = triangle_colors(tile_x, tile_y, tile_size, pix)
# Calculate distance between triangle pairs
d_ne = get_color_dist(n, e)
d_nw = get_color_dist(n, w)
d_se = get_color_dist(s, e)
d_sw = get_color_dist(s, w)
# Figure out which pair is the closest, which will determine the direction
# we'll split this tile into triangles. A 'right' split runs from top left
# to bottom right. A 'left' split runs bottom left to top right.
closest = sorted([d_ne, d_nw, d_se, d_sw])[0]
if closest in (d_ne, d_sw):
split = 'right'
elif closest in (d_nw, d_se):
split = 'left'
# Figure out the average color for each side of the "split"
if split == 'right':
top_color = get_average_color([n, e])
bottom_color = get_average_color([s, w])
else:
top_color = get_average_color([n, w])
bottom_color = get_average_color([s, e])
draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color,
draw) | python | def process_tile(tile_x, tile_y, tile_size, pix, draw, image):
"""Process a tile whose top left corner is at the given x and y
coordinates.
"""
logging.debug('Processing tile (%d, %d)', tile_x, tile_y)
# Calculate average color for each "triangle" in the given tile
n, e, s, w = triangle_colors(tile_x, tile_y, tile_size, pix)
# Calculate distance between triangle pairs
d_ne = get_color_dist(n, e)
d_nw = get_color_dist(n, w)
d_se = get_color_dist(s, e)
d_sw = get_color_dist(s, w)
# Figure out which pair is the closest, which will determine the direction
# we'll split this tile into triangles. A 'right' split runs from top left
# to bottom right. A 'left' split runs bottom left to top right.
closest = sorted([d_ne, d_nw, d_se, d_sw])[0]
if closest in (d_ne, d_sw):
split = 'right'
elif closest in (d_nw, d_se):
split = 'left'
# Figure out the average color for each side of the "split"
if split == 'right':
top_color = get_average_color([n, e])
bottom_color = get_average_color([s, w])
else:
top_color = get_average_color([n, w])
bottom_color = get_average_color([s, e])
draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color,
draw) | [
"def",
"process_tile",
"(",
"tile_x",
",",
"tile_y",
",",
"tile_size",
",",
"pix",
",",
"draw",
",",
"image",
")",
":",
"logging",
".",
"debug",
"(",
"'Processing tile (%d, %d)'",
",",
"tile_x",
",",
"tile_y",
")",
"# Calculate average color for each \"triangle\" in the given tile",
"n",
",",
"e",
",",
"s",
",",
"w",
"=",
"triangle_colors",
"(",
"tile_x",
",",
"tile_y",
",",
"tile_size",
",",
"pix",
")",
"# Calculate distance between triangle pairs",
"d_ne",
"=",
"get_color_dist",
"(",
"n",
",",
"e",
")",
"d_nw",
"=",
"get_color_dist",
"(",
"n",
",",
"w",
")",
"d_se",
"=",
"get_color_dist",
"(",
"s",
",",
"e",
")",
"d_sw",
"=",
"get_color_dist",
"(",
"s",
",",
"w",
")",
"# Figure out which pair is the closest, which will determine the direction",
"# we'll split this tile into triangles. A 'right' split runs from top left",
"# to bottom right. A 'left' split runs bottom left to top right.",
"closest",
"=",
"sorted",
"(",
"[",
"d_ne",
",",
"d_nw",
",",
"d_se",
",",
"d_sw",
"]",
")",
"[",
"0",
"]",
"if",
"closest",
"in",
"(",
"d_ne",
",",
"d_sw",
")",
":",
"split",
"=",
"'right'",
"elif",
"closest",
"in",
"(",
"d_nw",
",",
"d_se",
")",
":",
"split",
"=",
"'left'",
"# Figure out the average color for each side of the \"split\"",
"if",
"split",
"==",
"'right'",
":",
"top_color",
"=",
"get_average_color",
"(",
"[",
"n",
",",
"e",
"]",
")",
"bottom_color",
"=",
"get_average_color",
"(",
"[",
"s",
",",
"w",
"]",
")",
"else",
":",
"top_color",
"=",
"get_average_color",
"(",
"[",
"n",
",",
"w",
"]",
")",
"bottom_color",
"=",
"get_average_color",
"(",
"[",
"s",
",",
"e",
"]",
")",
"draw_triangles",
"(",
"tile_x",
",",
"tile_y",
",",
"tile_size",
",",
"split",
",",
"top_color",
",",
"bottom_color",
",",
"draw",
")"
] | Process a tile whose top left corner is at the given x and y
coordinates. | [
"Process",
"a",
"tile",
"whose",
"top",
"left",
"corner",
"is",
"at",
"the",
"given",
"x",
"and",
"y",
"coordinates",
"."
] | 8be58de01327f87af33ce7df8077d1582e75c005 | https://github.com/mccutchen/triangulizor/blob/8be58de01327f87af33ce7df8077d1582e75c005/triangulizor/triangulizor.py#L61-L94 |
247,725 | mccutchen/triangulizor | triangulizor/triangulizor.py | draw_triangles | def draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color,
draw):
"""Draws a triangle on each half of the tile with the given coordinates
and size.
"""
assert split in ('right', 'left')
# The four corners of this tile
nw = (tile_x, tile_y)
ne = (tile_x + tile_size - 1, tile_y)
se = (tile_x + tile_size - 1, tile_y + tile_size)
sw = (tile_x, tile_y + tile_size)
if split == 'left':
# top right triangle
draw_triangle(nw, ne, se, top_color, draw)
# bottom left triangle
draw_triangle(nw, sw, se, bottom_color, draw)
else:
# top left triangle
draw_triangle(sw, nw, ne, top_color, draw)
# bottom right triangle
draw_triangle(sw, se, ne, bottom_color, draw) | python | def draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color,
draw):
"""Draws a triangle on each half of the tile with the given coordinates
and size.
"""
assert split in ('right', 'left')
# The four corners of this tile
nw = (tile_x, tile_y)
ne = (tile_x + tile_size - 1, tile_y)
se = (tile_x + tile_size - 1, tile_y + tile_size)
sw = (tile_x, tile_y + tile_size)
if split == 'left':
# top right triangle
draw_triangle(nw, ne, se, top_color, draw)
# bottom left triangle
draw_triangle(nw, sw, se, bottom_color, draw)
else:
# top left triangle
draw_triangle(sw, nw, ne, top_color, draw)
# bottom right triangle
draw_triangle(sw, se, ne, bottom_color, draw) | [
"def",
"draw_triangles",
"(",
"tile_x",
",",
"tile_y",
",",
"tile_size",
",",
"split",
",",
"top_color",
",",
"bottom_color",
",",
"draw",
")",
":",
"assert",
"split",
"in",
"(",
"'right'",
",",
"'left'",
")",
"# The four corners of this tile",
"nw",
"=",
"(",
"tile_x",
",",
"tile_y",
")",
"ne",
"=",
"(",
"tile_x",
"+",
"tile_size",
"-",
"1",
",",
"tile_y",
")",
"se",
"=",
"(",
"tile_x",
"+",
"tile_size",
"-",
"1",
",",
"tile_y",
"+",
"tile_size",
")",
"sw",
"=",
"(",
"tile_x",
",",
"tile_y",
"+",
"tile_size",
")",
"if",
"split",
"==",
"'left'",
":",
"# top right triangle",
"draw_triangle",
"(",
"nw",
",",
"ne",
",",
"se",
",",
"top_color",
",",
"draw",
")",
"# bottom left triangle",
"draw_triangle",
"(",
"nw",
",",
"sw",
",",
"se",
",",
"bottom_color",
",",
"draw",
")",
"else",
":",
"# top left triangle",
"draw_triangle",
"(",
"sw",
",",
"nw",
",",
"ne",
",",
"top_color",
",",
"draw",
")",
"# bottom right triangle",
"draw_triangle",
"(",
"sw",
",",
"se",
",",
"ne",
",",
"bottom_color",
",",
"draw",
")"
] | Draws a triangle on each half of the tile with the given coordinates
and size. | [
"Draws",
"a",
"triangle",
"on",
"each",
"half",
"of",
"the",
"tile",
"with",
"the",
"given",
"coordinates",
"and",
"size",
"."
] | 8be58de01327f87af33ce7df8077d1582e75c005 | https://github.com/mccutchen/triangulizor/blob/8be58de01327f87af33ce7df8077d1582e75c005/triangulizor/triangulizor.py#L131-L153 |
247,726 | mccutchen/triangulizor | triangulizor/triangulizor.py | draw_triangle | def draw_triangle(a, b, c, color, draw):
"""Draws a triangle with the given vertices in the given color."""
draw.polygon([a, b, c], fill=color) | python | def draw_triangle(a, b, c, color, draw):
"""Draws a triangle with the given vertices in the given color."""
draw.polygon([a, b, c], fill=color) | [
"def",
"draw_triangle",
"(",
"a",
",",
"b",
",",
"c",
",",
"color",
",",
"draw",
")",
":",
"draw",
".",
"polygon",
"(",
"[",
"a",
",",
"b",
",",
"c",
"]",
",",
"fill",
"=",
"color",
")"
] | Draws a triangle with the given vertices in the given color. | [
"Draws",
"a",
"triangle",
"with",
"the",
"given",
"vertices",
"in",
"the",
"given",
"color",
"."
] | 8be58de01327f87af33ce7df8077d1582e75c005 | https://github.com/mccutchen/triangulizor/blob/8be58de01327f87af33ce7df8077d1582e75c005/triangulizor/triangulizor.py#L156-L158 |
247,727 | mccutchen/triangulizor | triangulizor/triangulizor.py | color_reducer | def color_reducer(c1, c2):
"""Helper function used to add two colors together when averaging."""
return tuple(v1 + v2 for v1, v2 in itertools.izip(c1, c2)) | python | def color_reducer(c1, c2):
"""Helper function used to add two colors together when averaging."""
return tuple(v1 + v2 for v1, v2 in itertools.izip(c1, c2)) | [
"def",
"color_reducer",
"(",
"c1",
",",
"c2",
")",
":",
"return",
"tuple",
"(",
"v1",
"+",
"v2",
"for",
"v1",
",",
"v2",
"in",
"itertools",
".",
"izip",
"(",
"c1",
",",
"c2",
")",
")"
] | Helper function used to add two colors together when averaging. | [
"Helper",
"function",
"used",
"to",
"add",
"two",
"colors",
"together",
"when",
"averaging",
"."
] | 8be58de01327f87af33ce7df8077d1582e75c005 | https://github.com/mccutchen/triangulizor/blob/8be58de01327f87af33ce7df8077d1582e75c005/triangulizor/triangulizor.py#L170-L172 |
247,728 | mccutchen/triangulizor | triangulizor/triangulizor.py | get_color_dist | def get_color_dist(c1, c2):
"""Calculates the "distance" between two colors, where the distance is
another color whose components are the absolute values of the difference
between each component of the input colors.
"""
return tuple(abs(v1 - v2) for v1, v2 in itertools.izip(c1, c2)) | python | def get_color_dist(c1, c2):
"""Calculates the "distance" between two colors, where the distance is
another color whose components are the absolute values of the difference
between each component of the input colors.
"""
return tuple(abs(v1 - v2) for v1, v2 in itertools.izip(c1, c2)) | [
"def",
"get_color_dist",
"(",
"c1",
",",
"c2",
")",
":",
"return",
"tuple",
"(",
"abs",
"(",
"v1",
"-",
"v2",
")",
"for",
"v1",
",",
"v2",
"in",
"itertools",
".",
"izip",
"(",
"c1",
",",
"c2",
")",
")"
] | Calculates the "distance" between two colors, where the distance is
another color whose components are the absolute values of the difference
between each component of the input colors. | [
"Calculates",
"the",
"distance",
"between",
"two",
"colors",
"where",
"the",
"distance",
"is",
"another",
"color",
"whose",
"components",
"are",
"the",
"absolute",
"values",
"of",
"the",
"difference",
"between",
"each",
"component",
"of",
"the",
"input",
"colors",
"."
] | 8be58de01327f87af33ce7df8077d1582e75c005 | https://github.com/mccutchen/triangulizor/blob/8be58de01327f87af33ce7df8077d1582e75c005/triangulizor/triangulizor.py#L175-L180 |
247,729 | mccutchen/triangulizor | triangulizor/triangulizor.py | prep_image | def prep_image(image, tile_size):
"""Takes an image and a tile size and returns a possibly cropped version
of the image that is evenly divisible in both dimensions by the tile size.
"""
w, h = image.size
x_tiles = w / tile_size # floor division
y_tiles = h / tile_size
new_w = x_tiles * tile_size
new_h = y_tiles * tile_size
if new_w == w and new_h == h:
return image
else:
crop_bounds = (0, 0, new_w, new_h)
return image.crop(crop_bounds) | python | def prep_image(image, tile_size):
"""Takes an image and a tile size and returns a possibly cropped version
of the image that is evenly divisible in both dimensions by the tile size.
"""
w, h = image.size
x_tiles = w / tile_size # floor division
y_tiles = h / tile_size
new_w = x_tiles * tile_size
new_h = y_tiles * tile_size
if new_w == w and new_h == h:
return image
else:
crop_bounds = (0, 0, new_w, new_h)
return image.crop(crop_bounds) | [
"def",
"prep_image",
"(",
"image",
",",
"tile_size",
")",
":",
"w",
",",
"h",
"=",
"image",
".",
"size",
"x_tiles",
"=",
"w",
"/",
"tile_size",
"# floor division",
"y_tiles",
"=",
"h",
"/",
"tile_size",
"new_w",
"=",
"x_tiles",
"*",
"tile_size",
"new_h",
"=",
"y_tiles",
"*",
"tile_size",
"if",
"new_w",
"==",
"w",
"and",
"new_h",
"==",
"h",
":",
"return",
"image",
"else",
":",
"crop_bounds",
"=",
"(",
"0",
",",
"0",
",",
"new_w",
",",
"new_h",
")",
"return",
"image",
".",
"crop",
"(",
"crop_bounds",
")"
] | Takes an image and a tile size and returns a possibly cropped version
of the image that is evenly divisible in both dimensions by the tile size. | [
"Takes",
"an",
"image",
"and",
"a",
"tile",
"size",
"and",
"returns",
"a",
"possibly",
"cropped",
"version",
"of",
"the",
"image",
"that",
"is",
"evenly",
"divisible",
"in",
"both",
"dimensions",
"by",
"the",
"tile",
"size",
"."
] | 8be58de01327f87af33ce7df8077d1582e75c005 | https://github.com/mccutchen/triangulizor/blob/8be58de01327f87af33ce7df8077d1582e75c005/triangulizor/triangulizor.py#L183-L196 |
247,730 | hirokiky/uiro | uiro/__init__.py | main | def main(global_conf, root, **settings):
""" Entry point to create Uiro application.
Setup all of necessary things:
* Getting root matching
* Initializing DB connection
* Initializing Template Lookups
* Collecting installed applications
* Creating apps for serving static files
and will create/return Uiro application.
"""
matching = import_module_attribute(settings['uiro.root_matching'])
apps = [import_module(app_name)
for app_name in settings['uiro.installed_apps'].split('\n')
if app_name != '']
static_matching = get_static_app_matching(apps)
if static_matching:
matching = static_matching + matching
setup_lookup(apps)
initdb(settings)
return make_wsgi_app(matching) | python | def main(global_conf, root, **settings):
""" Entry point to create Uiro application.
Setup all of necessary things:
* Getting root matching
* Initializing DB connection
* Initializing Template Lookups
* Collecting installed applications
* Creating apps for serving static files
and will create/return Uiro application.
"""
matching = import_module_attribute(settings['uiro.root_matching'])
apps = [import_module(app_name)
for app_name in settings['uiro.installed_apps'].split('\n')
if app_name != '']
static_matching = get_static_app_matching(apps)
if static_matching:
matching = static_matching + matching
setup_lookup(apps)
initdb(settings)
return make_wsgi_app(matching) | [
"def",
"main",
"(",
"global_conf",
",",
"root",
",",
"*",
"*",
"settings",
")",
":",
"matching",
"=",
"import_module_attribute",
"(",
"settings",
"[",
"'uiro.root_matching'",
"]",
")",
"apps",
"=",
"[",
"import_module",
"(",
"app_name",
")",
"for",
"app_name",
"in",
"settings",
"[",
"'uiro.installed_apps'",
"]",
".",
"split",
"(",
"'\\n'",
")",
"if",
"app_name",
"!=",
"''",
"]",
"static_matching",
"=",
"get_static_app_matching",
"(",
"apps",
")",
"if",
"static_matching",
":",
"matching",
"=",
"static_matching",
"+",
"matching",
"setup_lookup",
"(",
"apps",
")",
"initdb",
"(",
"settings",
")",
"return",
"make_wsgi_app",
"(",
"matching",
")"
] | Entry point to create Uiro application.
Setup all of necessary things:
* Getting root matching
* Initializing DB connection
* Initializing Template Lookups
* Collecting installed applications
* Creating apps for serving static files
and will create/return Uiro application. | [
"Entry",
"point",
"to",
"create",
"Uiro",
"application",
"."
] | 8436976b21ac9b0eac4243768f5ada12479b9e00 | https://github.com/hirokiky/uiro/blob/8436976b21ac9b0eac4243768f5ada12479b9e00/uiro/__init__.py#L10-L34 |
247,731 | devricks/soft_drf | soft_drf/api/viewsets/nested.py | NestedViewset.check_parent_object_permissions | def check_parent_object_permissions(self, request, obj):
"""
Check if the request should be permitted for a given parent object.
Raises an appropriate exception if the request is not permitted.
"""
for permission in self.get_parent_permissions():
if not permission.has_object_permission(request, self, obj):
self.permission_denied(request) | python | def check_parent_object_permissions(self, request, obj):
"""
Check if the request should be permitted for a given parent object.
Raises an appropriate exception if the request is not permitted.
"""
for permission in self.get_parent_permissions():
if not permission.has_object_permission(request, self, obj):
self.permission_denied(request) | [
"def",
"check_parent_object_permissions",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"for",
"permission",
"in",
"self",
".",
"get_parent_permissions",
"(",
")",
":",
"if",
"not",
"permission",
".",
"has_object_permission",
"(",
"request",
",",
"self",
",",
"obj",
")",
":",
"self",
".",
"permission_denied",
"(",
"request",
")"
] | Check if the request should be permitted for a given parent object.
Raises an appropriate exception if the request is not permitted. | [
"Check",
"if",
"the",
"request",
"should",
"be",
"permitted",
"for",
"a",
"given",
"parent",
"object",
".",
"Raises",
"an",
"appropriate",
"exception",
"if",
"the",
"request",
"is",
"not",
"permitted",
"."
] | 1869b13f9341bfcebd931059e93de2bc38570da3 | https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/api/viewsets/nested.py#L27-L34 |
247,732 | devricks/soft_drf | soft_drf/api/viewsets/nested.py | NestedViewset.get_parent_object | def get_parent_object(self, parent_queryset=None):
"""
Returns the parent object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if parent objects are referenced using multiple
keyword arguments in the url conf.
"""
if self._parent_object_cache is not None:
return self._parent_object_cache
if parent_queryset is None:
parent_queryset = self.get_parent_queryset()
if self.parent_model is None:
raise ImproperlyConfigured(
"'%s' must define 'parent_model'" % self.__class__.__name__
)
if self.parent_lookup_field is None:
raise ImproperlyConfigured(
"'%s' must define 'parent_lookup_field'" % self.__class__.__name__ # noqa
)
lookup_url_kwarg = '_'.join([
self.parent_model_name or self.parent_model._meta.model_name,
self.parent_lookup_field
])
lookup = self.kwargs.get(lookup_url_kwarg, None)
if lookup is not None:
filter_kwargs = {self.parent_lookup_field: lookup}
else:
raise ImproperlyConfigured(
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the '
'`parent_lookup_field` attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
obj = get_object_or_404(parent_queryset, **filter_kwargs)
self.check_parent_object_permissions(self.request, obj)
self._parent_object_cache = obj
return obj | python | def get_parent_object(self, parent_queryset=None):
"""
Returns the parent object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if parent objects are referenced using multiple
keyword arguments in the url conf.
"""
if self._parent_object_cache is not None:
return self._parent_object_cache
if parent_queryset is None:
parent_queryset = self.get_parent_queryset()
if self.parent_model is None:
raise ImproperlyConfigured(
"'%s' must define 'parent_model'" % self.__class__.__name__
)
if self.parent_lookup_field is None:
raise ImproperlyConfigured(
"'%s' must define 'parent_lookup_field'" % self.__class__.__name__ # noqa
)
lookup_url_kwarg = '_'.join([
self.parent_model_name or self.parent_model._meta.model_name,
self.parent_lookup_field
])
lookup = self.kwargs.get(lookup_url_kwarg, None)
if lookup is not None:
filter_kwargs = {self.parent_lookup_field: lookup}
else:
raise ImproperlyConfigured(
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the '
'`parent_lookup_field` attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
obj = get_object_or_404(parent_queryset, **filter_kwargs)
self.check_parent_object_permissions(self.request, obj)
self._parent_object_cache = obj
return obj | [
"def",
"get_parent_object",
"(",
"self",
",",
"parent_queryset",
"=",
"None",
")",
":",
"if",
"self",
".",
"_parent_object_cache",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_parent_object_cache",
"if",
"parent_queryset",
"is",
"None",
":",
"parent_queryset",
"=",
"self",
".",
"get_parent_queryset",
"(",
")",
"if",
"self",
".",
"parent_model",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"'%s' must define 'parent_model'\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"if",
"self",
".",
"parent_lookup_field",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"'%s' must define 'parent_lookup_field'\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# noqa",
")",
"lookup_url_kwarg",
"=",
"'_'",
".",
"join",
"(",
"[",
"self",
".",
"parent_model_name",
"or",
"self",
".",
"parent_model",
".",
"_meta",
".",
"model_name",
",",
"self",
".",
"parent_lookup_field",
"]",
")",
"lookup",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"lookup_url_kwarg",
",",
"None",
")",
"if",
"lookup",
"is",
"not",
"None",
":",
"filter_kwargs",
"=",
"{",
"self",
".",
"parent_lookup_field",
":",
"lookup",
"}",
"else",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Expected view %s to be called with a URL keyword argument '",
"'named \"%s\". Fix your URL conf, or set the '",
"'`parent_lookup_field` attribute on the view correctly.'",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"lookup_url_kwarg",
")",
")",
"obj",
"=",
"get_object_or_404",
"(",
"parent_queryset",
",",
"*",
"*",
"filter_kwargs",
")",
"self",
".",
"check_parent_object_permissions",
"(",
"self",
".",
"request",
",",
"obj",
")",
"self",
".",
"_parent_object_cache",
"=",
"obj",
"return",
"obj"
] | Returns the parent object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if parent objects are referenced using multiple
keyword arguments in the url conf. | [
"Returns",
"the",
"parent",
"object",
"the",
"view",
"is",
"displaying",
".",
"You",
"may",
"want",
"to",
"override",
"this",
"if",
"you",
"need",
"to",
"provide",
"non",
"-",
"standard",
"queryset",
"lookups",
".",
"Eg",
"if",
"parent",
"objects",
"are",
"referenced",
"using",
"multiple",
"keyword",
"arguments",
"in",
"the",
"url",
"conf",
"."
] | 1869b13f9341bfcebd931059e93de2bc38570da3 | https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/api/viewsets/nested.py#L56-L102 |
247,733 | klorenz/python-argdeco | argdeco/command_decorator.py | CommandDecorator.add_subcommands | def add_subcommands(self, command, *args, **kwargs):
"""add subcommands.
If command already defined, pass args and kwargs to add_subparsers()
method, else to add_parser() method. This behaviour is for convenience,
because I mostly use the sequence:
>>> p = parser.add_parser('foo', help="some help")
>>> subparser = p.add_subparsers()
If you want to configure your sub_parsers, you can do it with:
>>> command.add_subcommands('cmd',
help = "cmd help"
subcommands = dict(
title = "title"
description = "subcommands description"
)
)
"""
subcommands = kwargs.pop('subcommands', None)
try:
cmd = self[command]
except KeyError:
if 'formatter_class' not in kwargs:
kwargs['formatter_class'] = self.formatter_class
cmd = self.add_parser(command, *args, **kwargs)
args, kwargs = tuple(), dict()
if subcommands is not None:
kwargs = subcommands
child = CommandDecorator(
argparser = self.argparser,
commands = cmd.add_subparsers(*args, **kwargs),
parent = self,
name = command,
)
self.children.append(child)
return child | python | def add_subcommands(self, command, *args, **kwargs):
"""add subcommands.
If command already defined, pass args and kwargs to add_subparsers()
method, else to add_parser() method. This behaviour is for convenience,
because I mostly use the sequence:
>>> p = parser.add_parser('foo', help="some help")
>>> subparser = p.add_subparsers()
If you want to configure your sub_parsers, you can do it with:
>>> command.add_subcommands('cmd',
help = "cmd help"
subcommands = dict(
title = "title"
description = "subcommands description"
)
)
"""
subcommands = kwargs.pop('subcommands', None)
try:
cmd = self[command]
except KeyError:
if 'formatter_class' not in kwargs:
kwargs['formatter_class'] = self.formatter_class
cmd = self.add_parser(command, *args, **kwargs)
args, kwargs = tuple(), dict()
if subcommands is not None:
kwargs = subcommands
child = CommandDecorator(
argparser = self.argparser,
commands = cmd.add_subparsers(*args, **kwargs),
parent = self,
name = command,
)
self.children.append(child)
return child | [
"def",
"add_subcommands",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"subcommands",
"=",
"kwargs",
".",
"pop",
"(",
"'subcommands'",
",",
"None",
")",
"try",
":",
"cmd",
"=",
"self",
"[",
"command",
"]",
"except",
"KeyError",
":",
"if",
"'formatter_class'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'formatter_class'",
"]",
"=",
"self",
".",
"formatter_class",
"cmd",
"=",
"self",
".",
"add_parser",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"args",
",",
"kwargs",
"=",
"tuple",
"(",
")",
",",
"dict",
"(",
")",
"if",
"subcommands",
"is",
"not",
"None",
":",
"kwargs",
"=",
"subcommands",
"child",
"=",
"CommandDecorator",
"(",
"argparser",
"=",
"self",
".",
"argparser",
",",
"commands",
"=",
"cmd",
".",
"add_subparsers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"parent",
"=",
"self",
",",
"name",
"=",
"command",
",",
")",
"self",
".",
"children",
".",
"append",
"(",
"child",
")",
"return",
"child"
] | add subcommands.
If command already defined, pass args and kwargs to add_subparsers()
method, else to add_parser() method. This behaviour is for convenience,
because I mostly use the sequence:
>>> p = parser.add_parser('foo', help="some help")
>>> subparser = p.add_subparsers()
If you want to configure your sub_parsers, you can do it with:
>>> command.add_subcommands('cmd',
help = "cmd help"
subcommands = dict(
title = "title"
description = "subcommands description"
)
) | [
"add",
"subcommands",
"."
] | 8d01acef8c19d6883873689d017b14857876412d | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/command_decorator.py#L159-L200 |
247,734 | klorenz/python-argdeco | argdeco/command_decorator.py | CommandDecorator.update | def update(self, command=None, **kwargs):
"""update data, which is usually passed in ArgumentParser initialization
e.g. command.update(prog="foo")
"""
if command is None:
argparser = self.argparser
else:
argparser = self[command]
for k,v in kwargs.items():
setattr(argparser, k, v) | python | def update(self, command=None, **kwargs):
"""update data, which is usually passed in ArgumentParser initialization
e.g. command.update(prog="foo")
"""
if command is None:
argparser = self.argparser
else:
argparser = self[command]
for k,v in kwargs.items():
setattr(argparser, k, v) | [
"def",
"update",
"(",
"self",
",",
"command",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"command",
"is",
"None",
":",
"argparser",
"=",
"self",
".",
"argparser",
"else",
":",
"argparser",
"=",
"self",
"[",
"command",
"]",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"argparser",
",",
"k",
",",
"v",
")"
] | update data, which is usually passed in ArgumentParser initialization
e.g. command.update(prog="foo") | [
"update",
"data",
"which",
"is",
"usually",
"passed",
"in",
"ArgumentParser",
"initialization"
] | 8d01acef8c19d6883873689d017b14857876412d | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/command_decorator.py#L202-L213 |
247,735 | klorenz/python-argdeco | argdeco/command_decorator.py | CommandDecorator.get_config_name | def get_config_name(self, action, name=None):
'''get the name for configuration
This returns a name respecting commands and subcommands. So if you
have a command name "index" with subcommand "ls", which has option
"--all", you will pass the action for subcommand "ls" and the options's
dest name ("all" in this case), then this function will return
"index.ls.all" as configuration name for this option.
'''
_name = None
if name is None:
if '.' in action:
action, name = action.rsplit('.', 1)
else:
_name = ''
name = action
if _name is None:
if isinstance(action, basestring):
action = self.get_action(action)
_name = action.argdeco_name
logger.debug("_name=%s", _name)
config_name = Undefined
while True:
logger.debug("check _name=%s, name=%s", repr(_name), repr(name))
if _name in self.config_map:
if name in self.config_map[_name]:
config_name = self.config_map[_name][name]
if config_name is not None:
if config_name.startswith('.'):
config_name = _name + config_name
break
if _name == '':
break
if '.' not in _name:
_name = ''
continue
_name = _name.rsplit('.', 1)[0]
assert config_name is not Undefined, "could not determine config name for %s" % name
return config_name | python | def get_config_name(self, action, name=None):
'''get the name for configuration
This returns a name respecting commands and subcommands. So if you
have a command name "index" with subcommand "ls", which has option
"--all", you will pass the action for subcommand "ls" and the options's
dest name ("all" in this case), then this function will return
"index.ls.all" as configuration name for this option.
'''
_name = None
if name is None:
if '.' in action:
action, name = action.rsplit('.', 1)
else:
_name = ''
name = action
if _name is None:
if isinstance(action, basestring):
action = self.get_action(action)
_name = action.argdeco_name
logger.debug("_name=%s", _name)
config_name = Undefined
while True:
logger.debug("check _name=%s, name=%s", repr(_name), repr(name))
if _name in self.config_map:
if name in self.config_map[_name]:
config_name = self.config_map[_name][name]
if config_name is not None:
if config_name.startswith('.'):
config_name = _name + config_name
break
if _name == '':
break
if '.' not in _name:
_name = ''
continue
_name = _name.rsplit('.', 1)[0]
assert config_name is not Undefined, "could not determine config name for %s" % name
return config_name | [
"def",
"get_config_name",
"(",
"self",
",",
"action",
",",
"name",
"=",
"None",
")",
":",
"_name",
"=",
"None",
"if",
"name",
"is",
"None",
":",
"if",
"'.'",
"in",
"action",
":",
"action",
",",
"name",
"=",
"action",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"else",
":",
"_name",
"=",
"''",
"name",
"=",
"action",
"if",
"_name",
"is",
"None",
":",
"if",
"isinstance",
"(",
"action",
",",
"basestring",
")",
":",
"action",
"=",
"self",
".",
"get_action",
"(",
"action",
")",
"_name",
"=",
"action",
".",
"argdeco_name",
"logger",
".",
"debug",
"(",
"\"_name=%s\"",
",",
"_name",
")",
"config_name",
"=",
"Undefined",
"while",
"True",
":",
"logger",
".",
"debug",
"(",
"\"check _name=%s, name=%s\"",
",",
"repr",
"(",
"_name",
")",
",",
"repr",
"(",
"name",
")",
")",
"if",
"_name",
"in",
"self",
".",
"config_map",
":",
"if",
"name",
"in",
"self",
".",
"config_map",
"[",
"_name",
"]",
":",
"config_name",
"=",
"self",
".",
"config_map",
"[",
"_name",
"]",
"[",
"name",
"]",
"if",
"config_name",
"is",
"not",
"None",
":",
"if",
"config_name",
".",
"startswith",
"(",
"'.'",
")",
":",
"config_name",
"=",
"_name",
"+",
"config_name",
"break",
"if",
"_name",
"==",
"''",
":",
"break",
"if",
"'.'",
"not",
"in",
"_name",
":",
"_name",
"=",
"''",
"continue",
"_name",
"=",
"_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"assert",
"config_name",
"is",
"not",
"Undefined",
",",
"\"could not determine config name for %s\"",
"%",
"name",
"return",
"config_name"
] | get the name for configuration
This returns a name respecting commands and subcommands. So if you
have a command name "index" with subcommand "ls", which has option
"--all", you will pass the action for subcommand "ls" and the options's
dest name ("all" in this case), then this function will return
"index.ls.all" as configuration name for this option. | [
"get",
"the",
"name",
"for",
"configuration"
] | 8d01acef8c19d6883873689d017b14857876412d | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/command_decorator.py#L268-L316 |
247,736 | klorenz/python-argdeco | argdeco/command_decorator.py | CommandDecorator.add_command | def add_command(self, command, *args, **kwargs):
"""add a command.
This is basically a wrapper for add_parser()
"""
cmd = self.add_parser(command, *args, **kwargs) | python | def add_command(self, command, *args, **kwargs):
"""add a command.
This is basically a wrapper for add_parser()
"""
cmd = self.add_parser(command, *args, **kwargs) | [
"def",
"add_command",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"self",
".",
"add_parser",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | add a command.
This is basically a wrapper for add_parser() | [
"add",
"a",
"command",
"."
] | 8d01acef8c19d6883873689d017b14857876412d | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/command_decorator.py#L319-L324 |
247,737 | klorenz/python-argdeco | argdeco/command_decorator.py | CommandDecorator.execute | def execute(self, argv=None, compile=None, preprocessor=None, compiler_factory=None):
"""Parse arguments and execute decorated function
argv: list of arguments
compile:
- None, pass args as keyword args to function
- True, pass args as single dictionary
- function, get args from parse_args() and return a pair of
tuple and dict to be passed as args and kwargs to function
"""
action, args, kwargs = self.compile_args(argv=argv, compile=compile, preprocessor=preprocessor, compiler_factory=compiler_factory)
return action(*args, **kwargs) | python | def execute(self, argv=None, compile=None, preprocessor=None, compiler_factory=None):
"""Parse arguments and execute decorated function
argv: list of arguments
compile:
- None, pass args as keyword args to function
- True, pass args as single dictionary
- function, get args from parse_args() and return a pair of
tuple and dict to be passed as args and kwargs to function
"""
action, args, kwargs = self.compile_args(argv=argv, compile=compile, preprocessor=preprocessor, compiler_factory=compiler_factory)
return action(*args, **kwargs) | [
"def",
"execute",
"(",
"self",
",",
"argv",
"=",
"None",
",",
"compile",
"=",
"None",
",",
"preprocessor",
"=",
"None",
",",
"compiler_factory",
"=",
"None",
")",
":",
"action",
",",
"args",
",",
"kwargs",
"=",
"self",
".",
"compile_args",
"(",
"argv",
"=",
"argv",
",",
"compile",
"=",
"compile",
",",
"preprocessor",
"=",
"preprocessor",
",",
"compiler_factory",
"=",
"compiler_factory",
")",
"return",
"action",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Parse arguments and execute decorated function
argv: list of arguments
compile:
- None, pass args as keyword args to function
- True, pass args as single dictionary
- function, get args from parse_args() and return a pair of
tuple and dict to be passed as args and kwargs to function | [
"Parse",
"arguments",
"and",
"execute",
"decorated",
"function"
] | 8d01acef8c19d6883873689d017b14857876412d | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/command_decorator.py#L450-L462 |
247,738 | 20c/twentyc.rpc | twentyc/rpc/client.py | RestClient.update | def update(self, typ, id, **kwargs):
"""
update just fields sent by keyword args
"""
return self._load(self._request(typ, id=id, method='PUT', data=kwargs)) | python | def update(self, typ, id, **kwargs):
"""
update just fields sent by keyword args
"""
return self._load(self._request(typ, id=id, method='PUT', data=kwargs)) | [
"def",
"update",
"(",
"self",
",",
"typ",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_load",
"(",
"self",
".",
"_request",
"(",
"typ",
",",
"id",
"=",
"id",
",",
"method",
"=",
"'PUT'",
",",
"data",
"=",
"kwargs",
")",
")"
] | update just fields sent by keyword args | [
"update",
"just",
"fields",
"sent",
"by",
"keyword",
"args"
] | 23ff07be55eaf21cc2e1a13c2879710b5bc7f933 | https://github.com/20c/twentyc.rpc/blob/23ff07be55eaf21cc2e1a13c2879710b5bc7f933/twentyc/rpc/client.py#L145-L149 |
247,739 | 20c/twentyc.rpc | twentyc/rpc/client.py | RestClient.rm | def rm(self, typ, id):
"""
remove typ by id
"""
return self._load(self._request(typ, id=id, method='DELETE')) | python | def rm(self, typ, id):
"""
remove typ by id
"""
return self._load(self._request(typ, id=id, method='DELETE')) | [
"def",
"rm",
"(",
"self",
",",
"typ",
",",
"id",
")",
":",
"return",
"self",
".",
"_load",
"(",
"self",
".",
"_request",
"(",
"typ",
",",
"id",
"=",
"id",
",",
"method",
"=",
"'DELETE'",
")",
")"
] | remove typ by id | [
"remove",
"typ",
"by",
"id"
] | 23ff07be55eaf21cc2e1a13c2879710b5bc7f933 | https://github.com/20c/twentyc.rpc/blob/23ff07be55eaf21cc2e1a13c2879710b5bc7f933/twentyc/rpc/client.py#L160-L164 |
247,740 | renalreg/cornflake | cornflake/serializers.py | _merge_fields | def _merge_fields(a, b):
"""Merge two lists of fields.
Fields in `b` override fields in `a`. Fields in `a` are output first.
"""
a_names = set(x[0] for x in a)
b_names = set(x[0] for x in b)
a_keep = a_names - b_names
fields = []
for name, field in a:
if name in a_keep:
fields.append((name, field))
fields.extend(b)
return fields | python | def _merge_fields(a, b):
"""Merge two lists of fields.
Fields in `b` override fields in `a`. Fields in `a` are output first.
"""
a_names = set(x[0] for x in a)
b_names = set(x[0] for x in b)
a_keep = a_names - b_names
fields = []
for name, field in a:
if name in a_keep:
fields.append((name, field))
fields.extend(b)
return fields | [
"def",
"_merge_fields",
"(",
"a",
",",
"b",
")",
":",
"a_names",
"=",
"set",
"(",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"a",
")",
"b_names",
"=",
"set",
"(",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"b",
")",
"a_keep",
"=",
"a_names",
"-",
"b_names",
"fields",
"=",
"[",
"]",
"for",
"name",
",",
"field",
"in",
"a",
":",
"if",
"name",
"in",
"a_keep",
":",
"fields",
".",
"append",
"(",
"(",
"name",
",",
"field",
")",
")",
"fields",
".",
"extend",
"(",
"b",
")",
"return",
"fields"
] | Merge two lists of fields.
Fields in `b` override fields in `a`. Fields in `a` are output first. | [
"Merge",
"two",
"lists",
"of",
"fields",
"."
] | ce0c0b260c95e84046f108d05773f1f130ae886c | https://github.com/renalreg/cornflake/blob/ce0c0b260c95e84046f108d05773f1f130ae886c/cornflake/serializers.py#L95-L113 |
247,741 | minhhoit/yacms | yacms/conf/__init__.py | register_setting | def register_setting(name=None, label=None, editable=False, description=None,
default=None, choices=None, append=False,
translatable=False):
"""
Registers a setting that can be edited via the admin. This mostly
equates to storing the given args as a dict in the ``registry``
dict by name.
"""
if name is None:
raise TypeError("yacms.conf.register_setting requires the "
"'name' keyword argument.")
if editable and default is None:
raise TypeError("yacms.conf.register_setting requires the "
"'default' keyword argument when 'editable' is True.")
# append is True when called from an app (typically external)
# after the setting has already been registered, with the
# intention of appending to its default value.
if append and name in registry:
registry[name]["default"] += default
return
# If an editable setting has a value defined in the
# project's settings.py module, it can't be editable, since
# these lead to a lot of confusion once its value gets
# defined in the db.
if hasattr(django_settings, name):
editable = False
if label is None:
label = name.replace("_", " ").title()
# Python 2/3 compatibility. isinstance() is overridden by future
# on Python 2 to behave as Python 3 in conjunction with either
# Python 2's native types or the future.builtins types.
if isinstance(default, bool):
# Prevent bools treated as ints
setting_type = bool
elif isinstance(default, int):
# An int or long or subclass on Py2
setting_type = int
elif isinstance(default, (str, Promise)):
# A unicode or subclass on Py2
setting_type = str
elif isinstance(default, bytes):
# A byte-string or subclass on Py2
setting_type = bytes
else:
setting_type = type(default)
registry[name] = {"name": name, "label": label, "editable": editable,
"description": description, "default": default,
"choices": choices, "type": setting_type,
"translatable": translatable} | python | def register_setting(name=None, label=None, editable=False, description=None,
default=None, choices=None, append=False,
translatable=False):
"""
Registers a setting that can be edited via the admin. This mostly
equates to storing the given args as a dict in the ``registry``
dict by name.
"""
if name is None:
raise TypeError("yacms.conf.register_setting requires the "
"'name' keyword argument.")
if editable and default is None:
raise TypeError("yacms.conf.register_setting requires the "
"'default' keyword argument when 'editable' is True.")
# append is True when called from an app (typically external)
# after the setting has already been registered, with the
# intention of appending to its default value.
if append and name in registry:
registry[name]["default"] += default
return
# If an editable setting has a value defined in the
# project's settings.py module, it can't be editable, since
# these lead to a lot of confusion once its value gets
# defined in the db.
if hasattr(django_settings, name):
editable = False
if label is None:
label = name.replace("_", " ").title()
# Python 2/3 compatibility. isinstance() is overridden by future
# on Python 2 to behave as Python 3 in conjunction with either
# Python 2's native types or the future.builtins types.
if isinstance(default, bool):
# Prevent bools treated as ints
setting_type = bool
elif isinstance(default, int):
# An int or long or subclass on Py2
setting_type = int
elif isinstance(default, (str, Promise)):
# A unicode or subclass on Py2
setting_type = str
elif isinstance(default, bytes):
# A byte-string or subclass on Py2
setting_type = bytes
else:
setting_type = type(default)
registry[name] = {"name": name, "label": label, "editable": editable,
"description": description, "default": default,
"choices": choices, "type": setting_type,
"translatable": translatable} | [
"def",
"register_setting",
"(",
"name",
"=",
"None",
",",
"label",
"=",
"None",
",",
"editable",
"=",
"False",
",",
"description",
"=",
"None",
",",
"default",
"=",
"None",
",",
"choices",
"=",
"None",
",",
"append",
"=",
"False",
",",
"translatable",
"=",
"False",
")",
":",
"if",
"name",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"yacms.conf.register_setting requires the \"",
"\"'name' keyword argument.\"",
")",
"if",
"editable",
"and",
"default",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"yacms.conf.register_setting requires the \"",
"\"'default' keyword argument when 'editable' is True.\"",
")",
"# append is True when called from an app (typically external)",
"# after the setting has already been registered, with the",
"# intention of appending to its default value.",
"if",
"append",
"and",
"name",
"in",
"registry",
":",
"registry",
"[",
"name",
"]",
"[",
"\"default\"",
"]",
"+=",
"default",
"return",
"# If an editable setting has a value defined in the",
"# project's settings.py module, it can't be editable, since",
"# these lead to a lot of confusion once its value gets",
"# defined in the db.",
"if",
"hasattr",
"(",
"django_settings",
",",
"name",
")",
":",
"editable",
"=",
"False",
"if",
"label",
"is",
"None",
":",
"label",
"=",
"name",
".",
"replace",
"(",
"\"_\"",
",",
"\" \"",
")",
".",
"title",
"(",
")",
"# Python 2/3 compatibility. isinstance() is overridden by future",
"# on Python 2 to behave as Python 3 in conjunction with either",
"# Python 2's native types or the future.builtins types.",
"if",
"isinstance",
"(",
"default",
",",
"bool",
")",
":",
"# Prevent bools treated as ints",
"setting_type",
"=",
"bool",
"elif",
"isinstance",
"(",
"default",
",",
"int",
")",
":",
"# An int or long or subclass on Py2",
"setting_type",
"=",
"int",
"elif",
"isinstance",
"(",
"default",
",",
"(",
"str",
",",
"Promise",
")",
")",
":",
"# A unicode or subclass on Py2",
"setting_type",
"=",
"str",
"elif",
"isinstance",
"(",
"default",
",",
"bytes",
")",
":",
"# A byte-string or subclass on Py2",
"setting_type",
"=",
"bytes",
"else",
":",
"setting_type",
"=",
"type",
"(",
"default",
")",
"registry",
"[",
"name",
"]",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"label\"",
":",
"label",
",",
"\"editable\"",
":",
"editable",
",",
"\"description\"",
":",
"description",
",",
"\"default\"",
":",
"default",
",",
"\"choices\"",
":",
"choices",
",",
"\"type\"",
":",
"setting_type",
",",
"\"translatable\"",
":",
"translatable",
"}"
] | Registers a setting that can be edited via the admin. This mostly
equates to storing the given args as a dict in the ``registry``
dict by name. | [
"Registers",
"a",
"setting",
"that",
"can",
"be",
"edited",
"via",
"the",
"admin",
".",
"This",
"mostly",
"equates",
"to",
"storing",
"the",
"given",
"args",
"as",
"a",
"dict",
"in",
"the",
"registry",
"dict",
"by",
"name",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/__init__.py#L25-L76 |
247,742 | minhhoit/yacms | yacms/conf/__init__.py | Settings._get_editable | def _get_editable(self, request):
"""
Get the dictionary of editable settings for a given request. Settings
are fetched from the database once per request and then stored in
``_editable_caches``, a WeakKeyDictionary that will automatically
discard each entry when no more references to the request exist.
"""
try:
editable_settings = self._editable_caches[request]
except KeyError:
editable_settings = self._editable_caches[request] = self._load()
return editable_settings | python | def _get_editable(self, request):
"""
Get the dictionary of editable settings for a given request. Settings
are fetched from the database once per request and then stored in
``_editable_caches``, a WeakKeyDictionary that will automatically
discard each entry when no more references to the request exist.
"""
try:
editable_settings = self._editable_caches[request]
except KeyError:
editable_settings = self._editable_caches[request] = self._load()
return editable_settings | [
"def",
"_get_editable",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"editable_settings",
"=",
"self",
".",
"_editable_caches",
"[",
"request",
"]",
"except",
"KeyError",
":",
"editable_settings",
"=",
"self",
".",
"_editable_caches",
"[",
"request",
"]",
"=",
"self",
".",
"_load",
"(",
")",
"return",
"editable_settings"
] | Get the dictionary of editable settings for a given request. Settings
are fetched from the database once per request and then stored in
``_editable_caches``, a WeakKeyDictionary that will automatically
discard each entry when no more references to the request exist. | [
"Get",
"the",
"dictionary",
"of",
"editable",
"settings",
"for",
"a",
"given",
"request",
".",
"Settings",
"are",
"fetched",
"from",
"the",
"database",
"once",
"per",
"request",
"and",
"then",
"stored",
"in",
"_editable_caches",
"a",
"WeakKeyDictionary",
"that",
"will",
"automatically",
"discard",
"each",
"entry",
"when",
"no",
"more",
"references",
"to",
"the",
"request",
"exist",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/__init__.py#L142-L153 |
247,743 | minhhoit/yacms | yacms/conf/__init__.py | Settings._load | def _load(self):
"""
Load editable settings from the database and return them as a dict.
Delete any settings from the database that are no longer registered,
and emit a warning if there are settings that are defined in both
settings.py and the database.
"""
from yacms.conf.models import Setting
removed_settings = []
conflicting_settings = []
new_cache = {}
for setting_obj in Setting.objects.all():
# Check that the Setting object corresponds to a setting that has
# been declared in code using ``register_setting()``. If not, add
# it to a list of items to be deleted from the database later.
try:
setting = registry[setting_obj.name]
except KeyError:
removed_settings.append(setting_obj.name)
continue
# Convert a string from the database to the correct Python type.
setting_value = self._to_python(setting, setting_obj.value)
# If a setting is defined both in the database and in settings.py,
# raise a warning and use the value defined in settings.py.
if hasattr(django_settings, setting["name"]):
if setting_value != setting["default"]:
conflicting_settings.append(setting_obj.name)
continue
# If nothing went wrong, use the value from the database!
new_cache[setting["name"]] = setting_value
if removed_settings:
Setting.objects.filter(name__in=removed_settings).delete()
if conflicting_settings:
warn("These settings are defined in both settings.py and "
"the database: %s. The settings.py values will be used."
% ", ".join(conflicting_settings))
return new_cache | python | def _load(self):
"""
Load editable settings from the database and return them as a dict.
Delete any settings from the database that are no longer registered,
and emit a warning if there are settings that are defined in both
settings.py and the database.
"""
from yacms.conf.models import Setting
removed_settings = []
conflicting_settings = []
new_cache = {}
for setting_obj in Setting.objects.all():
# Check that the Setting object corresponds to a setting that has
# been declared in code using ``register_setting()``. If not, add
# it to a list of items to be deleted from the database later.
try:
setting = registry[setting_obj.name]
except KeyError:
removed_settings.append(setting_obj.name)
continue
# Convert a string from the database to the correct Python type.
setting_value = self._to_python(setting, setting_obj.value)
# If a setting is defined both in the database and in settings.py,
# raise a warning and use the value defined in settings.py.
if hasattr(django_settings, setting["name"]):
if setting_value != setting["default"]:
conflicting_settings.append(setting_obj.name)
continue
# If nothing went wrong, use the value from the database!
new_cache[setting["name"]] = setting_value
if removed_settings:
Setting.objects.filter(name__in=removed_settings).delete()
if conflicting_settings:
warn("These settings are defined in both settings.py and "
"the database: %s. The settings.py values will be used."
% ", ".join(conflicting_settings))
return new_cache | [
"def",
"_load",
"(",
"self",
")",
":",
"from",
"yacms",
".",
"conf",
".",
"models",
"import",
"Setting",
"removed_settings",
"=",
"[",
"]",
"conflicting_settings",
"=",
"[",
"]",
"new_cache",
"=",
"{",
"}",
"for",
"setting_obj",
"in",
"Setting",
".",
"objects",
".",
"all",
"(",
")",
":",
"# Check that the Setting object corresponds to a setting that has",
"# been declared in code using ``register_setting()``. If not, add",
"# it to a list of items to be deleted from the database later.",
"try",
":",
"setting",
"=",
"registry",
"[",
"setting_obj",
".",
"name",
"]",
"except",
"KeyError",
":",
"removed_settings",
".",
"append",
"(",
"setting_obj",
".",
"name",
")",
"continue",
"# Convert a string from the database to the correct Python type.",
"setting_value",
"=",
"self",
".",
"_to_python",
"(",
"setting",
",",
"setting_obj",
".",
"value",
")",
"# If a setting is defined both in the database and in settings.py,",
"# raise a warning and use the value defined in settings.py.",
"if",
"hasattr",
"(",
"django_settings",
",",
"setting",
"[",
"\"name\"",
"]",
")",
":",
"if",
"setting_value",
"!=",
"setting",
"[",
"\"default\"",
"]",
":",
"conflicting_settings",
".",
"append",
"(",
"setting_obj",
".",
"name",
")",
"continue",
"# If nothing went wrong, use the value from the database!",
"new_cache",
"[",
"setting",
"[",
"\"name\"",
"]",
"]",
"=",
"setting_value",
"if",
"removed_settings",
":",
"Setting",
".",
"objects",
".",
"filter",
"(",
"name__in",
"=",
"removed_settings",
")",
".",
"delete",
"(",
")",
"if",
"conflicting_settings",
":",
"warn",
"(",
"\"These settings are defined in both settings.py and \"",
"\"the database: %s. The settings.py values will be used.\"",
"%",
"\", \"",
".",
"join",
"(",
"conflicting_settings",
")",
")",
"return",
"new_cache"
] | Load editable settings from the database and return them as a dict.
Delete any settings from the database that are no longer registered,
and emit a warning if there are settings that are defined in both
settings.py and the database. | [
"Load",
"editable",
"settings",
"from",
"the",
"database",
"and",
"return",
"them",
"as",
"a",
"dict",
".",
"Delete",
"any",
"settings",
"from",
"the",
"database",
"that",
"are",
"no",
"longer",
"registered",
"and",
"emit",
"a",
"warning",
"if",
"there",
"are",
"settings",
"that",
"are",
"defined",
"in",
"both",
"settings",
".",
"py",
"and",
"the",
"database",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/__init__.py#L178-L223 |
247,744 | yougov/vr.runners | vr/runners/base.py | ensure_file | def ensure_file(url, path, md5sum=None):
"""
If file is not already at 'path', then download from 'url' and put it
there.
If md5sum is provided, and 'path' exists, check that file matches the
md5sum. If not, re-download.
"""
if not os.path.isfile(path) or (md5sum and md5sum != file_md5(path)):
download_file(url, path) | python | def ensure_file(url, path, md5sum=None):
"""
If file is not already at 'path', then download from 'url' and put it
there.
If md5sum is provided, and 'path' exists, check that file matches the
md5sum. If not, re-download.
"""
if not os.path.isfile(path) or (md5sum and md5sum != file_md5(path)):
download_file(url, path) | [
"def",
"ensure_file",
"(",
"url",
",",
"path",
",",
"md5sum",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"or",
"(",
"md5sum",
"and",
"md5sum",
"!=",
"file_md5",
"(",
"path",
")",
")",
":",
"download_file",
"(",
"url",
",",
"path",
")"
] | If file is not already at 'path', then download from 'url' and put it
there.
If md5sum is provided, and 'path' exists, check that file matches the
md5sum. If not, re-download. | [
"If",
"file",
"is",
"not",
"already",
"at",
"path",
"then",
"download",
"from",
"url",
"and",
"put",
"it",
"there",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/base.py#L427-L437 |
247,745 | yougov/vr.runners | vr/runners/base.py | BaseRunner.write_proc_sh | def write_proc_sh(self):
"""
Write the script that is the first thing called inside the
container. It sets env vars and then calls the real program.
"""
print("Writing proc.sh")
context = {
'tmp': '/tmp',
'home': '/app',
'settings': '/settings.yaml',
'envsh': '/env.sh',
'port': self.config.port,
'cmd': self.get_cmd(),
}
sh_path = os.path.join(get_container_path(self.config), 'proc.sh')
rendered = get_template('proc.sh') % context
with open(sh_path, 'w') as f:
f.write(rendered)
st = os.stat(sh_path)
os.chmod(
sh_path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | python | def write_proc_sh(self):
"""
Write the script that is the first thing called inside the
container. It sets env vars and then calls the real program.
"""
print("Writing proc.sh")
context = {
'tmp': '/tmp',
'home': '/app',
'settings': '/settings.yaml',
'envsh': '/env.sh',
'port': self.config.port,
'cmd': self.get_cmd(),
}
sh_path = os.path.join(get_container_path(self.config), 'proc.sh')
rendered = get_template('proc.sh') % context
with open(sh_path, 'w') as f:
f.write(rendered)
st = os.stat(sh_path)
os.chmod(
sh_path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | [
"def",
"write_proc_sh",
"(",
"self",
")",
":",
"print",
"(",
"\"Writing proc.sh\"",
")",
"context",
"=",
"{",
"'tmp'",
":",
"'/tmp'",
",",
"'home'",
":",
"'/app'",
",",
"'settings'",
":",
"'/settings.yaml'",
",",
"'envsh'",
":",
"'/env.sh'",
",",
"'port'",
":",
"self",
".",
"config",
".",
"port",
",",
"'cmd'",
":",
"self",
".",
"get_cmd",
"(",
")",
",",
"}",
"sh_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_container_path",
"(",
"self",
".",
"config",
")",
",",
"'proc.sh'",
")",
"rendered",
"=",
"get_template",
"(",
"'proc.sh'",
")",
"%",
"context",
"with",
"open",
"(",
"sh_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"rendered",
")",
"st",
"=",
"os",
".",
"stat",
"(",
"sh_path",
")",
"os",
".",
"chmod",
"(",
"sh_path",
",",
"st",
".",
"st_mode",
"|",
"stat",
".",
"S_IXUSR",
"|",
"stat",
".",
"S_IXGRP",
"|",
"stat",
".",
"S_IXOTH",
")"
] | Write the script that is the first thing called inside the
container. It sets env vars and then calls the real program. | [
"Write",
"the",
"script",
"that",
"is",
"the",
"first",
"thing",
"called",
"inside",
"the",
"container",
".",
"It",
"sets",
"env",
"vars",
"and",
"then",
"calls",
"the",
"real",
"program",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/base.py#L107-L127 |
247,746 | yougov/vr.runners | vr/runners/base.py | BaseRunner.get_cmd | def get_cmd(self):
"""
If self.config.cmd is not None, return that.
Otherwise, read the Procfile inside the build code, parse it
(as yaml), and pull out the command for self.config.proc_name.
"""
if self.config.cmd is not None:
return self.config.cmd
procfile_path = os.path.join(get_app_path(self.config), 'Procfile')
with open(procfile_path, 'r') as f:
procs = yaml.safe_load(f)
return procs[self.config.proc_name] | python | def get_cmd(self):
"""
If self.config.cmd is not None, return that.
Otherwise, read the Procfile inside the build code, parse it
(as yaml), and pull out the command for self.config.proc_name.
"""
if self.config.cmd is not None:
return self.config.cmd
procfile_path = os.path.join(get_app_path(self.config), 'Procfile')
with open(procfile_path, 'r') as f:
procs = yaml.safe_load(f)
return procs[self.config.proc_name] | [
"def",
"get_cmd",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
".",
"cmd",
"is",
"not",
"None",
":",
"return",
"self",
".",
"config",
".",
"cmd",
"procfile_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_app_path",
"(",
"self",
".",
"config",
")",
",",
"'Procfile'",
")",
"with",
"open",
"(",
"procfile_path",
",",
"'r'",
")",
"as",
"f",
":",
"procs",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"return",
"procs",
"[",
"self",
".",
"config",
".",
"proc_name",
"]"
] | If self.config.cmd is not None, return that.
Otherwise, read the Procfile inside the build code, parse it
(as yaml), and pull out the command for self.config.proc_name. | [
"If",
"self",
".",
"config",
".",
"cmd",
"is",
"not",
"None",
"return",
"that",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/base.py#L147-L160 |
247,747 | yougov/vr.runners | vr/runners/base.py | BaseRunner.ensure_container | def ensure_container(self, name=None):
"""Make sure container exists. It's only needed on newer
versions of LXC."""
if get_lxc_version() < pkg_resources.parse_version('2.0.0'):
# Nothing to do for old versions of LXC
return
if name is None:
name = self.container_name
args = [
'lxc-create',
'--name', name,
'--template', 'none',
'>', '/dev/null', '2>&1',
]
os.system(' '.join(args)) | python | def ensure_container(self, name=None):
"""Make sure container exists. It's only needed on newer
versions of LXC."""
if get_lxc_version() < pkg_resources.parse_version('2.0.0'):
# Nothing to do for old versions of LXC
return
if name is None:
name = self.container_name
args = [
'lxc-create',
'--name', name,
'--template', 'none',
'>', '/dev/null', '2>&1',
]
os.system(' '.join(args)) | [
"def",
"ensure_container",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"get_lxc_version",
"(",
")",
"<",
"pkg_resources",
".",
"parse_version",
"(",
"'2.0.0'",
")",
":",
"# Nothing to do for old versions of LXC",
"return",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"container_name",
"args",
"=",
"[",
"'lxc-create'",
",",
"'--name'",
",",
"name",
",",
"'--template'",
",",
"'none'",
",",
"'>'",
",",
"'/dev/null'",
",",
"'2>&1'",
",",
"]",
"os",
".",
"system",
"(",
"' '",
".",
"join",
"(",
"args",
")",
")"
] | Make sure container exists. It's only needed on newer
versions of LXC. | [
"Make",
"sure",
"container",
"exists",
".",
"It",
"s",
"only",
"needed",
"on",
"newer",
"versions",
"of",
"LXC",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/base.py#L162-L178 |
247,748 | yougov/vr.runners | vr/runners/base.py | BaseRunner.ensure_build | def ensure_build(self):
"""
If self.config.build_url is set, ensure it's been downloaded to the
builds folder.
"""
if self.config.build_url:
path = get_buildfile_path(self.config)
# Ensure that builds_root has been created.
mkdir(BUILDS_ROOT)
build_md5 = getattr(self.config, 'build_md5', None)
ensure_file(self.config.build_url, path, build_md5)
# Now untar.
self.untar() | python | def ensure_build(self):
"""
If self.config.build_url is set, ensure it's been downloaded to the
builds folder.
"""
if self.config.build_url:
path = get_buildfile_path(self.config)
# Ensure that builds_root has been created.
mkdir(BUILDS_ROOT)
build_md5 = getattr(self.config, 'build_md5', None)
ensure_file(self.config.build_url, path, build_md5)
# Now untar.
self.untar() | [
"def",
"ensure_build",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
".",
"build_url",
":",
"path",
"=",
"get_buildfile_path",
"(",
"self",
".",
"config",
")",
"# Ensure that builds_root has been created.",
"mkdir",
"(",
"BUILDS_ROOT",
")",
"build_md5",
"=",
"getattr",
"(",
"self",
".",
"config",
",",
"'build_md5'",
",",
"None",
")",
"ensure_file",
"(",
"self",
".",
"config",
".",
"build_url",
",",
"path",
",",
"build_md5",
")",
"# Now untar.",
"self",
".",
"untar",
"(",
")"
] | If self.config.build_url is set, ensure it's been downloaded to the
builds folder. | [
"If",
"self",
".",
"config",
".",
"build_url",
"is",
"set",
"ensure",
"it",
"s",
"been",
"downloaded",
"to",
"the",
"builds",
"folder",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/base.py#L180-L194 |
247,749 | yougov/vr.runners | vr/runners/base.py | BaseRunner.teardown | def teardown(self):
"""
Delete the proc path where everything has been put.
The build will be cleaned up elsewhere.
"""
proc_path = get_proc_path(self.config)
if os.path.isdir(proc_path):
shutil.rmtree(proc_path) | python | def teardown(self):
"""
Delete the proc path where everything has been put.
The build will be cleaned up elsewhere.
"""
proc_path = get_proc_path(self.config)
if os.path.isdir(proc_path):
shutil.rmtree(proc_path) | [
"def",
"teardown",
"(",
"self",
")",
":",
"proc_path",
"=",
"get_proc_path",
"(",
"self",
".",
"config",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"proc_path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"proc_path",
")"
] | Delete the proc path where everything has been put.
The build will be cleaned up elsewhere. | [
"Delete",
"the",
"proc",
"path",
"where",
"everything",
"has",
"been",
"put",
".",
"The",
"build",
"will",
"be",
"cleaned",
"up",
"elsewhere",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/base.py#L305-L312 |
247,750 | miquelo/resort | packages/resort/engine/execution.py | Context.resolve | def resolve(self, value):
"""
Resolve contextual value.
:param value:
Contextual value.
:return:
If value is a function with a single parameter, which is a read-only
dictionary, the return value of the function called with context
properties as its parameter. If not, the value itself.
"""
if isinstance(value, collections.Callable):
return value({
"base_dir": self.__base_dir,
"profile_dir": self.__prof_dir,
"profile_name": self.__prof_name
})
return value | python | def resolve(self, value):
"""
Resolve contextual value.
:param value:
Contextual value.
:return:
If value is a function with a single parameter, which is a read-only
dictionary, the return value of the function called with context
properties as its parameter. If not, the value itself.
"""
if isinstance(value, collections.Callable):
return value({
"base_dir": self.__base_dir,
"profile_dir": self.__prof_dir,
"profile_name": self.__prof_name
})
return value | [
"def",
"resolve",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Callable",
")",
":",
"return",
"value",
"(",
"{",
"\"base_dir\"",
":",
"self",
".",
"__base_dir",
",",
"\"profile_dir\"",
":",
"self",
".",
"__prof_dir",
",",
"\"profile_name\"",
":",
"self",
".",
"__prof_name",
"}",
")",
"return",
"value"
] | Resolve contextual value.
:param value:
Contextual value.
:return:
If value is a function with a single parameter, which is a read-only
dictionary, the return value of the function called with context
properties as its parameter. If not, the value itself. | [
"Resolve",
"contextual",
"value",
"."
] | 097a25d3257c91a75c194fd44c2797ab356f85dd | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/engine/execution.py#L43-L62 |
247,751 | townsenddw/jhubctl | jhubctl/hubs/hubs.py | HubList.get | def get(self, name=None):
"""Print a list of all jupyterHubs."""
# Print a list of hubs.
if name is None:
hubs = self.get_hubs()
print("Running Jupyterhub Deployments (by name):")
for hub_name in hubs:
hub = Hub(namespace=hub_name)
data = hub.get_description()
url = data['LoadBalancer Ingress']
print(f' - Name: {hub_name}')
print(f' Url: {url}')
else:
hub = Hub(namespace=name)
hub.get() | python | def get(self, name=None):
"""Print a list of all jupyterHubs."""
# Print a list of hubs.
if name is None:
hubs = self.get_hubs()
print("Running Jupyterhub Deployments (by name):")
for hub_name in hubs:
hub = Hub(namespace=hub_name)
data = hub.get_description()
url = data['LoadBalancer Ingress']
print(f' - Name: {hub_name}')
print(f' Url: {url}')
else:
hub = Hub(namespace=name)
hub.get() | [
"def",
"get",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"# Print a list of hubs.",
"if",
"name",
"is",
"None",
":",
"hubs",
"=",
"self",
".",
"get_hubs",
"(",
")",
"print",
"(",
"\"Running Jupyterhub Deployments (by name):\"",
")",
"for",
"hub_name",
"in",
"hubs",
":",
"hub",
"=",
"Hub",
"(",
"namespace",
"=",
"hub_name",
")",
"data",
"=",
"hub",
".",
"get_description",
"(",
")",
"url",
"=",
"data",
"[",
"'LoadBalancer Ingress'",
"]",
"print",
"(",
"f' - Name: {hub_name}'",
")",
"print",
"(",
"f' Url: {url}'",
")",
"else",
":",
"hub",
"=",
"Hub",
"(",
"namespace",
"=",
"name",
")",
"hub",
".",
"get",
"(",
")"
] | Print a list of all jupyterHubs. | [
"Print",
"a",
"list",
"of",
"all",
"jupyterHubs",
"."
] | c8c20f86a16e9d01dd90e4607d81423417cc773b | https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/hubs/hubs.py#L43-L57 |
247,752 | pjuren/pyokit | src/pyokit/scripts/regionCollapse.py | main | def main(args, prog_name):
"""
main entry point for the script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
list.
"""
# get options and arguments
ui = getUI(args, prog_name)
if ui.optionIsSet("test"):
# just run unit tests
unittest.main(argv=[sys.argv[0]])
elif ui.optionIsSet("help"):
# just show help
ui.usage()
else:
verbose = (ui.optionIsSet("verbose") is True) or DEFAULT_VERBOSITY
# how to handle strand, names, and whether to collapse only regions with
# exactly matching genomic loci?
stranded = ui.optionIsSet("stranded")
names = ui.optionIsSet("accumulate_names")
exact = ui.optionIsSet("exact")
# get output handle
out_fh = sys.stdout
if ui.optionIsSet("output"):
out_fh = open(ui.getValue("output"), "w")
# get input file-handle
in_fh = sys.stdin
if ui.hasArgument(0):
in_fh = open(ui.getArgument(0))
# load data -- TODO at the moment we load everying; need to think about
# whether it is possible to do this using a single pass of the data, but not
# loading it all first.
regions = [x for x in BEDIterator(in_fh, verbose)]
if exact:
collapse_exact(regions, stranded, names, out_fh)
else:
for x in collapseRegions(regions, stranded, names, verbose):
out_fh.write(str(x) + "\n") | python | def main(args, prog_name):
"""
main entry point for the script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
list.
"""
# get options and arguments
ui = getUI(args, prog_name)
if ui.optionIsSet("test"):
# just run unit tests
unittest.main(argv=[sys.argv[0]])
elif ui.optionIsSet("help"):
# just show help
ui.usage()
else:
verbose = (ui.optionIsSet("verbose") is True) or DEFAULT_VERBOSITY
# how to handle strand, names, and whether to collapse only regions with
# exactly matching genomic loci?
stranded = ui.optionIsSet("stranded")
names = ui.optionIsSet("accumulate_names")
exact = ui.optionIsSet("exact")
# get output handle
out_fh = sys.stdout
if ui.optionIsSet("output"):
out_fh = open(ui.getValue("output"), "w")
# get input file-handle
in_fh = sys.stdin
if ui.hasArgument(0):
in_fh = open(ui.getArgument(0))
# load data -- TODO at the moment we load everying; need to think about
# whether it is possible to do this using a single pass of the data, but not
# loading it all first.
regions = [x for x in BEDIterator(in_fh, verbose)]
if exact:
collapse_exact(regions, stranded, names, out_fh)
else:
for x in collapseRegions(regions, stranded, names, verbose):
out_fh.write(str(x) + "\n") | [
"def",
"main",
"(",
"args",
",",
"prog_name",
")",
":",
"# get options and arguments",
"ui",
"=",
"getUI",
"(",
"args",
",",
"prog_name",
")",
"if",
"ui",
".",
"optionIsSet",
"(",
"\"test\"",
")",
":",
"# just run unit tests",
"unittest",
".",
"main",
"(",
"argv",
"=",
"[",
"sys",
".",
"argv",
"[",
"0",
"]",
"]",
")",
"elif",
"ui",
".",
"optionIsSet",
"(",
"\"help\"",
")",
":",
"# just show help",
"ui",
".",
"usage",
"(",
")",
"else",
":",
"verbose",
"=",
"(",
"ui",
".",
"optionIsSet",
"(",
"\"verbose\"",
")",
"is",
"True",
")",
"or",
"DEFAULT_VERBOSITY",
"# how to handle strand, names, and whether to collapse only regions with",
"# exactly matching genomic loci?",
"stranded",
"=",
"ui",
".",
"optionIsSet",
"(",
"\"stranded\"",
")",
"names",
"=",
"ui",
".",
"optionIsSet",
"(",
"\"accumulate_names\"",
")",
"exact",
"=",
"ui",
".",
"optionIsSet",
"(",
"\"exact\"",
")",
"# get output handle",
"out_fh",
"=",
"sys",
".",
"stdout",
"if",
"ui",
".",
"optionIsSet",
"(",
"\"output\"",
")",
":",
"out_fh",
"=",
"open",
"(",
"ui",
".",
"getValue",
"(",
"\"output\"",
")",
",",
"\"w\"",
")",
"# get input file-handle",
"in_fh",
"=",
"sys",
".",
"stdin",
"if",
"ui",
".",
"hasArgument",
"(",
"0",
")",
":",
"in_fh",
"=",
"open",
"(",
"ui",
".",
"getArgument",
"(",
"0",
")",
")",
"# load data -- TODO at the moment we load everying; need to think about",
"# whether it is possible to do this using a single pass of the data, but not",
"# loading it all first.",
"regions",
"=",
"[",
"x",
"for",
"x",
"in",
"BEDIterator",
"(",
"in_fh",
",",
"verbose",
")",
"]",
"if",
"exact",
":",
"collapse_exact",
"(",
"regions",
",",
"stranded",
",",
"names",
",",
"out_fh",
")",
"else",
":",
"for",
"x",
"in",
"collapseRegions",
"(",
"regions",
",",
"stranded",
",",
"names",
",",
"verbose",
")",
":",
"out_fh",
".",
"write",
"(",
"str",
"(",
"x",
")",
"+",
"\"\\n\"",
")"
] | main entry point for the script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
list. | [
"main",
"entry",
"point",
"for",
"the",
"script",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/regionCollapse.py#L101-L147 |
247,753 | arindampradhan/cheesy | cheesy/ch.py | _pull_all | def _pull_all(command):
"""Website scraper for the info from table content"""
page = requests.get(BASE_URL,verify=False)
soup = BeautifulSoup(page.text,"lxml")
table = soup.find('table',{'class':'list'})
rows = table.findAll("tr")
rows = rows[1:-1]
l = []
name_max = 0
for row in rows:
elements = row.findAll('td')
date = elements[0].string
name = elements[1].string
n = _ascii_checker(name)
version = n.split(' ')[1]
name = n.split(' ')[0]
if name_max < len(name):
name_max = len(name)
link = elements[1].find('a')['href']
link = urlparse.urljoin(BASE_URL,link)
desc = elements[2].string
li = (name,desc,link,date,version)
l.append(li)
print u"\n\033[1m\033[1m\033[4m PACKAGES \033[0m\n"
if command == 'ls':
for li in l:
print u"\033[1m \u25E6 %s \033[0m \033[93m%s \033[0m"%(li[0],li[4])
if command == 'list':
for li in l:
name = li[0] + "".join(" " for i in range(name_max-len(li[0])))
desc = li[1]
if len(li[1]) > 56:
desc = desc[:56] + " .."
print u"\033[1m \u25D8 %s \033[0m \033[93m%s \033[0m"%(name,desc) | python | def _pull_all(command):
"""Website scraper for the info from table content"""
page = requests.get(BASE_URL,verify=False)
soup = BeautifulSoup(page.text,"lxml")
table = soup.find('table',{'class':'list'})
rows = table.findAll("tr")
rows = rows[1:-1]
l = []
name_max = 0
for row in rows:
elements = row.findAll('td')
date = elements[0].string
name = elements[1].string
n = _ascii_checker(name)
version = n.split(' ')[1]
name = n.split(' ')[0]
if name_max < len(name):
name_max = len(name)
link = elements[1].find('a')['href']
link = urlparse.urljoin(BASE_URL,link)
desc = elements[2].string
li = (name,desc,link,date,version)
l.append(li)
print u"\n\033[1m\033[1m\033[4m PACKAGES \033[0m\n"
if command == 'ls':
for li in l:
print u"\033[1m \u25E6 %s \033[0m \033[93m%s \033[0m"%(li[0],li[4])
if command == 'list':
for li in l:
name = li[0] + "".join(" " for i in range(name_max-len(li[0])))
desc = li[1]
if len(li[1]) > 56:
desc = desc[:56] + " .."
print u"\033[1m \u25D8 %s \033[0m \033[93m%s \033[0m"%(name,desc) | [
"def",
"_pull_all",
"(",
"command",
")",
":",
"page",
"=",
"requests",
".",
"get",
"(",
"BASE_URL",
",",
"verify",
"=",
"False",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"page",
".",
"text",
",",
"\"lxml\"",
")",
"table",
"=",
"soup",
".",
"find",
"(",
"'table'",
",",
"{",
"'class'",
":",
"'list'",
"}",
")",
"rows",
"=",
"table",
".",
"findAll",
"(",
"\"tr\"",
")",
"rows",
"=",
"rows",
"[",
"1",
":",
"-",
"1",
"]",
"l",
"=",
"[",
"]",
"name_max",
"=",
"0",
"for",
"row",
"in",
"rows",
":",
"elements",
"=",
"row",
".",
"findAll",
"(",
"'td'",
")",
"date",
"=",
"elements",
"[",
"0",
"]",
".",
"string",
"name",
"=",
"elements",
"[",
"1",
"]",
".",
"string",
"n",
"=",
"_ascii_checker",
"(",
"name",
")",
"version",
"=",
"n",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
"name",
"=",
"n",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"if",
"name_max",
"<",
"len",
"(",
"name",
")",
":",
"name_max",
"=",
"len",
"(",
"name",
")",
"link",
"=",
"elements",
"[",
"1",
"]",
".",
"find",
"(",
"'a'",
")",
"[",
"'href'",
"]",
"link",
"=",
"urlparse",
".",
"urljoin",
"(",
"BASE_URL",
",",
"link",
")",
"desc",
"=",
"elements",
"[",
"2",
"]",
".",
"string",
"li",
"=",
"(",
"name",
",",
"desc",
",",
"link",
",",
"date",
",",
"version",
")",
"l",
".",
"append",
"(",
"li",
")",
"print",
"u\"\\n\\033[1m\\033[1m\\033[4m PACKAGES \\033[0m\\n\"",
"if",
"command",
"==",
"'ls'",
":",
"for",
"li",
"in",
"l",
":",
"print",
"u\"\\033[1m \\u25E6 %s \\033[0m \\033[93m%s \\033[0m\"",
"%",
"(",
"li",
"[",
"0",
"]",
",",
"li",
"[",
"4",
"]",
")",
"if",
"command",
"==",
"'list'",
":",
"for",
"li",
"in",
"l",
":",
"name",
"=",
"li",
"[",
"0",
"]",
"+",
"\"\"",
".",
"join",
"(",
"\" \"",
"for",
"i",
"in",
"range",
"(",
"name_max",
"-",
"len",
"(",
"li",
"[",
"0",
"]",
")",
")",
")",
"desc",
"=",
"li",
"[",
"1",
"]",
"if",
"len",
"(",
"li",
"[",
"1",
"]",
")",
">",
"56",
":",
"desc",
"=",
"desc",
"[",
":",
"56",
"]",
"+",
"\" ..\"",
"print",
"u\"\\033[1m \\u25D8 %s \\033[0m \\033[93m%s \\033[0m\"",
"%",
"(",
"name",
",",
"desc",
")"
] | Website scraper for the info from table content | [
"Website",
"scraper",
"for",
"the",
"info",
"from",
"table",
"content"
] | a7dbc90bba551a562644b1563c595d4ac38f15ed | https://github.com/arindampradhan/cheesy/blob/a7dbc90bba551a562644b1563c595d4ac38f15ed/cheesy/ch.py#L43-L78 |
247,754 | arindampradhan/cheesy | cheesy/ch.py | _release_info | def _release_info(jsn,VERSION):
"""Gives information about a particular package version."""
try:
release_point = jsn['releases'][VERSION][0]
except KeyError:
print "\033[91m\033[1mError: Release not found."
exit(1)
python_version = release_point['python_version']
filename = release_point['filename']
md5 = release_point['md5_digest']
download_url_for_release = release_point['url']
download_num_for_release = release_point['downloads']
download_size_for_release = _sizeof_fmt(int(release_point['size']))
print """
\033[1m\033[1m \033[4mPACKAGE VERSION INFO\033[0m
\033[1m md5 :\033[0m \033[93m%s \033[0m
\033[1m python version :\033[0m \033[93m%s \033[0m
\033[1m download url :\033[0m \033[93m%s \033[0m
\033[1m download number :\033[0m \033[93m%s \033[0m
\033[1m size :\033[0m \033[93m%s \033[0m
\033[1m filename :\033[0m \033[93m%s \033[0m
"""%(md5,python_version,download_url_for_release,\
download_num_for_release,download_size_for_release,filename) | python | def _release_info(jsn,VERSION):
"""Gives information about a particular package version."""
try:
release_point = jsn['releases'][VERSION][0]
except KeyError:
print "\033[91m\033[1mError: Release not found."
exit(1)
python_version = release_point['python_version']
filename = release_point['filename']
md5 = release_point['md5_digest']
download_url_for_release = release_point['url']
download_num_for_release = release_point['downloads']
download_size_for_release = _sizeof_fmt(int(release_point['size']))
print """
\033[1m\033[1m \033[4mPACKAGE VERSION INFO\033[0m
\033[1m md5 :\033[0m \033[93m%s \033[0m
\033[1m python version :\033[0m \033[93m%s \033[0m
\033[1m download url :\033[0m \033[93m%s \033[0m
\033[1m download number :\033[0m \033[93m%s \033[0m
\033[1m size :\033[0m \033[93m%s \033[0m
\033[1m filename :\033[0m \033[93m%s \033[0m
"""%(md5,python_version,download_url_for_release,\
download_num_for_release,download_size_for_release,filename) | [
"def",
"_release_info",
"(",
"jsn",
",",
"VERSION",
")",
":",
"try",
":",
"release_point",
"=",
"jsn",
"[",
"'releases'",
"]",
"[",
"VERSION",
"]",
"[",
"0",
"]",
"except",
"KeyError",
":",
"print",
"\"\\033[91m\\033[1mError: Release not found.\"",
"exit",
"(",
"1",
")",
"python_version",
"=",
"release_point",
"[",
"'python_version'",
"]",
"filename",
"=",
"release_point",
"[",
"'filename'",
"]",
"md5",
"=",
"release_point",
"[",
"'md5_digest'",
"]",
"download_url_for_release",
"=",
"release_point",
"[",
"'url'",
"]",
"download_num_for_release",
"=",
"release_point",
"[",
"'downloads'",
"]",
"download_size_for_release",
"=",
"_sizeof_fmt",
"(",
"int",
"(",
"release_point",
"[",
"'size'",
"]",
")",
")",
"print",
"\"\"\"\n\t\\033[1m\\033[1m \\033[4mPACKAGE VERSION INFO\\033[0m\n\n\t\\033[1m\tmd5 :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\tpython version :\\033[0m \\033[93m%s \\033[0m\t\n\t\\033[1m\tdownload url :\\033[0m \\033[93m%s \\033[0m\t\n\t\\033[1m\tdownload number :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\tsize :\\033[0m \\033[93m%s \\033[0m\t\n\t\\033[1m\tfilename :\\033[0m \\033[93m%s \\033[0m\t\n\t\"\"\"",
"%",
"(",
"md5",
",",
"python_version",
",",
"download_url_for_release",
",",
"download_num_for_release",
",",
"download_size_for_release",
",",
"filename",
")"
] | Gives information about a particular package version. | [
"Gives",
"information",
"about",
"a",
"particular",
"package",
"version",
"."
] | a7dbc90bba551a562644b1563c595d4ac38f15ed | https://github.com/arindampradhan/cheesy/blob/a7dbc90bba551a562644b1563c595d4ac38f15ed/cheesy/ch.py#L97-L120 |
247,755 | arindampradhan/cheesy | cheesy/ch.py | _construct | def _construct(PACKAGE,VERSION):
"""Construct the information part from the API."""
jsn = _get_info(PACKAGE)
package_url = jsn['info']['package_url']
author = jsn['info']['author']
author_email = jsn['info']['author_email']
description = jsn['info']['description']
last_month = jsn['info']['downloads']['last_month']
last_week = jsn['info']['downloads']['last_week']
last_day = jsn['info']['downloads']['last_day']
classifiers = jsn['info']['classifiers']
license = jsn['info']['license']
summary = jsn['info']['summary']
home_page = jsn['info']['home_page']
releases = reversed(jsn['releases'].keys())
releases = ' | '.join(releases)[:56]
download_url = jsn['urls'][0]['url']
filename = jsn['urls'][0]['filename']
size = _sizeof_fmt(int(jsn['urls'][0]['size']))
if VERSION:
try:
_release_info(jsn,VERSION)
except IndexError:
print "\033[91m\033[1mError: Try the Command:\n\033[1m\033[0m\033[1m$ cheesy <PACKAGE> <VERSION>"
return None
print """
\n\033[1m\033[4mDESCRIPTION\n\n\033[0m\033[93m%s \033[0m
\033[1m\033[1m \033[4mPACKAGE INFO\033[0m
\n
\033[1m package url :\033[0m \033[93m%s \033[0m
\033[1m author name :\033[0m \033[93m%s \033[0m
\033[1m author email :\033[0m \033[93m%s \033[0m
\033[1m downloads last month :\033[0m \033[93m%s \033[0m
\033[1m downloads last week :\033[0m \033[93m%s \033[0m
\033[1m downloads last day :\033[0m \033[93m%s \033[0m
\033[1m homepage :\033[0m \033[93m%s \033[0m
\033[1m releases :\033[0m \033[93m%s \033[0m
\033[1m download url :\033[0m \033[93m%s \033[0m
\033[1m filename :\033[0m \033[93m%s \033[0m
\033[1m size :\033[0m \033[93m%s \033[0m
"""%(description,package_url,author,author_email,last_month,last_week,\
last_day,home_page,releases,download_url,filename,size) | python | def _construct(PACKAGE,VERSION):
"""Construct the information part from the API."""
jsn = _get_info(PACKAGE)
package_url = jsn['info']['package_url']
author = jsn['info']['author']
author_email = jsn['info']['author_email']
description = jsn['info']['description']
last_month = jsn['info']['downloads']['last_month']
last_week = jsn['info']['downloads']['last_week']
last_day = jsn['info']['downloads']['last_day']
classifiers = jsn['info']['classifiers']
license = jsn['info']['license']
summary = jsn['info']['summary']
home_page = jsn['info']['home_page']
releases = reversed(jsn['releases'].keys())
releases = ' | '.join(releases)[:56]
download_url = jsn['urls'][0]['url']
filename = jsn['urls'][0]['filename']
size = _sizeof_fmt(int(jsn['urls'][0]['size']))
if VERSION:
try:
_release_info(jsn,VERSION)
except IndexError:
print "\033[91m\033[1mError: Try the Command:\n\033[1m\033[0m\033[1m$ cheesy <PACKAGE> <VERSION>"
return None
print """
\n\033[1m\033[4mDESCRIPTION\n\n\033[0m\033[93m%s \033[0m
\033[1m\033[1m \033[4mPACKAGE INFO\033[0m
\n
\033[1m package url :\033[0m \033[93m%s \033[0m
\033[1m author name :\033[0m \033[93m%s \033[0m
\033[1m author email :\033[0m \033[93m%s \033[0m
\033[1m downloads last month :\033[0m \033[93m%s \033[0m
\033[1m downloads last week :\033[0m \033[93m%s \033[0m
\033[1m downloads last day :\033[0m \033[93m%s \033[0m
\033[1m homepage :\033[0m \033[93m%s \033[0m
\033[1m releases :\033[0m \033[93m%s \033[0m
\033[1m download url :\033[0m \033[93m%s \033[0m
\033[1m filename :\033[0m \033[93m%s \033[0m
\033[1m size :\033[0m \033[93m%s \033[0m
"""%(description,package_url,author,author_email,last_month,last_week,\
last_day,home_page,releases,download_url,filename,size) | [
"def",
"_construct",
"(",
"PACKAGE",
",",
"VERSION",
")",
":",
"jsn",
"=",
"_get_info",
"(",
"PACKAGE",
")",
"package_url",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'package_url'",
"]",
"author",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'author'",
"]",
"author_email",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'author_email'",
"]",
"description",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'description'",
"]",
"last_month",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'downloads'",
"]",
"[",
"'last_month'",
"]",
"last_week",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'downloads'",
"]",
"[",
"'last_week'",
"]",
"last_day",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'downloads'",
"]",
"[",
"'last_day'",
"]",
"classifiers",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'classifiers'",
"]",
"license",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'license'",
"]",
"summary",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'summary'",
"]",
"home_page",
"=",
"jsn",
"[",
"'info'",
"]",
"[",
"'home_page'",
"]",
"releases",
"=",
"reversed",
"(",
"jsn",
"[",
"'releases'",
"]",
".",
"keys",
"(",
")",
")",
"releases",
"=",
"' | '",
".",
"join",
"(",
"releases",
")",
"[",
":",
"56",
"]",
"download_url",
"=",
"jsn",
"[",
"'urls'",
"]",
"[",
"0",
"]",
"[",
"'url'",
"]",
"filename",
"=",
"jsn",
"[",
"'urls'",
"]",
"[",
"0",
"]",
"[",
"'filename'",
"]",
"size",
"=",
"_sizeof_fmt",
"(",
"int",
"(",
"jsn",
"[",
"'urls'",
"]",
"[",
"0",
"]",
"[",
"'size'",
"]",
")",
")",
"if",
"VERSION",
":",
"try",
":",
"_release_info",
"(",
"jsn",
",",
"VERSION",
")",
"except",
"IndexError",
":",
"print",
"\"\\033[91m\\033[1mError: Try the Command:\\n\\033[1m\\033[0m\\033[1m$ cheesy <PACKAGE> <VERSION>\"",
"return",
"None",
"print",
"\"\"\"\n\t\\n\\033[1m\\033[4mDESCRIPTION\\n\\n\\033[0m\\033[93m%s \\033[0m\n\t\n\t\\033[1m\\033[1m \\033[4mPACKAGE INFO\\033[0m\n\t\\n\n\t\\033[1m\tpackage url :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\tauthor name :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\tauthor email :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\tdownloads last month :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\tdownloads last week :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\tdownloads last day :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\thomepage :\\033[0m \\033[93m%s \\033[0m\n\t\\033[1m\treleases :\\033[0m \\033[93m%s \\033[0m\t\n\t\\033[1m\tdownload url :\\033[0m \\033[93m%s \\033[0m\t\n\t\\033[1m\tfilename :\\033[0m \\033[93m%s \\033[0m\t\n\t\\033[1m\tsize :\\033[0m \\033[93m%s \\033[0m\t\n\t\"\"\"",
"%",
"(",
"description",
",",
"package_url",
",",
"author",
",",
"author_email",
",",
"last_month",
",",
"last_week",
",",
"last_day",
",",
"home_page",
",",
"releases",
",",
"download_url",
",",
"filename",
",",
"size",
")"
] | Construct the information part from the API. | [
"Construct",
"the",
"information",
"part",
"from",
"the",
"API",
"."
] | a7dbc90bba551a562644b1563c595d4ac38f15ed | https://github.com/arindampradhan/cheesy/blob/a7dbc90bba551a562644b1563c595d4ac38f15ed/cheesy/ch.py#L122-L167 |
247,756 | arindampradhan/cheesy | cheesy/ch.py | main | def main():
'''cheesy gives you the news for today's cheese pipy factory from command line'''
arguments = docopt(__doc__, version=__version__)
if arguments['ls']:
_pull_all('ls')
elif arguments['list']:
_pull_all('list')
elif arguments['<PACKAGE>']:
try:
if arguments['<VERSION>']:
_construct(arguments['<PACKAGE>'],arguments['<VERSION>'])
else:
_construct(arguments['<PACKAGE>'],None)
except ValueError:
print "\033[91m\033[1mError: package not found try.. \033[0m\033[1m\n$ cheese ls \nto view pacakages"
else:
print(__doc__) | python | def main():
'''cheesy gives you the news for today's cheese pipy factory from command line'''
arguments = docopt(__doc__, version=__version__)
if arguments['ls']:
_pull_all('ls')
elif arguments['list']:
_pull_all('list')
elif arguments['<PACKAGE>']:
try:
if arguments['<VERSION>']:
_construct(arguments['<PACKAGE>'],arguments['<VERSION>'])
else:
_construct(arguments['<PACKAGE>'],None)
except ValueError:
print "\033[91m\033[1mError: package not found try.. \033[0m\033[1m\n$ cheese ls \nto view pacakages"
else:
print(__doc__) | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__version__",
")",
"if",
"arguments",
"[",
"'ls'",
"]",
":",
"_pull_all",
"(",
"'ls'",
")",
"elif",
"arguments",
"[",
"'list'",
"]",
":",
"_pull_all",
"(",
"'list'",
")",
"elif",
"arguments",
"[",
"'<PACKAGE>'",
"]",
":",
"try",
":",
"if",
"arguments",
"[",
"'<VERSION>'",
"]",
":",
"_construct",
"(",
"arguments",
"[",
"'<PACKAGE>'",
"]",
",",
"arguments",
"[",
"'<VERSION>'",
"]",
")",
"else",
":",
"_construct",
"(",
"arguments",
"[",
"'<PACKAGE>'",
"]",
",",
"None",
")",
"except",
"ValueError",
":",
"print",
"\"\\033[91m\\033[1mError: package not found try.. \\033[0m\\033[1m\\n$ cheese ls \\nto view pacakages\"",
"else",
":",
"print",
"(",
"__doc__",
")"
] | cheesy gives you the news for today's cheese pipy factory from command line | [
"cheesy",
"gives",
"you",
"the",
"news",
"for",
"today",
"s",
"cheese",
"pipy",
"factory",
"from",
"command",
"line"
] | a7dbc90bba551a562644b1563c595d4ac38f15ed | https://github.com/arindampradhan/cheesy/blob/a7dbc90bba551a562644b1563c595d4ac38f15ed/cheesy/ch.py#L170-L186 |
247,757 | fstab50/metal | metal/chk_standalone.py | os_packages | def os_packages(metadata):
""" Installs operating system dependent packages """
family = metadata[0]
release = metadata[1]
#
if 'Amazon' in family and '2' not in release:
stdout_message('Identified Amazon Linux 1 os distro')
commands = [
'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
return True
elif 'Amazon' in family and '2' in release:
stdout_message('Identified Amazon Linux 2 os distro')
commands = [
'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
return True
elif 'Redhat' in family:
stdout_message('Identified Redhat Enterprise Linux os distro')
commands = [
'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
elif 'Ubuntu' or 'Mint' in family:
stdout_message('Identified Ubuntu Linux os distro')
commands = [
'sudo apt -y update', 'sudo apt -y upgrade',
'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
return True
return False | python | def os_packages(metadata):
""" Installs operating system dependent packages """
family = metadata[0]
release = metadata[1]
#
if 'Amazon' in family and '2' not in release:
stdout_message('Identified Amazon Linux 1 os distro')
commands = [
'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
return True
elif 'Amazon' in family and '2' in release:
stdout_message('Identified Amazon Linux 2 os distro')
commands = [
'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
return True
elif 'Redhat' in family:
stdout_message('Identified Redhat Enterprise Linux os distro')
commands = [
'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
elif 'Ubuntu' or 'Mint' in family:
stdout_message('Identified Ubuntu Linux os distro')
commands = [
'sudo apt -y update', 'sudo apt -y upgrade',
'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
stdout_message(subprocess.getoutput(cmd))
return True
return False | [
"def",
"os_packages",
"(",
"metadata",
")",
":",
"family",
"=",
"metadata",
"[",
"0",
"]",
"release",
"=",
"metadata",
"[",
"1",
"]",
"#",
"if",
"'Amazon'",
"in",
"family",
"and",
"'2'",
"not",
"in",
"release",
":",
"stdout_message",
"(",
"'Identified Amazon Linux 1 os distro'",
")",
"commands",
"=",
"[",
"'sudo yum -y update'",
",",
"'sudo yum -y groupinstall \"Development tools\"'",
"]",
"for",
"cmd",
"in",
"commands",
":",
"stdout_message",
"(",
"subprocess",
".",
"getoutput",
"(",
"cmd",
")",
")",
"return",
"True",
"elif",
"'Amazon'",
"in",
"family",
"and",
"'2'",
"in",
"release",
":",
"stdout_message",
"(",
"'Identified Amazon Linux 2 os distro'",
")",
"commands",
"=",
"[",
"'sudo yum -y update'",
",",
"'sudo yum -y groupinstall \"Development tools\"'",
"]",
"for",
"cmd",
"in",
"commands",
":",
"stdout_message",
"(",
"subprocess",
".",
"getoutput",
"(",
"cmd",
")",
")",
"return",
"True",
"elif",
"'Redhat'",
"in",
"family",
":",
"stdout_message",
"(",
"'Identified Redhat Enterprise Linux os distro'",
")",
"commands",
"=",
"[",
"'sudo yum -y update'",
",",
"'sudo yum -y groupinstall \"Development tools\"'",
"]",
"for",
"cmd",
"in",
"commands",
":",
"stdout_message",
"(",
"subprocess",
".",
"getoutput",
"(",
"cmd",
")",
")",
"elif",
"'Ubuntu'",
"or",
"'Mint'",
"in",
"family",
":",
"stdout_message",
"(",
"'Identified Ubuntu Linux os distro'",
")",
"commands",
"=",
"[",
"'sudo apt -y update'",
",",
"'sudo apt -y upgrade'",
",",
"'sudo yum -y groupinstall \"Development tools\"'",
"]",
"for",
"cmd",
"in",
"commands",
":",
"stdout_message",
"(",
"subprocess",
".",
"getoutput",
"(",
"cmd",
")",
")",
"return",
"True",
"return",
"False"
] | Installs operating system dependent packages | [
"Installs",
"operating",
"system",
"dependent",
"packages"
] | 0488bbdd516a508909267cc44191f632e21156ba | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chk_standalone.py#L166-L203 |
247,758 | fstab50/metal | metal/chk_standalone.py | stdout_message | def stdout_message(message, prefix='INFO', quiet=False,
multiline=False, tabspaces=4, severity=''):
""" Prints message to cli stdout while indicating type and severity
Args:
:message (str): text characters to be printed to stdout
:prefix (str): 4-letter string message type identifier.
:quiet (bool): Flag to suppress all output
:multiline (bool): indicates multiline message; removes blank lines on
either side of printed message
:tabspaces (int): left justified number of spaces
:severity (str): header msg determined color instead of prefix
.. code-block:: python
# Examples:
- INFO (default)
- ERROR (error, problem occurred)
- WARN (warning)
- NOTE (important to know)
Returns:
TYPE: bool, Success (printed) | Failure (no output)
"""
prefix = prefix.upper()
tabspaces = int(tabspaces)
# prefix color handling
choices = ('RED', 'BLUE', 'WHITE', 'GREEN', 'ORANGE')
critical_status = ('ERROR', 'FAIL', 'WTF', 'STOP', 'HALT', 'EXIT', 'F*CK')
if quiet:
return False
else:
if prefix in critical_status or severity.upper() == 'CRITICAL':
header = (Colors.YELLOW + '\t[ ' + Colors.RED + prefix +
Colors.YELLOW + ' ]' + Colors.RESET + ': ')
elif severity.upper() == 'WARNING':
header = (Colors.YELLOW + '\t[ ' + Colors.ORANGE + prefix +
Colors.YELLOW + ' ]' + Colors.RESET + ': ')
else: # default color scheme
header = (Colors.YELLOW + '\t[ ' + Colors.DARKCYAN + prefix +
Colors.YELLOW + ' ]' + Colors.RESET + ': ')
if multiline:
print(header.expandtabs(tabspaces) + str(message))
else:
print('\n' + header.expandtabs(tabspaces) + str(message) + '\n')
return True | python | def stdout_message(message, prefix='INFO', quiet=False,
multiline=False, tabspaces=4, severity=''):
""" Prints message to cli stdout while indicating type and severity
Args:
:message (str): text characters to be printed to stdout
:prefix (str): 4-letter string message type identifier.
:quiet (bool): Flag to suppress all output
:multiline (bool): indicates multiline message; removes blank lines on
either side of printed message
:tabspaces (int): left justified number of spaces
:severity (str): header msg determined color instead of prefix
.. code-block:: python
# Examples:
- INFO (default)
- ERROR (error, problem occurred)
- WARN (warning)
- NOTE (important to know)
Returns:
TYPE: bool, Success (printed) | Failure (no output)
"""
prefix = prefix.upper()
tabspaces = int(tabspaces)
# prefix color handling
choices = ('RED', 'BLUE', 'WHITE', 'GREEN', 'ORANGE')
critical_status = ('ERROR', 'FAIL', 'WTF', 'STOP', 'HALT', 'EXIT', 'F*CK')
if quiet:
return False
else:
if prefix in critical_status or severity.upper() == 'CRITICAL':
header = (Colors.YELLOW + '\t[ ' + Colors.RED + prefix +
Colors.YELLOW + ' ]' + Colors.RESET + ': ')
elif severity.upper() == 'WARNING':
header = (Colors.YELLOW + '\t[ ' + Colors.ORANGE + prefix +
Colors.YELLOW + ' ]' + Colors.RESET + ': ')
else: # default color scheme
header = (Colors.YELLOW + '\t[ ' + Colors.DARKCYAN + prefix +
Colors.YELLOW + ' ]' + Colors.RESET + ': ')
if multiline:
print(header.expandtabs(tabspaces) + str(message))
else:
print('\n' + header.expandtabs(tabspaces) + str(message) + '\n')
return True | [
"def",
"stdout_message",
"(",
"message",
",",
"prefix",
"=",
"'INFO'",
",",
"quiet",
"=",
"False",
",",
"multiline",
"=",
"False",
",",
"tabspaces",
"=",
"4",
",",
"severity",
"=",
"''",
")",
":",
"prefix",
"=",
"prefix",
".",
"upper",
"(",
")",
"tabspaces",
"=",
"int",
"(",
"tabspaces",
")",
"# prefix color handling",
"choices",
"=",
"(",
"'RED'",
",",
"'BLUE'",
",",
"'WHITE'",
",",
"'GREEN'",
",",
"'ORANGE'",
")",
"critical_status",
"=",
"(",
"'ERROR'",
",",
"'FAIL'",
",",
"'WTF'",
",",
"'STOP'",
",",
"'HALT'",
",",
"'EXIT'",
",",
"'F*CK'",
")",
"if",
"quiet",
":",
"return",
"False",
"else",
":",
"if",
"prefix",
"in",
"critical_status",
"or",
"severity",
".",
"upper",
"(",
")",
"==",
"'CRITICAL'",
":",
"header",
"=",
"(",
"Colors",
".",
"YELLOW",
"+",
"'\\t[ '",
"+",
"Colors",
".",
"RED",
"+",
"prefix",
"+",
"Colors",
".",
"YELLOW",
"+",
"' ]'",
"+",
"Colors",
".",
"RESET",
"+",
"': '",
")",
"elif",
"severity",
".",
"upper",
"(",
")",
"==",
"'WARNING'",
":",
"header",
"=",
"(",
"Colors",
".",
"YELLOW",
"+",
"'\\t[ '",
"+",
"Colors",
".",
"ORANGE",
"+",
"prefix",
"+",
"Colors",
".",
"YELLOW",
"+",
"' ]'",
"+",
"Colors",
".",
"RESET",
"+",
"': '",
")",
"else",
":",
"# default color scheme",
"header",
"=",
"(",
"Colors",
".",
"YELLOW",
"+",
"'\\t[ '",
"+",
"Colors",
".",
"DARKCYAN",
"+",
"prefix",
"+",
"Colors",
".",
"YELLOW",
"+",
"' ]'",
"+",
"Colors",
".",
"RESET",
"+",
"': '",
")",
"if",
"multiline",
":",
"print",
"(",
"header",
".",
"expandtabs",
"(",
"tabspaces",
")",
"+",
"str",
"(",
"message",
")",
")",
"else",
":",
"print",
"(",
"'\\n'",
"+",
"header",
".",
"expandtabs",
"(",
"tabspaces",
")",
"+",
"str",
"(",
"message",
")",
"+",
"'\\n'",
")",
"return",
"True"
] | Prints message to cli stdout while indicating type and severity
Args:
:message (str): text characters to be printed to stdout
:prefix (str): 4-letter string message type identifier.
:quiet (bool): Flag to suppress all output
:multiline (bool): indicates multiline message; removes blank lines on
either side of printed message
:tabspaces (int): left justified number of spaces
:severity (str): header msg determined color instead of prefix
.. code-block:: python
# Examples:
- INFO (default)
- ERROR (error, problem occurred)
- WARN (warning)
- NOTE (important to know)
Returns:
TYPE: bool, Success (printed) | Failure (no output) | [
"Prints",
"message",
"to",
"cli",
"stdout",
"while",
"indicating",
"type",
"and",
"severity"
] | 0488bbdd516a508909267cc44191f632e21156ba | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chk_standalone.py#L206-L253 |
247,759 | fstab50/metal | metal/chk_standalone.py | main | def main():
"""
Check Dependencies, download files, integrity check
"""
# vars
tar_file = TMPDIR + '/' + BINARY_URL.split('/')[-1]
chksum = TMPDIR + '/' + MD5_URL.split('/')[-1]
# pre-run validation + execution
if precheck() and os_packages(distro.linux_distribution()):
stdout_message('begin download')
download()
stdout_message('begin valid_checksum')
valid_checksum(tar_file, chksum)
return compile_binary(tar_file)
logger.warning('%s: Pre-run dependency check fail - Exit' % inspect.stack()[0][3])
return False | python | def main():
"""
Check Dependencies, download files, integrity check
"""
# vars
tar_file = TMPDIR + '/' + BINARY_URL.split('/')[-1]
chksum = TMPDIR + '/' + MD5_URL.split('/')[-1]
# pre-run validation + execution
if precheck() and os_packages(distro.linux_distribution()):
stdout_message('begin download')
download()
stdout_message('begin valid_checksum')
valid_checksum(tar_file, chksum)
return compile_binary(tar_file)
logger.warning('%s: Pre-run dependency check fail - Exit' % inspect.stack()[0][3])
return False | [
"def",
"main",
"(",
")",
":",
"# vars",
"tar_file",
"=",
"TMPDIR",
"+",
"'/'",
"+",
"BINARY_URL",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"chksum",
"=",
"TMPDIR",
"+",
"'/'",
"+",
"MD5_URL",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"# pre-run validation + execution",
"if",
"precheck",
"(",
")",
"and",
"os_packages",
"(",
"distro",
".",
"linux_distribution",
"(",
")",
")",
":",
"stdout_message",
"(",
"'begin download'",
")",
"download",
"(",
")",
"stdout_message",
"(",
"'begin valid_checksum'",
")",
"valid_checksum",
"(",
"tar_file",
",",
"chksum",
")",
"return",
"compile_binary",
"(",
"tar_file",
")",
"logger",
".",
"warning",
"(",
"'%s: Pre-run dependency check fail - Exit'",
"%",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
")",
"return",
"False"
] | Check Dependencies, download files, integrity check | [
"Check",
"Dependencies",
"download",
"files",
"integrity",
"check"
] | 0488bbdd516a508909267cc44191f632e21156ba | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chk_standalone.py#L256-L271 |
247,760 | naphatkrit/easyci | easyci/commands/gc.py | gc | def gc(ctx):
"""Runs housekeeping tasks to free up space.
For now, this only removes saved but unused (unreachable) test results.
"""
vcs = ctx.obj['vcs']
count = 0
with locking.lock(vcs, locking.Lock.tests_history):
known_signatures = set(get_committed_signatures(vcs) + get_staged_signatures(vcs))
for signature in get_signatures_with_results(vcs):
if signature not in known_signatures:
count += 1
remove_results(vcs, signature)
click.echo('Removed {} saved results.'.format(count)) | python | def gc(ctx):
"""Runs housekeeping tasks to free up space.
For now, this only removes saved but unused (unreachable) test results.
"""
vcs = ctx.obj['vcs']
count = 0
with locking.lock(vcs, locking.Lock.tests_history):
known_signatures = set(get_committed_signatures(vcs) + get_staged_signatures(vcs))
for signature in get_signatures_with_results(vcs):
if signature not in known_signatures:
count += 1
remove_results(vcs, signature)
click.echo('Removed {} saved results.'.format(count)) | [
"def",
"gc",
"(",
"ctx",
")",
":",
"vcs",
"=",
"ctx",
".",
"obj",
"[",
"'vcs'",
"]",
"count",
"=",
"0",
"with",
"locking",
".",
"lock",
"(",
"vcs",
",",
"locking",
".",
"Lock",
".",
"tests_history",
")",
":",
"known_signatures",
"=",
"set",
"(",
"get_committed_signatures",
"(",
"vcs",
")",
"+",
"get_staged_signatures",
"(",
"vcs",
")",
")",
"for",
"signature",
"in",
"get_signatures_with_results",
"(",
"vcs",
")",
":",
"if",
"signature",
"not",
"in",
"known_signatures",
":",
"count",
"+=",
"1",
"remove_results",
"(",
"vcs",
",",
"signature",
")",
"click",
".",
"echo",
"(",
"'Removed {} saved results.'",
".",
"format",
"(",
"count",
")",
")"
] | Runs housekeeping tasks to free up space.
For now, this only removes saved but unused (unreachable) test results. | [
"Runs",
"housekeeping",
"tasks",
"to",
"free",
"up",
"space",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/commands/gc.py#L12-L25 |
247,761 | Tinche/django-bower-cache | registry/tasks.py | clone_repo | def clone_repo(pkg_name, repo_url):
"""Create a new cloned repo with the given parameters."""
new_repo = ClonedRepo(name=pkg_name, origin=repo_url)
new_repo.save()
return new_repo | python | def clone_repo(pkg_name, repo_url):
"""Create a new cloned repo with the given parameters."""
new_repo = ClonedRepo(name=pkg_name, origin=repo_url)
new_repo.save()
return new_repo | [
"def",
"clone_repo",
"(",
"pkg_name",
",",
"repo_url",
")",
":",
"new_repo",
"=",
"ClonedRepo",
"(",
"name",
"=",
"pkg_name",
",",
"origin",
"=",
"repo_url",
")",
"new_repo",
".",
"save",
"(",
")",
"return",
"new_repo"
] | Create a new cloned repo with the given parameters. | [
"Create",
"a",
"new",
"cloned",
"repo",
"with",
"the",
"given",
"parameters",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/tasks.py#L10-L14 |
247,762 | Tinche/django-bower-cache | registry/tasks.py | pull_repo | def pull_repo(repo_name):
"""Pull from origin for repo_name."""
repo = ClonedRepo.objects.get(pk=repo_name)
repo.pull() | python | def pull_repo(repo_name):
"""Pull from origin for repo_name."""
repo = ClonedRepo.objects.get(pk=repo_name)
repo.pull() | [
"def",
"pull_repo",
"(",
"repo_name",
")",
":",
"repo",
"=",
"ClonedRepo",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"repo_name",
")",
"repo",
".",
"pull",
"(",
")"
] | Pull from origin for repo_name. | [
"Pull",
"from",
"origin",
"for",
"repo_name",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/tasks.py#L18-L21 |
247,763 | Tinche/django-bower-cache | registry/tasks.py | pull_all_repos | def pull_all_repos():
"""Pull origin updates for all repos with origins."""
repos = ClonedRepo.objects.all()
for repo in repos:
if repo.origin is not None:
pull_repo.delay(repo_name=repo.name) | python | def pull_all_repos():
"""Pull origin updates for all repos with origins."""
repos = ClonedRepo.objects.all()
for repo in repos:
if repo.origin is not None:
pull_repo.delay(repo_name=repo.name) | [
"def",
"pull_all_repos",
"(",
")",
":",
"repos",
"=",
"ClonedRepo",
".",
"objects",
".",
"all",
"(",
")",
"for",
"repo",
"in",
"repos",
":",
"if",
"repo",
".",
"origin",
"is",
"not",
"None",
":",
"pull_repo",
".",
"delay",
"(",
"repo_name",
"=",
"repo",
".",
"name",
")"
] | Pull origin updates for all repos with origins. | [
"Pull",
"origin",
"updates",
"for",
"all",
"repos",
"with",
"origins",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/tasks.py#L25-L30 |
247,764 | Othernet-Project/hwd | hwd/network.py | NetIface._get_ipv4_addrs | def _get_ipv4_addrs(self):
"""
Returns the IPv4 addresses associated with this NIC. If no IPv4
addresses are used, then empty dictionary is returned.
"""
addrs = self._get_addrs()
ipv4addrs = addrs.get(netifaces.AF_INET)
if not ipv4addrs:
return {}
return ipv4addrs[0] | python | def _get_ipv4_addrs(self):
"""
Returns the IPv4 addresses associated with this NIC. If no IPv4
addresses are used, then empty dictionary is returned.
"""
addrs = self._get_addrs()
ipv4addrs = addrs.get(netifaces.AF_INET)
if not ipv4addrs:
return {}
return ipv4addrs[0] | [
"def",
"_get_ipv4_addrs",
"(",
"self",
")",
":",
"addrs",
"=",
"self",
".",
"_get_addrs",
"(",
")",
"ipv4addrs",
"=",
"addrs",
".",
"get",
"(",
"netifaces",
".",
"AF_INET",
")",
"if",
"not",
"ipv4addrs",
":",
"return",
"{",
"}",
"return",
"ipv4addrs",
"[",
"0",
"]"
] | Returns the IPv4 addresses associated with this NIC. If no IPv4
addresses are used, then empty dictionary is returned. | [
"Returns",
"the",
"IPv4",
"addresses",
"associated",
"with",
"this",
"NIC",
".",
"If",
"no",
"IPv4",
"addresses",
"are",
"used",
"then",
"empty",
"dictionary",
"is",
"returned",
"."
] | 7f4445bac61aa2305806aa80338e2ce5baa1093c | https://github.com/Othernet-Project/hwd/blob/7f4445bac61aa2305806aa80338e2ce5baa1093c/hwd/network.py#L47-L56 |
247,765 | Othernet-Project/hwd | hwd/network.py | NetIface._get_ipv6addrs | def _get_ipv6addrs(self):
"""
Returns the IPv6 addresses associated with this NIC. If no IPv6
addresses are used, empty dict is returned.
"""
addrs = self._get_addrs()
ipv6addrs = addrs.get(netifaces.AF_INET6)
if not ipv6addrs:
return {}
return ipv6addrs[0] | python | def _get_ipv6addrs(self):
"""
Returns the IPv6 addresses associated with this NIC. If no IPv6
addresses are used, empty dict is returned.
"""
addrs = self._get_addrs()
ipv6addrs = addrs.get(netifaces.AF_INET6)
if not ipv6addrs:
return {}
return ipv6addrs[0] | [
"def",
"_get_ipv6addrs",
"(",
"self",
")",
":",
"addrs",
"=",
"self",
".",
"_get_addrs",
"(",
")",
"ipv6addrs",
"=",
"addrs",
".",
"get",
"(",
"netifaces",
".",
"AF_INET6",
")",
"if",
"not",
"ipv6addrs",
":",
"return",
"{",
"}",
"return",
"ipv6addrs",
"[",
"0",
"]"
] | Returns the IPv6 addresses associated with this NIC. If no IPv6
addresses are used, empty dict is returned. | [
"Returns",
"the",
"IPv6",
"addresses",
"associated",
"with",
"this",
"NIC",
".",
"If",
"no",
"IPv6",
"addresses",
"are",
"used",
"empty",
"dict",
"is",
"returned",
"."
] | 7f4445bac61aa2305806aa80338e2ce5baa1093c | https://github.com/Othernet-Project/hwd/blob/7f4445bac61aa2305806aa80338e2ce5baa1093c/hwd/network.py#L58-L67 |
247,766 | Othernet-Project/hwd | hwd/network.py | NetIface._get_default_gateway | def _get_default_gateway(self, ip=4):
"""
Returns the default gateway for given IP version. The ``ip`` argument
is used to specify the IP version, and can be either 4 or 6.
"""
net_type = netifaces.AF_INET if ip == 4 else netifaces.AF_INET6
gw = netifaces.gateways()['default'].get(net_type, (None, None))
if gw[1] == self.name:
return gw[0] | python | def _get_default_gateway(self, ip=4):
"""
Returns the default gateway for given IP version. The ``ip`` argument
is used to specify the IP version, and can be either 4 or 6.
"""
net_type = netifaces.AF_INET if ip == 4 else netifaces.AF_INET6
gw = netifaces.gateways()['default'].get(net_type, (None, None))
if gw[1] == self.name:
return gw[0] | [
"def",
"_get_default_gateway",
"(",
"self",
",",
"ip",
"=",
"4",
")",
":",
"net_type",
"=",
"netifaces",
".",
"AF_INET",
"if",
"ip",
"==",
"4",
"else",
"netifaces",
".",
"AF_INET6",
"gw",
"=",
"netifaces",
".",
"gateways",
"(",
")",
"[",
"'default'",
"]",
".",
"get",
"(",
"net_type",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"gw",
"[",
"1",
"]",
"==",
"self",
".",
"name",
":",
"return",
"gw",
"[",
"0",
"]"
] | Returns the default gateway for given IP version. The ``ip`` argument
is used to specify the IP version, and can be either 4 or 6. | [
"Returns",
"the",
"default",
"gateway",
"for",
"given",
"IP",
"version",
".",
"The",
"ip",
"argument",
"is",
"used",
"to",
"specify",
"the",
"IP",
"version",
"and",
"can",
"be",
"either",
"4",
"or",
"6",
"."
] | 7f4445bac61aa2305806aa80338e2ce5baa1093c | https://github.com/Othernet-Project/hwd/blob/7f4445bac61aa2305806aa80338e2ce5baa1093c/hwd/network.py#L69-L77 |
247,767 | ArabellaTech/ydcommon | ydcommon/fab.py | release_qa | def release_qa(quietly=False):
"""
Release code to QA server
"""
name = prompt(red('Sprint name?'), default='Sprint 1').lower().replace(' ', "_")
release_date = prompt(red('Sprint start date (Y-m-d)?'), default='2013-01-20').replace('-', '')
release_name = '%s_%s' % (release_date, name)
local('git flow release start %s' % release_name)
local('git flow release publish %s' % release_name)
if not quietly:
print(red('PLEASE DEPLOY CODE: fab deploy:all')) | python | def release_qa(quietly=False):
"""
Release code to QA server
"""
name = prompt(red('Sprint name?'), default='Sprint 1').lower().replace(' ', "_")
release_date = prompt(red('Sprint start date (Y-m-d)?'), default='2013-01-20').replace('-', '')
release_name = '%s_%s' % (release_date, name)
local('git flow release start %s' % release_name)
local('git flow release publish %s' % release_name)
if not quietly:
print(red('PLEASE DEPLOY CODE: fab deploy:all')) | [
"def",
"release_qa",
"(",
"quietly",
"=",
"False",
")",
":",
"name",
"=",
"prompt",
"(",
"red",
"(",
"'Sprint name?'",
")",
",",
"default",
"=",
"'Sprint 1'",
")",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"\"_\"",
")",
"release_date",
"=",
"prompt",
"(",
"red",
"(",
"'Sprint start date (Y-m-d)?'",
")",
",",
"default",
"=",
"'2013-01-20'",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"release_name",
"=",
"'%s_%s'",
"%",
"(",
"release_date",
",",
"name",
")",
"local",
"(",
"'git flow release start %s'",
"%",
"release_name",
")",
"local",
"(",
"'git flow release publish %s'",
"%",
"release_name",
")",
"if",
"not",
"quietly",
":",
"print",
"(",
"red",
"(",
"'PLEASE DEPLOY CODE: fab deploy:all'",
")",
")"
] | Release code to QA server | [
"Release",
"code",
"to",
"QA",
"server"
] | 4aa105e7b33f379e8f09111497c0e427b189c36c | https://github.com/ArabellaTech/ydcommon/blob/4aa105e7b33f379e8f09111497c0e427b189c36c/ydcommon/fab.py#L63-L73 |
247,768 | ArabellaTech/ydcommon | ydcommon/fab.py | update_qa | def update_qa(quietly=False):
"""
Merge code from develop to qa
"""
switch('dev')
switch('qa')
local('git merge --no-edit develop')
local('git push')
if not quietly:
print(red('PLEASE DEPLOY CODE: fab deploy:all')) | python | def update_qa(quietly=False):
"""
Merge code from develop to qa
"""
switch('dev')
switch('qa')
local('git merge --no-edit develop')
local('git push')
if not quietly:
print(red('PLEASE DEPLOY CODE: fab deploy:all')) | [
"def",
"update_qa",
"(",
"quietly",
"=",
"False",
")",
":",
"switch",
"(",
"'dev'",
")",
"switch",
"(",
"'qa'",
")",
"local",
"(",
"'git merge --no-edit develop'",
")",
"local",
"(",
"'git push'",
")",
"if",
"not",
"quietly",
":",
"print",
"(",
"red",
"(",
"'PLEASE DEPLOY CODE: fab deploy:all'",
")",
")"
] | Merge code from develop to qa | [
"Merge",
"code",
"from",
"develop",
"to",
"qa"
] | 4aa105e7b33f379e8f09111497c0e427b189c36c | https://github.com/ArabellaTech/ydcommon/blob/4aa105e7b33f379e8f09111497c0e427b189c36c/ydcommon/fab.py#L76-L85 |
247,769 | ArabellaTech/ydcommon | ydcommon/fab.py | backup_db | def backup_db():
"""
Backup local database
"""
if not os.path.exists('backups'):
os.makedirs('backups')
local('python manage.py dump_database | gzip > backups/' + _sql_paths('local', datetime.now())) | python | def backup_db():
"""
Backup local database
"""
if not os.path.exists('backups'):
os.makedirs('backups')
local('python manage.py dump_database | gzip > backups/' + _sql_paths('local', datetime.now())) | [
"def",
"backup_db",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'backups'",
")",
":",
"os",
".",
"makedirs",
"(",
"'backups'",
")",
"local",
"(",
"'python manage.py dump_database | gzip > backups/'",
"+",
"_sql_paths",
"(",
"'local'",
",",
"datetime",
".",
"now",
"(",
")",
")",
")"
] | Backup local database | [
"Backup",
"local",
"database"
] | 4aa105e7b33f379e8f09111497c0e427b189c36c | https://github.com/ArabellaTech/ydcommon/blob/4aa105e7b33f379e8f09111497c0e427b189c36c/ydcommon/fab.py#L123-L129 |
247,770 | ArabellaTech/ydcommon | ydcommon/fab.py | _get_db | def _get_db():
"""
Get database from server
"""
with cd(env.remote_path):
file_path = '/tmp/' + _sql_paths('remote', str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', ''))
run(env.python + ' manage.py dump_database | gzip > ' + file_path)
local_file_path = './backups/' + _sql_paths('remote', datetime.now())
get(file_path, local_file_path)
run('rm ' + file_path)
return local_file_path | python | def _get_db():
"""
Get database from server
"""
with cd(env.remote_path):
file_path = '/tmp/' + _sql_paths('remote', str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', ''))
run(env.python + ' manage.py dump_database | gzip > ' + file_path)
local_file_path = './backups/' + _sql_paths('remote', datetime.now())
get(file_path, local_file_path)
run('rm ' + file_path)
return local_file_path | [
"def",
"_get_db",
"(",
")",
":",
"with",
"cd",
"(",
"env",
".",
"remote_path",
")",
":",
"file_path",
"=",
"'/tmp/'",
"+",
"_sql_paths",
"(",
"'remote'",
",",
"str",
"(",
"base64",
".",
"urlsafe_b64encode",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
")",
".",
"replace",
"(",
"'='",
",",
"''",
")",
")",
"run",
"(",
"env",
".",
"python",
"+",
"' manage.py dump_database | gzip > '",
"+",
"file_path",
")",
"local_file_path",
"=",
"'./backups/'",
"+",
"_sql_paths",
"(",
"'remote'",
",",
"datetime",
".",
"now",
"(",
")",
")",
"get",
"(",
"file_path",
",",
"local_file_path",
")",
"run",
"(",
"'rm '",
"+",
"file_path",
")",
"return",
"local_file_path"
] | Get database from server | [
"Get",
"database",
"from",
"server"
] | 4aa105e7b33f379e8f09111497c0e427b189c36c | https://github.com/ArabellaTech/ydcommon/blob/4aa105e7b33f379e8f09111497c0e427b189c36c/ydcommon/fab.py#L132-L142 |
247,771 | ArabellaTech/ydcommon | ydcommon/fab.py | command | def command(command):
"""
Run custom Django management command
"""
with cd(env.remote_path):
sudo(env.python + ' manage.py %s' % command, user=env.remote_user) | python | def command(command):
"""
Run custom Django management command
"""
with cd(env.remote_path):
sudo(env.python + ' manage.py %s' % command, user=env.remote_user) | [
"def",
"command",
"(",
"command",
")",
":",
"with",
"cd",
"(",
"env",
".",
"remote_path",
")",
":",
"sudo",
"(",
"env",
".",
"python",
"+",
"' manage.py %s'",
"%",
"command",
",",
"user",
"=",
"env",
".",
"remote_user",
")"
] | Run custom Django management command | [
"Run",
"custom",
"Django",
"management",
"command"
] | 4aa105e7b33f379e8f09111497c0e427b189c36c | https://github.com/ArabellaTech/ydcommon/blob/4aa105e7b33f379e8f09111497c0e427b189c36c/ydcommon/fab.py#L173-L178 |
247,772 | ArabellaTech/ydcommon | ydcommon/fab.py | copy_s3_bucket | def copy_s3_bucket(src_bucket_name, src_bucket_secret_key, src_bucket_access_key,
dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key):
""" Copy S3 bucket directory with CMS data between environments. Operations are done on server. """
with cd(env.remote_path):
tmp_dir = "s3_tmp"
sudo('rm -rf %s' % tmp_dir, warn_only=True, user=env.remote_user)
sudo('mkdir %s' % tmp_dir, user=env.remote_user)
sudo('s3cmd --recursive get s3://%s/upload/ %s --secret_key=%s --access_key=%s' % (
src_bucket_name, tmp_dir, src_bucket_secret_key, src_bucket_access_key),
user=env.remote_user)
sudo('s3cmd --recursive put %s/ s3://%s/upload/ --secret_key=%s --access_key=%s' % (
tmp_dir, dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key),
user=env.remote_user)
sudo('s3cmd setacl s3://%s/upload --acl-public --recursive --secret_key=%s --access_key=%s' % (
dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key),
user=env.remote_user)
# cleanup
sudo('rm -rf %s' % tmp_dir, warn_only=True, user=env.remote_user) | python | def copy_s3_bucket(src_bucket_name, src_bucket_secret_key, src_bucket_access_key,
dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key):
""" Copy S3 bucket directory with CMS data between environments. Operations are done on server. """
with cd(env.remote_path):
tmp_dir = "s3_tmp"
sudo('rm -rf %s' % tmp_dir, warn_only=True, user=env.remote_user)
sudo('mkdir %s' % tmp_dir, user=env.remote_user)
sudo('s3cmd --recursive get s3://%s/upload/ %s --secret_key=%s --access_key=%s' % (
src_bucket_name, tmp_dir, src_bucket_secret_key, src_bucket_access_key),
user=env.remote_user)
sudo('s3cmd --recursive put %s/ s3://%s/upload/ --secret_key=%s --access_key=%s' % (
tmp_dir, dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key),
user=env.remote_user)
sudo('s3cmd setacl s3://%s/upload --acl-public --recursive --secret_key=%s --access_key=%s' % (
dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key),
user=env.remote_user)
# cleanup
sudo('rm -rf %s' % tmp_dir, warn_only=True, user=env.remote_user) | [
"def",
"copy_s3_bucket",
"(",
"src_bucket_name",
",",
"src_bucket_secret_key",
",",
"src_bucket_access_key",
",",
"dst_bucket_name",
",",
"dst_bucket_secret_key",
",",
"dst_bucket_access_key",
")",
":",
"with",
"cd",
"(",
"env",
".",
"remote_path",
")",
":",
"tmp_dir",
"=",
"\"s3_tmp\"",
"sudo",
"(",
"'rm -rf %s'",
"%",
"tmp_dir",
",",
"warn_only",
"=",
"True",
",",
"user",
"=",
"env",
".",
"remote_user",
")",
"sudo",
"(",
"'mkdir %s'",
"%",
"tmp_dir",
",",
"user",
"=",
"env",
".",
"remote_user",
")",
"sudo",
"(",
"'s3cmd --recursive get s3://%s/upload/ %s --secret_key=%s --access_key=%s'",
"%",
"(",
"src_bucket_name",
",",
"tmp_dir",
",",
"src_bucket_secret_key",
",",
"src_bucket_access_key",
")",
",",
"user",
"=",
"env",
".",
"remote_user",
")",
"sudo",
"(",
"'s3cmd --recursive put %s/ s3://%s/upload/ --secret_key=%s --access_key=%s'",
"%",
"(",
"tmp_dir",
",",
"dst_bucket_name",
",",
"dst_bucket_secret_key",
",",
"dst_bucket_access_key",
")",
",",
"user",
"=",
"env",
".",
"remote_user",
")",
"sudo",
"(",
"'s3cmd setacl s3://%s/upload --acl-public --recursive --secret_key=%s --access_key=%s'",
"%",
"(",
"dst_bucket_name",
",",
"dst_bucket_secret_key",
",",
"dst_bucket_access_key",
")",
",",
"user",
"=",
"env",
".",
"remote_user",
")",
"# cleanup",
"sudo",
"(",
"'rm -rf %s'",
"%",
"tmp_dir",
",",
"warn_only",
"=",
"True",
",",
"user",
"=",
"env",
".",
"remote_user",
")"
] | Copy S3 bucket directory with CMS data between environments. Operations are done on server. | [
"Copy",
"S3",
"bucket",
"directory",
"with",
"CMS",
"data",
"between",
"environments",
".",
"Operations",
"are",
"done",
"on",
"server",
"."
] | 4aa105e7b33f379e8f09111497c0e427b189c36c | https://github.com/ArabellaTech/ydcommon/blob/4aa105e7b33f379e8f09111497c0e427b189c36c/ydcommon/fab.py#L324-L342 |
247,773 | theonion/influxer | influxer/wsgi.py | send_point_data | def send_point_data(events, additional):
"""creates data point payloads and sends them to influxdb
"""
bodies = {}
for (site, content_id), count in events.items():
if not len(site) or not len(content_id):
continue
# influxdb will take an array of arrays of values, cutting down on the number of requests
# needed to be sent to it wo write data
bodies.setdefault(site, [])
# get additional info
event, path = additional.get((site, content_id), (None, None))
# append the point
bodies[site].append([content_id, event, path, count])
for site, points in bodies.items():
# send payload to influxdb
try:
data = [{
"name": site,
"columns": ["content_id", "event", "path", "value"],
"points": points,
}]
INFLUXDB_CLIENT.write_points(data)
except Exception as e:
LOGGER.exception(e) | python | def send_point_data(events, additional):
"""creates data point payloads and sends them to influxdb
"""
bodies = {}
for (site, content_id), count in events.items():
if not len(site) or not len(content_id):
continue
# influxdb will take an array of arrays of values, cutting down on the number of requests
# needed to be sent to it wo write data
bodies.setdefault(site, [])
# get additional info
event, path = additional.get((site, content_id), (None, None))
# append the point
bodies[site].append([content_id, event, path, count])
for site, points in bodies.items():
# send payload to influxdb
try:
data = [{
"name": site,
"columns": ["content_id", "event", "path", "value"],
"points": points,
}]
INFLUXDB_CLIENT.write_points(data)
except Exception as e:
LOGGER.exception(e) | [
"def",
"send_point_data",
"(",
"events",
",",
"additional",
")",
":",
"bodies",
"=",
"{",
"}",
"for",
"(",
"site",
",",
"content_id",
")",
",",
"count",
"in",
"events",
".",
"items",
"(",
")",
":",
"if",
"not",
"len",
"(",
"site",
")",
"or",
"not",
"len",
"(",
"content_id",
")",
":",
"continue",
"# influxdb will take an array of arrays of values, cutting down on the number of requests",
"# needed to be sent to it wo write data",
"bodies",
".",
"setdefault",
"(",
"site",
",",
"[",
"]",
")",
"# get additional info",
"event",
",",
"path",
"=",
"additional",
".",
"get",
"(",
"(",
"site",
",",
"content_id",
")",
",",
"(",
"None",
",",
"None",
")",
")",
"# append the point",
"bodies",
"[",
"site",
"]",
".",
"append",
"(",
"[",
"content_id",
",",
"event",
",",
"path",
",",
"count",
"]",
")",
"for",
"site",
",",
"points",
"in",
"bodies",
".",
"items",
"(",
")",
":",
"# send payload to influxdb",
"try",
":",
"data",
"=",
"[",
"{",
"\"name\"",
":",
"site",
",",
"\"columns\"",
":",
"[",
"\"content_id\"",
",",
"\"event\"",
",",
"\"path\"",
",",
"\"value\"",
"]",
",",
"\"points\"",
":",
"points",
",",
"}",
"]",
"INFLUXDB_CLIENT",
".",
"write_points",
"(",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")"
] | creates data point payloads and sends them to influxdb | [
"creates",
"data",
"point",
"payloads",
"and",
"sends",
"them",
"to",
"influxdb"
] | bdc6e4770d1e37c21a785881c9c50f4c767b34cc | https://github.com/theonion/influxer/blob/bdc6e4770d1e37c21a785881c9c50f4c767b34cc/influxer/wsgi.py#L74-L102 |
247,774 | theonion/influxer | influxer/wsgi.py | send_trending_data | def send_trending_data(events):
"""creates data point payloads for trending data to influxdb
"""
bodies = {}
# sort the values
top_hits = sorted(
[(key, count) for key, count in events.items()],
key=lambda x: x[1],
reverse=True
)[:100]
# build up points to be written
for (site, content_id), count in top_hits:
if not len(site) or not re.match(CONTENT_ID_REGEX, content_id):
continue
# add point
bodies.setdefault(site, [])
bodies[site].append([content_id, count])
for site, points in bodies.items():
# create name
name = "{}_trending".format(site)
# send payload to influxdb
try:
data = [{
"name": name,
"columns": ["content_id", "value"],
"points": points,
}]
INFLUXDB_CLIENT.write_points(data)
except Exception as e:
LOGGER.exception(e) | python | def send_trending_data(events):
"""creates data point payloads for trending data to influxdb
"""
bodies = {}
# sort the values
top_hits = sorted(
[(key, count) for key, count in events.items()],
key=lambda x: x[1],
reverse=True
)[:100]
# build up points to be written
for (site, content_id), count in top_hits:
if not len(site) or not re.match(CONTENT_ID_REGEX, content_id):
continue
# add point
bodies.setdefault(site, [])
bodies[site].append([content_id, count])
for site, points in bodies.items():
# create name
name = "{}_trending".format(site)
# send payload to influxdb
try:
data = [{
"name": name,
"columns": ["content_id", "value"],
"points": points,
}]
INFLUXDB_CLIENT.write_points(data)
except Exception as e:
LOGGER.exception(e) | [
"def",
"send_trending_data",
"(",
"events",
")",
":",
"bodies",
"=",
"{",
"}",
"# sort the values",
"top_hits",
"=",
"sorted",
"(",
"[",
"(",
"key",
",",
"count",
")",
"for",
"key",
",",
"count",
"in",
"events",
".",
"items",
"(",
")",
"]",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"reverse",
"=",
"True",
")",
"[",
":",
"100",
"]",
"# build up points to be written",
"for",
"(",
"site",
",",
"content_id",
")",
",",
"count",
"in",
"top_hits",
":",
"if",
"not",
"len",
"(",
"site",
")",
"or",
"not",
"re",
".",
"match",
"(",
"CONTENT_ID_REGEX",
",",
"content_id",
")",
":",
"continue",
"# add point",
"bodies",
".",
"setdefault",
"(",
"site",
",",
"[",
"]",
")",
"bodies",
"[",
"site",
"]",
".",
"append",
"(",
"[",
"content_id",
",",
"count",
"]",
")",
"for",
"site",
",",
"points",
"in",
"bodies",
".",
"items",
"(",
")",
":",
"# create name",
"name",
"=",
"\"{}_trending\"",
".",
"format",
"(",
"site",
")",
"# send payload to influxdb",
"try",
":",
"data",
"=",
"[",
"{",
"\"name\"",
":",
"name",
",",
"\"columns\"",
":",
"[",
"\"content_id\"",
",",
"\"value\"",
"]",
",",
"\"points\"",
":",
"points",
",",
"}",
"]",
"INFLUXDB_CLIENT",
".",
"write_points",
"(",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")"
] | creates data point payloads for trending data to influxdb | [
"creates",
"data",
"point",
"payloads",
"for",
"trending",
"data",
"to",
"influxdb"
] | bdc6e4770d1e37c21a785881c9c50f4c767b34cc | https://github.com/theonion/influxer/blob/bdc6e4770d1e37c21a785881c9c50f4c767b34cc/influxer/wsgi.py#L105-L138 |
247,775 | theonion/influxer | influxer/wsgi.py | count_events | def count_events():
"""pulls data from the queue, tabulates it and spawns a send event
"""
# wait loop
while 1:
# sleep and let the queue build up
gevent.sleep(FLUSH_INTERVAL)
# init the data points containers
events = Counter()
additional = {}
# flush the queue
while 1:
try:
site, content_id, event, path = EVENTS_QUEUE.get_nowait()
events[(site, content_id)] += 1
if event and path:
additional[(site, content_id)] = (event, path)
except queue.Empty:
break
except Exception as e:
LOGGER.exception(e)
break
# after tabulating, spawn a new thread to send the data to influxdb
if len(events):
gevent.spawn(send_point_data, events, additional)
gevent.spawn(send_trending_data, events) | python | def count_events():
"""pulls data from the queue, tabulates it and spawns a send event
"""
# wait loop
while 1:
# sleep and let the queue build up
gevent.sleep(FLUSH_INTERVAL)
# init the data points containers
events = Counter()
additional = {}
# flush the queue
while 1:
try:
site, content_id, event, path = EVENTS_QUEUE.get_nowait()
events[(site, content_id)] += 1
if event and path:
additional[(site, content_id)] = (event, path)
except queue.Empty:
break
except Exception as e:
LOGGER.exception(e)
break
# after tabulating, spawn a new thread to send the data to influxdb
if len(events):
gevent.spawn(send_point_data, events, additional)
gevent.spawn(send_trending_data, events) | [
"def",
"count_events",
"(",
")",
":",
"# wait loop",
"while",
"1",
":",
"# sleep and let the queue build up",
"gevent",
".",
"sleep",
"(",
"FLUSH_INTERVAL",
")",
"# init the data points containers",
"events",
"=",
"Counter",
"(",
")",
"additional",
"=",
"{",
"}",
"# flush the queue",
"while",
"1",
":",
"try",
":",
"site",
",",
"content_id",
",",
"event",
",",
"path",
"=",
"EVENTS_QUEUE",
".",
"get_nowait",
"(",
")",
"events",
"[",
"(",
"site",
",",
"content_id",
")",
"]",
"+=",
"1",
"if",
"event",
"and",
"path",
":",
"additional",
"[",
"(",
"site",
",",
"content_id",
")",
"]",
"=",
"(",
"event",
",",
"path",
")",
"except",
"queue",
".",
"Empty",
":",
"break",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"break",
"# after tabulating, spawn a new thread to send the data to influxdb",
"if",
"len",
"(",
"events",
")",
":",
"gevent",
".",
"spawn",
"(",
"send_point_data",
",",
"events",
",",
"additional",
")",
"gevent",
".",
"spawn",
"(",
"send_trending_data",
",",
"events",
")"
] | pulls data from the queue, tabulates it and spawns a send event | [
"pulls",
"data",
"from",
"the",
"queue",
"tabulates",
"it",
"and",
"spawns",
"a",
"send",
"event"
] | bdc6e4770d1e37c21a785881c9c50f4c767b34cc | https://github.com/theonion/influxer/blob/bdc6e4770d1e37c21a785881c9c50f4c767b34cc/influxer/wsgi.py#L141-L169 |
247,776 | theonion/influxer | influxer/wsgi.py | content_ids | def content_ids(params):
"""does the same this as `pageviews`, except it includes content ids and then optionally filters
the response by a list of content ids passed as query params - note, this load can be a little
heavy and could take a minute
"""
# set up default values
default_from, default_to, yesterday, _ = make_default_times()
# get params
try:
series = params.get("site", [DEFAULT_SERIES])[0]
from_date = params.get("from", [default_from])[0]
to_date = params.get("to", [default_to])[0]
group_by = params.get("group_by", [DEFAULT_GROUP_BY])[0]
ids = params.get("content_id", [])
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message}), "500 Internal Error"
# check the cache
cache_key = "{}:{}:{}:{}:{}:{}:{}".format(
memcached_prefix, "contentids.json", series, from_date, to_date, group_by, ids)
try:
data = MEMCACHED_CLIENT.get(cache_key)
if data:
return data, "200 OK"
except Exception as e:
LOGGER.exception(e)
# enforce content ids
if not len(ids):
return json.dumps({"error": "you must pass at least one content id'"}), "400 Bad Request"
# parse from date
from_date = parse_datetime(from_date)
if from_date is None:
LOGGER.error("could not parse 'from'")
return json.dumps({"error": "could not parse 'from'"}), "400 Bad Request"
# parse to date
to_date = parse_datetime(to_date)
if to_date is None:
LOGGER.error("could not parse 'to'")
return json.dumps({"error": "could not parse 'to'"}), "400 Bad Request"
# influx will only keep non-aggregated data for a day, so if the from param is beyond that point
# we need to update the series name to use the rolled up values
if from_date < yesterday:
series = update_series(series, "pageviews", "content_id")
# format times
from_date = format_datetime(from_date)
to_date = format_datetime(to_date)
# start building the query
query = "SELECT content_id, sum(value) as value " \
"FROM {series} " \
"WHERE time > '{from_date}' AND time < '{to_date}' " \
"GROUP BY content_id, time({group_by}) " \
"fill(0);"
args = {"series": series, "from_date": from_date, "to_date": to_date, "group_by": group_by}
# send the request
try:
res = INFLUXDB_CLIENT.query(query.format(**args))
# capture errors and send them back along with the query (for inspection/debugging)
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message, "query": query.format(**args)}), "500 Internal Error"
# build the response object
response = flatten_response(res)
# filter by content ids
if len(ids):
for site, points in response.items():
filtered = filter(lambda p: p["content_id"] in ids, points)
response[site] = filtered
res = json.dumps(response)
# cache the response
try:
MEMCACHED_CLIENT.set(cache_key, res, time=MEMCACHED_EXPIRATION)
except Exception as e:
LOGGER.exception(e)
return res, "200 OK" | python | def content_ids(params):
"""does the same this as `pageviews`, except it includes content ids and then optionally filters
the response by a list of content ids passed as query params - note, this load can be a little
heavy and could take a minute
"""
# set up default values
default_from, default_to, yesterday, _ = make_default_times()
# get params
try:
series = params.get("site", [DEFAULT_SERIES])[0]
from_date = params.get("from", [default_from])[0]
to_date = params.get("to", [default_to])[0]
group_by = params.get("group_by", [DEFAULT_GROUP_BY])[0]
ids = params.get("content_id", [])
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message}), "500 Internal Error"
# check the cache
cache_key = "{}:{}:{}:{}:{}:{}:{}".format(
memcached_prefix, "contentids.json", series, from_date, to_date, group_by, ids)
try:
data = MEMCACHED_CLIENT.get(cache_key)
if data:
return data, "200 OK"
except Exception as e:
LOGGER.exception(e)
# enforce content ids
if not len(ids):
return json.dumps({"error": "you must pass at least one content id'"}), "400 Bad Request"
# parse from date
from_date = parse_datetime(from_date)
if from_date is None:
LOGGER.error("could not parse 'from'")
return json.dumps({"error": "could not parse 'from'"}), "400 Bad Request"
# parse to date
to_date = parse_datetime(to_date)
if to_date is None:
LOGGER.error("could not parse 'to'")
return json.dumps({"error": "could not parse 'to'"}), "400 Bad Request"
# influx will only keep non-aggregated data for a day, so if the from param is beyond that point
# we need to update the series name to use the rolled up values
if from_date < yesterday:
series = update_series(series, "pageviews", "content_id")
# format times
from_date = format_datetime(from_date)
to_date = format_datetime(to_date)
# start building the query
query = "SELECT content_id, sum(value) as value " \
"FROM {series} " \
"WHERE time > '{from_date}' AND time < '{to_date}' " \
"GROUP BY content_id, time({group_by}) " \
"fill(0);"
args = {"series": series, "from_date": from_date, "to_date": to_date, "group_by": group_by}
# send the request
try:
res = INFLUXDB_CLIENT.query(query.format(**args))
# capture errors and send them back along with the query (for inspection/debugging)
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message, "query": query.format(**args)}), "500 Internal Error"
# build the response object
response = flatten_response(res)
# filter by content ids
if len(ids):
for site, points in response.items():
filtered = filter(lambda p: p["content_id"] in ids, points)
response[site] = filtered
res = json.dumps(response)
# cache the response
try:
MEMCACHED_CLIENT.set(cache_key, res, time=MEMCACHED_EXPIRATION)
except Exception as e:
LOGGER.exception(e)
return res, "200 OK" | [
"def",
"content_ids",
"(",
"params",
")",
":",
"# set up default values",
"default_from",
",",
"default_to",
",",
"yesterday",
",",
"_",
"=",
"make_default_times",
"(",
")",
"# get params",
"try",
":",
"series",
"=",
"params",
".",
"get",
"(",
"\"site\"",
",",
"[",
"DEFAULT_SERIES",
"]",
")",
"[",
"0",
"]",
"from_date",
"=",
"params",
".",
"get",
"(",
"\"from\"",
",",
"[",
"default_from",
"]",
")",
"[",
"0",
"]",
"to_date",
"=",
"params",
".",
"get",
"(",
"\"to\"",
",",
"[",
"default_to",
"]",
")",
"[",
"0",
"]",
"group_by",
"=",
"params",
".",
"get",
"(",
"\"group_by\"",
",",
"[",
"DEFAULT_GROUP_BY",
"]",
")",
"[",
"0",
"]",
"ids",
"=",
"params",
".",
"get",
"(",
"\"content_id\"",
",",
"[",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"e",
".",
"message",
"}",
")",
",",
"\"500 Internal Error\"",
"# check the cache",
"cache_key",
"=",
"\"{}:{}:{}:{}:{}:{}:{}\"",
".",
"format",
"(",
"memcached_prefix",
",",
"\"contentids.json\"",
",",
"series",
",",
"from_date",
",",
"to_date",
",",
"group_by",
",",
"ids",
")",
"try",
":",
"data",
"=",
"MEMCACHED_CLIENT",
".",
"get",
"(",
"cache_key",
")",
"if",
"data",
":",
"return",
"data",
",",
"\"200 OK\"",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"# enforce content ids",
"if",
"not",
"len",
"(",
"ids",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"\"you must pass at least one content id'\"",
"}",
")",
",",
"\"400 Bad Request\"",
"# parse from date",
"from_date",
"=",
"parse_datetime",
"(",
"from_date",
")",
"if",
"from_date",
"is",
"None",
":",
"LOGGER",
".",
"error",
"(",
"\"could not parse 'from'\"",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"\"could not parse 'from'\"",
"}",
")",
",",
"\"400 Bad Request\"",
"# parse to date",
"to_date",
"=",
"parse_datetime",
"(",
"to_date",
")",
"if",
"to_date",
"is",
"None",
":",
"LOGGER",
".",
"error",
"(",
"\"could not parse 'to'\"",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"\"could not parse 'to'\"",
"}",
")",
",",
"\"400 Bad Request\"",
"# influx will only keep non-aggregated data for a day, so if the from param is beyond that point",
"# we need to update the series name to use the rolled up values",
"if",
"from_date",
"<",
"yesterday",
":",
"series",
"=",
"update_series",
"(",
"series",
",",
"\"pageviews\"",
",",
"\"content_id\"",
")",
"# format times",
"from_date",
"=",
"format_datetime",
"(",
"from_date",
")",
"to_date",
"=",
"format_datetime",
"(",
"to_date",
")",
"# start building the query",
"query",
"=",
"\"SELECT content_id, sum(value) as value \"",
"\"FROM {series} \"",
"\"WHERE time > '{from_date}' AND time < '{to_date}' \"",
"\"GROUP BY content_id, time({group_by}) \"",
"\"fill(0);\"",
"args",
"=",
"{",
"\"series\"",
":",
"series",
",",
"\"from_date\"",
":",
"from_date",
",",
"\"to_date\"",
":",
"to_date",
",",
"\"group_by\"",
":",
"group_by",
"}",
"# send the request",
"try",
":",
"res",
"=",
"INFLUXDB_CLIENT",
".",
"query",
"(",
"query",
".",
"format",
"(",
"*",
"*",
"args",
")",
")",
"# capture errors and send them back along with the query (for inspection/debugging)",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"e",
".",
"message",
",",
"\"query\"",
":",
"query",
".",
"format",
"(",
"*",
"*",
"args",
")",
"}",
")",
",",
"\"500 Internal Error\"",
"# build the response object",
"response",
"=",
"flatten_response",
"(",
"res",
")",
"# filter by content ids",
"if",
"len",
"(",
"ids",
")",
":",
"for",
"site",
",",
"points",
"in",
"response",
".",
"items",
"(",
")",
":",
"filtered",
"=",
"filter",
"(",
"lambda",
"p",
":",
"p",
"[",
"\"content_id\"",
"]",
"in",
"ids",
",",
"points",
")",
"response",
"[",
"site",
"]",
"=",
"filtered",
"res",
"=",
"json",
".",
"dumps",
"(",
"response",
")",
"# cache the response",
"try",
":",
"MEMCACHED_CLIENT",
".",
"set",
"(",
"cache_key",
",",
"res",
",",
"time",
"=",
"MEMCACHED_EXPIRATION",
")",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"return",
"res",
",",
"\"200 OK\""
] | does the same this as `pageviews`, except it includes content ids and then optionally filters
the response by a list of content ids passed as query params - note, this load can be a little
heavy and could take a minute | [
"does",
"the",
"same",
"this",
"as",
"pageviews",
"except",
"it",
"includes",
"content",
"ids",
"and",
"then",
"optionally",
"filters",
"the",
"response",
"by",
"a",
"list",
"of",
"content",
"ids",
"passed",
"as",
"query",
"params",
"-",
"note",
"this",
"load",
"can",
"be",
"a",
"little",
"heavy",
"and",
"could",
"take",
"a",
"minute"
] | bdc6e4770d1e37c21a785881c9c50f4c767b34cc | https://github.com/theonion/influxer/blob/bdc6e4770d1e37c21a785881c9c50f4c767b34cc/influxer/wsgi.py#L412-L499 |
247,777 | theonion/influxer | influxer/wsgi.py | trending | def trending(params):
"""gets trending content values
"""
# get params
try:
series = params.get("site", [DEFAULT_SERIES])[0]
offset = params.get("offset", [DEFAULT_GROUP_BY])[0]
limit = params.get("limit", [20])[0]
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message}), "500 Internal Error"
# check the cache
cache_key = "{}:{}:{}:{}:{}".format(memcached_prefix, "trending.json", series, offset, limit)
try:
data = MEMCACHED_CLIENT.get(cache_key)
if data:
return data, "200 OK"
except Exception as e:
LOGGER.exception(e)
# update series name
series = update_trending_series(series)
# parse the limit
try:
limit = int(limit)
except ValueError:
LOGGER.error("limit param must be an integer")
return json.dumps({"error": "limit param must be an integer"}), "400 Bad Request"
# build the query
query = "SELECT content_id, sum(value) as value " \
"FROM {series} " \
"WHERE time > now() - {offset} " \
"GROUP BY content_id;"
args = {"series": series, "offset": offset}
# send the request
try:
res = INFLUXDB_CLIENT.query(query.format(**args))
# capture errors and send them back along with the query (for inspection/debugging)
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message, "query": query.format(**args)}), "500 Internal Error"
# build the response object
response = flatten_response(res)
# limit the number of content per site
for site, points in response.items():
sorted_content = sorted(points, key=lambda p: p["value"], reverse=True)[:limit]
response[site] = sorted_content
clean_response = {}
for site, values in response.items():
clean_name = site.split("-")[0]
clean_response[clean_name] = values
res = json.dumps(clean_response)
# cache the response
try:
MEMCACHED_CLIENT.set(cache_key, res, time=MEMCACHED_EXPIRATION)
except Exception as e:
LOGGER.exception(e)
return res, "200 OK" | python | def trending(params):
"""gets trending content values
"""
# get params
try:
series = params.get("site", [DEFAULT_SERIES])[0]
offset = params.get("offset", [DEFAULT_GROUP_BY])[0]
limit = params.get("limit", [20])[0]
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message}), "500 Internal Error"
# check the cache
cache_key = "{}:{}:{}:{}:{}".format(memcached_prefix, "trending.json", series, offset, limit)
try:
data = MEMCACHED_CLIENT.get(cache_key)
if data:
return data, "200 OK"
except Exception as e:
LOGGER.exception(e)
# update series name
series = update_trending_series(series)
# parse the limit
try:
limit = int(limit)
except ValueError:
LOGGER.error("limit param must be an integer")
return json.dumps({"error": "limit param must be an integer"}), "400 Bad Request"
# build the query
query = "SELECT content_id, sum(value) as value " \
"FROM {series} " \
"WHERE time > now() - {offset} " \
"GROUP BY content_id;"
args = {"series": series, "offset": offset}
# send the request
try:
res = INFLUXDB_CLIENT.query(query.format(**args))
# capture errors and send them back along with the query (for inspection/debugging)
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message, "query": query.format(**args)}), "500 Internal Error"
# build the response object
response = flatten_response(res)
# limit the number of content per site
for site, points in response.items():
sorted_content = sorted(points, key=lambda p: p["value"], reverse=True)[:limit]
response[site] = sorted_content
clean_response = {}
for site, values in response.items():
clean_name = site.split("-")[0]
clean_response[clean_name] = values
res = json.dumps(clean_response)
# cache the response
try:
MEMCACHED_CLIENT.set(cache_key, res, time=MEMCACHED_EXPIRATION)
except Exception as e:
LOGGER.exception(e)
return res, "200 OK" | [
"def",
"trending",
"(",
"params",
")",
":",
"# get params",
"try",
":",
"series",
"=",
"params",
".",
"get",
"(",
"\"site\"",
",",
"[",
"DEFAULT_SERIES",
"]",
")",
"[",
"0",
"]",
"offset",
"=",
"params",
".",
"get",
"(",
"\"offset\"",
",",
"[",
"DEFAULT_GROUP_BY",
"]",
")",
"[",
"0",
"]",
"limit",
"=",
"params",
".",
"get",
"(",
"\"limit\"",
",",
"[",
"20",
"]",
")",
"[",
"0",
"]",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"e",
".",
"message",
"}",
")",
",",
"\"500 Internal Error\"",
"# check the cache",
"cache_key",
"=",
"\"{}:{}:{}:{}:{}\"",
".",
"format",
"(",
"memcached_prefix",
",",
"\"trending.json\"",
",",
"series",
",",
"offset",
",",
"limit",
")",
"try",
":",
"data",
"=",
"MEMCACHED_CLIENT",
".",
"get",
"(",
"cache_key",
")",
"if",
"data",
":",
"return",
"data",
",",
"\"200 OK\"",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"# update series name",
"series",
"=",
"update_trending_series",
"(",
"series",
")",
"# parse the limit",
"try",
":",
"limit",
"=",
"int",
"(",
"limit",
")",
"except",
"ValueError",
":",
"LOGGER",
".",
"error",
"(",
"\"limit param must be an integer\"",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"\"limit param must be an integer\"",
"}",
")",
",",
"\"400 Bad Request\"",
"# build the query",
"query",
"=",
"\"SELECT content_id, sum(value) as value \"",
"\"FROM {series} \"",
"\"WHERE time > now() - {offset} \"",
"\"GROUP BY content_id;\"",
"args",
"=",
"{",
"\"series\"",
":",
"series",
",",
"\"offset\"",
":",
"offset",
"}",
"# send the request",
"try",
":",
"res",
"=",
"INFLUXDB_CLIENT",
".",
"query",
"(",
"query",
".",
"format",
"(",
"*",
"*",
"args",
")",
")",
"# capture errors and send them back along with the query (for inspection/debugging)",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"error\"",
":",
"e",
".",
"message",
",",
"\"query\"",
":",
"query",
".",
"format",
"(",
"*",
"*",
"args",
")",
"}",
")",
",",
"\"500 Internal Error\"",
"# build the response object",
"response",
"=",
"flatten_response",
"(",
"res",
")",
"# limit the number of content per site",
"for",
"site",
",",
"points",
"in",
"response",
".",
"items",
"(",
")",
":",
"sorted_content",
"=",
"sorted",
"(",
"points",
",",
"key",
"=",
"lambda",
"p",
":",
"p",
"[",
"\"value\"",
"]",
",",
"reverse",
"=",
"True",
")",
"[",
":",
"limit",
"]",
"response",
"[",
"site",
"]",
"=",
"sorted_content",
"clean_response",
"=",
"{",
"}",
"for",
"site",
",",
"values",
"in",
"response",
".",
"items",
"(",
")",
":",
"clean_name",
"=",
"site",
".",
"split",
"(",
"\"-\"",
")",
"[",
"0",
"]",
"clean_response",
"[",
"clean_name",
"]",
"=",
"values",
"res",
"=",
"json",
".",
"dumps",
"(",
"clean_response",
")",
"# cache the response",
"try",
":",
"MEMCACHED_CLIENT",
".",
"set",
"(",
"cache_key",
",",
"res",
",",
"time",
"=",
"MEMCACHED_EXPIRATION",
")",
"except",
"Exception",
"as",
"e",
":",
"LOGGER",
".",
"exception",
"(",
"e",
")",
"return",
"res",
",",
"\"200 OK\""
] | gets trending content values | [
"gets",
"trending",
"content",
"values"
] | bdc6e4770d1e37c21a785881c9c50f4c767b34cc | https://github.com/theonion/influxer/blob/bdc6e4770d1e37c21a785881c9c50f4c767b34cc/influxer/wsgi.py#L502-L569 |
247,778 | MrKriss/vigilance | vigilance/conditions.py | maha_dist | def maha_dist(df):
"""Compute the squared Mahalanobis Distance for each row in the dataframe
Given a list of rows `x`, each with `p` elements, a vector :math:\mu of the
row means of length `p`, and the :math:pxp covarence matrix of the columns :math:\Sigma,
The returned value for each row is:
.. math::
D^{2} = (x - \mu)^{T} \Sigma^{-1} (x - \mu)
Args:
df: The input DataFrame
Returns:
Series: The squared Mahalanobis Distance for each row
Notes:
This implimentation is based on the `R function`_ for the same mahalanobis calculation
.. _R function:
https://stat.ethz.ch/R-manual/R-devel/library/stats/html/mahalanobis.html
"""
mean = df.mean()
S_1 = np.linalg.inv(df.cov())
def fun(row):
A = np.dot((row.T - mean), S_1)
return np.dot(A, (row-mean))
return df.apply(fun, axis=1) | python | def maha_dist(df):
"""Compute the squared Mahalanobis Distance for each row in the dataframe
Given a list of rows `x`, each with `p` elements, a vector :math:\mu of the
row means of length `p`, and the :math:pxp covarence matrix of the columns :math:\Sigma,
The returned value for each row is:
.. math::
D^{2} = (x - \mu)^{T} \Sigma^{-1} (x - \mu)
Args:
df: The input DataFrame
Returns:
Series: The squared Mahalanobis Distance for each row
Notes:
This implimentation is based on the `R function`_ for the same mahalanobis calculation
.. _R function:
https://stat.ethz.ch/R-manual/R-devel/library/stats/html/mahalanobis.html
"""
mean = df.mean()
S_1 = np.linalg.inv(df.cov())
def fun(row):
A = np.dot((row.T - mean), S_1)
return np.dot(A, (row-mean))
return df.apply(fun, axis=1) | [
"def",
"maha_dist",
"(",
"df",
")",
":",
"mean",
"=",
"df",
".",
"mean",
"(",
")",
"S_1",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"df",
".",
"cov",
"(",
")",
")",
"def",
"fun",
"(",
"row",
")",
":",
"A",
"=",
"np",
".",
"dot",
"(",
"(",
"row",
".",
"T",
"-",
"mean",
")",
",",
"S_1",
")",
"return",
"np",
".",
"dot",
"(",
"A",
",",
"(",
"row",
"-",
"mean",
")",
")",
"return",
"df",
".",
"apply",
"(",
"fun",
",",
"axis",
"=",
"1",
")"
] | Compute the squared Mahalanobis Distance for each row in the dataframe
Given a list of rows `x`, each with `p` elements, a vector :math:\mu of the
row means of length `p`, and the :math:pxp covarence matrix of the columns :math:\Sigma,
The returned value for each row is:
.. math::
D^{2} = (x - \mu)^{T} \Sigma^{-1} (x - \mu)
Args:
df: The input DataFrame
Returns:
Series: The squared Mahalanobis Distance for each row
Notes:
This implimentation is based on the `R function`_ for the same mahalanobis calculation
.. _R function:
https://stat.ethz.ch/R-manual/R-devel/library/stats/html/mahalanobis.html | [
"Compute",
"the",
"squared",
"Mahalanobis",
"Distance",
"for",
"each",
"row",
"in",
"the",
"dataframe"
] | 2946b09f524c042c12d796f111f287866e7a3c67 | https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/conditions.py#L12-L44 |
247,779 | MrKriss/vigilance | vigilance/conditions.py | within_n_sds | def within_n_sds(n, series):
"""Return true if all values in sequence are within n SDs"""
z_score = (series - series.mean()) / series.std()
return (z_score.abs() <= n).all() | python | def within_n_sds(n, series):
"""Return true if all values in sequence are within n SDs"""
z_score = (series - series.mean()) / series.std()
return (z_score.abs() <= n).all() | [
"def",
"within_n_sds",
"(",
"n",
",",
"series",
")",
":",
"z_score",
"=",
"(",
"series",
"-",
"series",
".",
"mean",
"(",
")",
")",
"/",
"series",
".",
"std",
"(",
")",
"return",
"(",
"z_score",
".",
"abs",
"(",
")",
"<=",
"n",
")",
".",
"all",
"(",
")"
] | Return true if all values in sequence are within n SDs | [
"Return",
"true",
"if",
"all",
"values",
"in",
"sequence",
"are",
"within",
"n",
"SDs"
] | 2946b09f524c042c12d796f111f287866e7a3c67 | https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/conditions.py#L47-L50 |
247,780 | MrKriss/vigilance | vigilance/conditions.py | within_n_mads | def within_n_mads(n, series):
"""Return true if all values in sequence are within n MADs"""
mad_score = (series - series.mean()) / series.mad()
return (mad_score.abs() <= n).all() | python | def within_n_mads(n, series):
"""Return true if all values in sequence are within n MADs"""
mad_score = (series - series.mean()) / series.mad()
return (mad_score.abs() <= n).all() | [
"def",
"within_n_mads",
"(",
"n",
",",
"series",
")",
":",
"mad_score",
"=",
"(",
"series",
"-",
"series",
".",
"mean",
"(",
")",
")",
"/",
"series",
".",
"mad",
"(",
")",
"return",
"(",
"mad_score",
".",
"abs",
"(",
")",
"<=",
"n",
")",
".",
"all",
"(",
")"
] | Return true if all values in sequence are within n MADs | [
"Return",
"true",
"if",
"all",
"values",
"in",
"sequence",
"are",
"within",
"n",
"MADs"
] | 2946b09f524c042c12d796f111f287866e7a3c67 | https://github.com/MrKriss/vigilance/blob/2946b09f524c042c12d796f111f287866e7a3c67/vigilance/conditions.py#L53-L56 |
247,781 | tsroten/ticktock | ticktock.py | open | def open(filename, flag='c', protocol=None, writeback=False,
maxsize=DEFAULT_MAXSIZE, timeout=DEFAULT_TIMEOUT):
"""Open a database file as a persistent dictionary.
The persistent dictionary file is opened using :func:`dbm.open`, so
performance will depend on which :mod:`dbm` modules are installed.
:func:`open` chooses to open a :class:`Shelf <shelve.Shelf>`,
:class:`LRUShelf`, :class:`TimeoutShelf`, or :class:`LRUTimeoutShelf`
depending on the values of keyword arguments *maxsize* and *timeout*.
A :data:`None` value for *maxsize* and *timeout* will disable the LRU
cache management and automatic data timeout features respectively.
:param filename: The base filename for the underlying database that is
passed to :func:`dbm.open`.
:param flag: The flag to pass to :func:`dbm.open`.
:param protocol: The pickle protocol to pass to :func:`pickle.dump`.
:param writeback: Whether or not to write back all accessed entries on
:meth:`Shelf.sync <shelve.Shelf.sync>` and
:meth:`Shelf.close <shelve.Shelf.close>`
:type writeback: bool
:param maxsize: The maximum size the container is allowed to grow to.
``0`` means that no size limit is enforced. :data:`None` means that
LRU cache management is disabled.
:type maxsize: integer or :data:`None`
:param timeout: The default timeout value for data (in seconds). ``0``
means that the data never expires. :data:`None` means that automatic
timeout features will be disabled.
:type timeout: integer or :data:`None`
:return: A shelf
:rtype: :class:`~shelve.Shelf`, :class:`LRUShelf`, :class:`TimeoutShelf`,
or :class:`LRUTimeoutShelf`
"""
import dbm
dict = dbm.open(filename, flag)
if maxsize is None and timeout is None:
return Shelf(dict, protocol, writeback)
elif maxsize is None:
return TimeoutShelf(dict, protocol, writeback, timeout=timeout)
elif timeout is None:
return LRUShelf(dict, protocol, writeback, maxsize=maxsize)
return LRUTimeoutShelf(dict, protocol, writeback, timeout=timeout,
maxsize=maxsize) | python | def open(filename, flag='c', protocol=None, writeback=False,
maxsize=DEFAULT_MAXSIZE, timeout=DEFAULT_TIMEOUT):
"""Open a database file as a persistent dictionary.
The persistent dictionary file is opened using :func:`dbm.open`, so
performance will depend on which :mod:`dbm` modules are installed.
:func:`open` chooses to open a :class:`Shelf <shelve.Shelf>`,
:class:`LRUShelf`, :class:`TimeoutShelf`, or :class:`LRUTimeoutShelf`
depending on the values of keyword arguments *maxsize* and *timeout*.
A :data:`None` value for *maxsize* and *timeout* will disable the LRU
cache management and automatic data timeout features respectively.
:param filename: The base filename for the underlying database that is
passed to :func:`dbm.open`.
:param flag: The flag to pass to :func:`dbm.open`.
:param protocol: The pickle protocol to pass to :func:`pickle.dump`.
:param writeback: Whether or not to write back all accessed entries on
:meth:`Shelf.sync <shelve.Shelf.sync>` and
:meth:`Shelf.close <shelve.Shelf.close>`
:type writeback: bool
:param maxsize: The maximum size the container is allowed to grow to.
``0`` means that no size limit is enforced. :data:`None` means that
LRU cache management is disabled.
:type maxsize: integer or :data:`None`
:param timeout: The default timeout value for data (in seconds). ``0``
means that the data never expires. :data:`None` means that automatic
timeout features will be disabled.
:type timeout: integer or :data:`None`
:return: A shelf
:rtype: :class:`~shelve.Shelf`, :class:`LRUShelf`, :class:`TimeoutShelf`,
or :class:`LRUTimeoutShelf`
"""
import dbm
dict = dbm.open(filename, flag)
if maxsize is None and timeout is None:
return Shelf(dict, protocol, writeback)
elif maxsize is None:
return TimeoutShelf(dict, protocol, writeback, timeout=timeout)
elif timeout is None:
return LRUShelf(dict, protocol, writeback, maxsize=maxsize)
return LRUTimeoutShelf(dict, protocol, writeback, timeout=timeout,
maxsize=maxsize) | [
"def",
"open",
"(",
"filename",
",",
"flag",
"=",
"'c'",
",",
"protocol",
"=",
"None",
",",
"writeback",
"=",
"False",
",",
"maxsize",
"=",
"DEFAULT_MAXSIZE",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"import",
"dbm",
"dict",
"=",
"dbm",
".",
"open",
"(",
"filename",
",",
"flag",
")",
"if",
"maxsize",
"is",
"None",
"and",
"timeout",
"is",
"None",
":",
"return",
"Shelf",
"(",
"dict",
",",
"protocol",
",",
"writeback",
")",
"elif",
"maxsize",
"is",
"None",
":",
"return",
"TimeoutShelf",
"(",
"dict",
",",
"protocol",
",",
"writeback",
",",
"timeout",
"=",
"timeout",
")",
"elif",
"timeout",
"is",
"None",
":",
"return",
"LRUShelf",
"(",
"dict",
",",
"protocol",
",",
"writeback",
",",
"maxsize",
"=",
"maxsize",
")",
"return",
"LRUTimeoutShelf",
"(",
"dict",
",",
"protocol",
",",
"writeback",
",",
"timeout",
"=",
"timeout",
",",
"maxsize",
"=",
"maxsize",
")"
] | Open a database file as a persistent dictionary.
The persistent dictionary file is opened using :func:`dbm.open`, so
performance will depend on which :mod:`dbm` modules are installed.
:func:`open` chooses to open a :class:`Shelf <shelve.Shelf>`,
:class:`LRUShelf`, :class:`TimeoutShelf`, or :class:`LRUTimeoutShelf`
depending on the values of keyword arguments *maxsize* and *timeout*.
A :data:`None` value for *maxsize* and *timeout* will disable the LRU
cache management and automatic data timeout features respectively.
:param filename: The base filename for the underlying database that is
passed to :func:`dbm.open`.
:param flag: The flag to pass to :func:`dbm.open`.
:param protocol: The pickle protocol to pass to :func:`pickle.dump`.
:param writeback: Whether or not to write back all accessed entries on
:meth:`Shelf.sync <shelve.Shelf.sync>` and
:meth:`Shelf.close <shelve.Shelf.close>`
:type writeback: bool
:param maxsize: The maximum size the container is allowed to grow to.
``0`` means that no size limit is enforced. :data:`None` means that
LRU cache management is disabled.
:type maxsize: integer or :data:`None`
:param timeout: The default timeout value for data (in seconds). ``0``
means that the data never expires. :data:`None` means that automatic
timeout features will be disabled.
:type timeout: integer or :data:`None`
:return: A shelf
:rtype: :class:`~shelve.Shelf`, :class:`LRUShelf`, :class:`TimeoutShelf`,
or :class:`LRUTimeoutShelf` | [
"Open",
"a",
"database",
"file",
"as",
"a",
"persistent",
"dictionary",
"."
] | 3c5431fff24d6f266f3f5ee31ade8696826943bd | https://github.com/tsroten/ticktock/blob/3c5431fff24d6f266f3f5ee31ade8696826943bd/ticktock.py#L372-L415 |
247,782 | tsroten/ticktock | ticktock.py | _LRUMixin._remove_add_key | def _remove_add_key(self, key):
"""Move a key to the end of the linked list and discard old entries."""
if not hasattr(self, '_queue'):
return # haven't initialized yet, so don't bother
if key in self._queue:
self._queue.remove(key)
self._queue.append(key)
if self.maxsize == 0:
return
while len(self._queue) > self.maxsize:
del self[self._queue[0]] | python | def _remove_add_key(self, key):
"""Move a key to the end of the linked list and discard old entries."""
if not hasattr(self, '_queue'):
return # haven't initialized yet, so don't bother
if key in self._queue:
self._queue.remove(key)
self._queue.append(key)
if self.maxsize == 0:
return
while len(self._queue) > self.maxsize:
del self[self._queue[0]] | [
"def",
"_remove_add_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_queue'",
")",
":",
"return",
"# haven't initialized yet, so don't bother",
"if",
"key",
"in",
"self",
".",
"_queue",
":",
"self",
".",
"_queue",
".",
"remove",
"(",
"key",
")",
"self",
".",
"_queue",
".",
"append",
"(",
"key",
")",
"if",
"self",
".",
"maxsize",
"==",
"0",
":",
"return",
"while",
"len",
"(",
"self",
".",
"_queue",
")",
">",
"self",
".",
"maxsize",
":",
"del",
"self",
"[",
"self",
".",
"_queue",
"[",
"0",
"]",
"]"
] | Move a key to the end of the linked list and discard old entries. | [
"Move",
"a",
"key",
"to",
"the",
"end",
"of",
"the",
"linked",
"list",
"and",
"discard",
"old",
"entries",
"."
] | 3c5431fff24d6f266f3f5ee31ade8696826943bd | https://github.com/tsroten/ticktock/blob/3c5431fff24d6f266f3f5ee31ade8696826943bd/ticktock.py#L66-L76 |
247,783 | tsroten/ticktock | ticktock.py | _TimeoutMixin._is_expired | def _is_expired(self, key):
"""Check if a key is expired. If so, delete the key."""
if not hasattr(self, '_index'):
return False # haven't initalized yet, so don't bother
try:
timeout = self._index[key]
except KeyError:
if self.timeout:
self._index[key] = int(time() + self.timeout)
else:
self._index[key] = None
return False
if timeout is None or timeout >= time():
return False
del self[key] # key expired, so delete it from container
return True | python | def _is_expired(self, key):
"""Check if a key is expired. If so, delete the key."""
if not hasattr(self, '_index'):
return False # haven't initalized yet, so don't bother
try:
timeout = self._index[key]
except KeyError:
if self.timeout:
self._index[key] = int(time() + self.timeout)
else:
self._index[key] = None
return False
if timeout is None or timeout >= time():
return False
del self[key] # key expired, so delete it from container
return True | [
"def",
"_is_expired",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_index'",
")",
":",
"return",
"False",
"# haven't initalized yet, so don't bother",
"try",
":",
"timeout",
"=",
"self",
".",
"_index",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"self",
".",
"timeout",
":",
"self",
".",
"_index",
"[",
"key",
"]",
"=",
"int",
"(",
"time",
"(",
")",
"+",
"self",
".",
"timeout",
")",
"else",
":",
"self",
".",
"_index",
"[",
"key",
"]",
"=",
"None",
"return",
"False",
"if",
"timeout",
"is",
"None",
"or",
"timeout",
">=",
"time",
"(",
")",
":",
"return",
"False",
"del",
"self",
"[",
"key",
"]",
"# key expired, so delete it from container",
"return",
"True"
] | Check if a key is expired. If so, delete the key. | [
"Check",
"if",
"a",
"key",
"is",
"expired",
".",
"If",
"so",
"delete",
"the",
"key",
"."
] | 3c5431fff24d6f266f3f5ee31ade8696826943bd | https://github.com/tsroten/ticktock/blob/3c5431fff24d6f266f3f5ee31ade8696826943bd/ticktock.py#L153-L168 |
247,784 | tsroten/ticktock | ticktock.py | _TimeoutMixin.set | def set(self, key, func, *args, **kwargs):
"""Return key's value if it exists, otherwise call given function.
:param key: The key to lookup/set.
:param func: A function to use if the key doesn't exist.
All other arguments and keyword arguments are passed to *func*.
"""
if key in self:
return self[key]
self[key] = value = func(*args, **kwargs)
return value | python | def set(self, key, func, *args, **kwargs):
"""Return key's value if it exists, otherwise call given function.
:param key: The key to lookup/set.
:param func: A function to use if the key doesn't exist.
All other arguments and keyword arguments are passed to *func*.
"""
if key in self:
return self[key]
self[key] = value = func(*args, **kwargs)
return value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"self",
"[",
"key",
"]",
"self",
"[",
"key",
"]",
"=",
"value",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"value"
] | Return key's value if it exists, otherwise call given function.
:param key: The key to lookup/set.
:param func: A function to use if the key doesn't exist.
All other arguments and keyword arguments are passed to *func*. | [
"Return",
"key",
"s",
"value",
"if",
"it",
"exists",
"otherwise",
"call",
"given",
"function",
"."
] | 3c5431fff24d6f266f3f5ee31ade8696826943bd | https://github.com/tsroten/ticktock/blob/3c5431fff24d6f266f3f5ee31ade8696826943bd/ticktock.py#L180-L192 |
247,785 | tsroten/ticktock | ticktock.py | _TimeoutMixin.sync | def sync(self):
"""Sync the timeout index entry with the shelf."""
if self.writeback and self.cache:
super(_TimeoutMixin, self).__delitem__(self._INDEX)
super(_TimeoutMixin, self).sync()
self.writeback = False
super(_TimeoutMixin, self).__setitem__(self._INDEX, self._index)
self.writeback = True
if hasattr(self.dict, 'sync'):
self.dict.sync() | python | def sync(self):
"""Sync the timeout index entry with the shelf."""
if self.writeback and self.cache:
super(_TimeoutMixin, self).__delitem__(self._INDEX)
super(_TimeoutMixin, self).sync()
self.writeback = False
super(_TimeoutMixin, self).__setitem__(self._INDEX, self._index)
self.writeback = True
if hasattr(self.dict, 'sync'):
self.dict.sync() | [
"def",
"sync",
"(",
"self",
")",
":",
"if",
"self",
".",
"writeback",
"and",
"self",
".",
"cache",
":",
"super",
"(",
"_TimeoutMixin",
",",
"self",
")",
".",
"__delitem__",
"(",
"self",
".",
"_INDEX",
")",
"super",
"(",
"_TimeoutMixin",
",",
"self",
")",
".",
"sync",
"(",
")",
"self",
".",
"writeback",
"=",
"False",
"super",
"(",
"_TimeoutMixin",
",",
"self",
")",
".",
"__setitem__",
"(",
"self",
".",
"_INDEX",
",",
"self",
".",
"_index",
")",
"self",
".",
"writeback",
"=",
"True",
"if",
"hasattr",
"(",
"self",
".",
"dict",
",",
"'sync'",
")",
":",
"self",
".",
"dict",
".",
"sync",
"(",
")"
] | Sync the timeout index entry with the shelf. | [
"Sync",
"the",
"timeout",
"index",
"entry",
"with",
"the",
"shelf",
"."
] | 3c5431fff24d6f266f3f5ee31ade8696826943bd | https://github.com/tsroten/ticktock/blob/3c5431fff24d6f266f3f5ee31ade8696826943bd/ticktock.py#L251-L260 |
247,786 | minhhoit/yacms | yacms/core/admin.py | DisplayableAdmin.save_model | def save_model(self, request, obj, form, change):
"""
Save model for every language so that field auto-population
is done for every each of it.
"""
super(DisplayableAdmin, self).save_model(request, obj, form, change)
if settings.USE_MODELTRANSLATION:
lang = get_language()
for code in OrderedDict(settings.LANGUAGES):
if code != lang: # Already done
try:
activate(code)
except:
pass
else:
obj.save()
activate(lang) | python | def save_model(self, request, obj, form, change):
"""
Save model for every language so that field auto-population
is done for every each of it.
"""
super(DisplayableAdmin, self).save_model(request, obj, form, change)
if settings.USE_MODELTRANSLATION:
lang = get_language()
for code in OrderedDict(settings.LANGUAGES):
if code != lang: # Already done
try:
activate(code)
except:
pass
else:
obj.save()
activate(lang) | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"super",
"(",
"DisplayableAdmin",
",",
"self",
")",
".",
"save_model",
"(",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
"if",
"settings",
".",
"USE_MODELTRANSLATION",
":",
"lang",
"=",
"get_language",
"(",
")",
"for",
"code",
"in",
"OrderedDict",
"(",
"settings",
".",
"LANGUAGES",
")",
":",
"if",
"code",
"!=",
"lang",
":",
"# Already done",
"try",
":",
"activate",
"(",
"code",
")",
"except",
":",
"pass",
"else",
":",
"obj",
".",
"save",
"(",
")",
"activate",
"(",
"lang",
")"
] | Save model for every language so that field auto-population
is done for every each of it. | [
"Save",
"model",
"for",
"every",
"language",
"so",
"that",
"field",
"auto",
"-",
"population",
"is",
"done",
"for",
"every",
"each",
"of",
"it",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L116-L132 |
247,787 | minhhoit/yacms | yacms/core/admin.py | BaseDynamicInlineAdmin.get_fields | def get_fields(self, request, obj=None):
"""
For subclasses of ``Orderable``, the ``_order`` field must
always be present and be the last field.
"""
fields = super(BaseDynamicInlineAdmin, self).get_fields(request, obj)
if issubclass(self.model, Orderable):
fields = list(fields)
try:
fields.remove("_order")
except ValueError:
pass
fields.append("_order")
return fields | python | def get_fields(self, request, obj=None):
"""
For subclasses of ``Orderable``, the ``_order`` field must
always be present and be the last field.
"""
fields = super(BaseDynamicInlineAdmin, self).get_fields(request, obj)
if issubclass(self.model, Orderable):
fields = list(fields)
try:
fields.remove("_order")
except ValueError:
pass
fields.append("_order")
return fields | [
"def",
"get_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"fields",
"=",
"super",
"(",
"BaseDynamicInlineAdmin",
",",
"self",
")",
".",
"get_fields",
"(",
"request",
",",
"obj",
")",
"if",
"issubclass",
"(",
"self",
".",
"model",
",",
"Orderable",
")",
":",
"fields",
"=",
"list",
"(",
"fields",
")",
"try",
":",
"fields",
".",
"remove",
"(",
"\"_order\"",
")",
"except",
"ValueError",
":",
"pass",
"fields",
".",
"append",
"(",
"\"_order\"",
")",
"return",
"fields"
] | For subclasses of ``Orderable``, the ``_order`` field must
always be present and be the last field. | [
"For",
"subclasses",
"of",
"Orderable",
"the",
"_order",
"field",
"must",
"always",
"be",
"present",
"and",
"be",
"the",
"last",
"field",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L146-L159 |
247,788 | minhhoit/yacms | yacms/core/admin.py | BaseDynamicInlineAdmin.get_fieldsets | def get_fieldsets(self, request, obj=None):
"""
Same as above, but for fieldsets.
"""
fieldsets = super(BaseDynamicInlineAdmin, self).get_fieldsets(
request, obj)
if issubclass(self.model, Orderable):
for fieldset in fieldsets:
fields = [f for f in list(fieldset[1]["fields"])
if not hasattr(f, "translated_field")]
try:
fields.remove("_order")
except ValueError:
pass
fieldset[1]["fields"] = fields
fieldsets[-1][1]["fields"].append("_order")
return fieldsets | python | def get_fieldsets(self, request, obj=None):
"""
Same as above, but for fieldsets.
"""
fieldsets = super(BaseDynamicInlineAdmin, self).get_fieldsets(
request, obj)
if issubclass(self.model, Orderable):
for fieldset in fieldsets:
fields = [f for f in list(fieldset[1]["fields"])
if not hasattr(f, "translated_field")]
try:
fields.remove("_order")
except ValueError:
pass
fieldset[1]["fields"] = fields
fieldsets[-1][1]["fields"].append("_order")
return fieldsets | [
"def",
"get_fieldsets",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"fieldsets",
"=",
"super",
"(",
"BaseDynamicInlineAdmin",
",",
"self",
")",
".",
"get_fieldsets",
"(",
"request",
",",
"obj",
")",
"if",
"issubclass",
"(",
"self",
".",
"model",
",",
"Orderable",
")",
":",
"for",
"fieldset",
"in",
"fieldsets",
":",
"fields",
"=",
"[",
"f",
"for",
"f",
"in",
"list",
"(",
"fieldset",
"[",
"1",
"]",
"[",
"\"fields\"",
"]",
")",
"if",
"not",
"hasattr",
"(",
"f",
",",
"\"translated_field\"",
")",
"]",
"try",
":",
"fields",
".",
"remove",
"(",
"\"_order\"",
")",
"except",
"ValueError",
":",
"pass",
"fieldset",
"[",
"1",
"]",
"[",
"\"fields\"",
"]",
"=",
"fields",
"fieldsets",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"[",
"\"fields\"",
"]",
".",
"append",
"(",
"\"_order\"",
")",
"return",
"fieldsets"
] | Same as above, but for fieldsets. | [
"Same",
"as",
"above",
"but",
"for",
"fieldsets",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L161-L177 |
247,789 | minhhoit/yacms | yacms/core/admin.py | OwnableAdmin.save_form | def save_form(self, request, form, change):
"""
Set the object's owner as the logged in user.
"""
obj = form.save(commit=False)
if obj.user_id is None:
obj.user = request.user
return super(OwnableAdmin, self).save_form(request, form, change) | python | def save_form(self, request, form, change):
"""
Set the object's owner as the logged in user.
"""
obj = form.save(commit=False)
if obj.user_id is None:
obj.user = request.user
return super(OwnableAdmin, self).save_form(request, form, change) | [
"def",
"save_form",
"(",
"self",
",",
"request",
",",
"form",
",",
"change",
")",
":",
"obj",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"if",
"obj",
".",
"user_id",
"is",
"None",
":",
"obj",
".",
"user",
"=",
"request",
".",
"user",
"return",
"super",
"(",
"OwnableAdmin",
",",
"self",
")",
".",
"save_form",
"(",
"request",
",",
"form",
",",
"change",
")"
] | Set the object's owner as the logged in user. | [
"Set",
"the",
"object",
"s",
"owner",
"as",
"the",
"logged",
"in",
"user",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L229-L236 |
247,790 | minhhoit/yacms | yacms/core/admin.py | ContentTypedAdmin.base_concrete_modeladmin | def base_concrete_modeladmin(self):
""" The class inheriting directly from ContentModelAdmin. """
candidates = [self.__class__]
while candidates:
candidate = candidates.pop()
if ContentTypedAdmin in candidate.__bases__:
return candidate
candidates.extend(candidate.__bases__)
raise Exception("Can't find base concrete ModelAdmin class.") | python | def base_concrete_modeladmin(self):
""" The class inheriting directly from ContentModelAdmin. """
candidates = [self.__class__]
while candidates:
candidate = candidates.pop()
if ContentTypedAdmin in candidate.__bases__:
return candidate
candidates.extend(candidate.__bases__)
raise Exception("Can't find base concrete ModelAdmin class.") | [
"def",
"base_concrete_modeladmin",
"(",
"self",
")",
":",
"candidates",
"=",
"[",
"self",
".",
"__class__",
"]",
"while",
"candidates",
":",
"candidate",
"=",
"candidates",
".",
"pop",
"(",
")",
"if",
"ContentTypedAdmin",
"in",
"candidate",
".",
"__bases__",
":",
"return",
"candidate",
"candidates",
".",
"extend",
"(",
"candidate",
".",
"__bases__",
")",
"raise",
"Exception",
"(",
"\"Can't find base concrete ModelAdmin class.\"",
")"
] | The class inheriting directly from ContentModelAdmin. | [
"The",
"class",
"inheriting",
"directly",
"from",
"ContentModelAdmin",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L305-L314 |
247,791 | minhhoit/yacms | yacms/core/admin.py | ContentTypedAdmin.changelist_view | def changelist_view(self, request, extra_context=None):
""" Redirect to the changelist view for subclasses. """
if self.model is not self.concrete_model:
return HttpResponseRedirect(
admin_url(self.concrete_model, "changelist"))
extra_context = extra_context or {}
extra_context["content_models"] = self.get_content_models()
return super(ContentTypedAdmin, self).changelist_view(
request, extra_context) | python | def changelist_view(self, request, extra_context=None):
""" Redirect to the changelist view for subclasses. """
if self.model is not self.concrete_model:
return HttpResponseRedirect(
admin_url(self.concrete_model, "changelist"))
extra_context = extra_context or {}
extra_context["content_models"] = self.get_content_models()
return super(ContentTypedAdmin, self).changelist_view(
request, extra_context) | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"if",
"self",
".",
"model",
"is",
"not",
"self",
".",
"concrete_model",
":",
"return",
"HttpResponseRedirect",
"(",
"admin_url",
"(",
"self",
".",
"concrete_model",
",",
"\"changelist\"",
")",
")",
"extra_context",
"=",
"extra_context",
"or",
"{",
"}",
"extra_context",
"[",
"\"content_models\"",
"]",
"=",
"self",
".",
"get_content_models",
"(",
")",
"return",
"super",
"(",
"ContentTypedAdmin",
",",
"self",
")",
".",
"changelist_view",
"(",
"request",
",",
"extra_context",
")"
] | Redirect to the changelist view for subclasses. | [
"Redirect",
"to",
"the",
"changelist",
"view",
"for",
"subclasses",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L340-L350 |
247,792 | minhhoit/yacms | yacms/core/admin.py | ContentTypedAdmin.get_content_models | def get_content_models(self):
""" Return all subclasses that are admin registered. """
models = []
for model in self.concrete_model.get_content_models():
try:
admin_url(model, "add")
except NoReverseMatch:
continue
else:
setattr(model, "meta_verbose_name", model._meta.verbose_name)
setattr(model, "add_url", admin_url(model, "add"))
models.append(model)
return models | python | def get_content_models(self):
""" Return all subclasses that are admin registered. """
models = []
for model in self.concrete_model.get_content_models():
try:
admin_url(model, "add")
except NoReverseMatch:
continue
else:
setattr(model, "meta_verbose_name", model._meta.verbose_name)
setattr(model, "add_url", admin_url(model, "add"))
models.append(model)
return models | [
"def",
"get_content_models",
"(",
"self",
")",
":",
"models",
"=",
"[",
"]",
"for",
"model",
"in",
"self",
".",
"concrete_model",
".",
"get_content_models",
"(",
")",
":",
"try",
":",
"admin_url",
"(",
"model",
",",
"\"add\"",
")",
"except",
"NoReverseMatch",
":",
"continue",
"else",
":",
"setattr",
"(",
"model",
",",
"\"meta_verbose_name\"",
",",
"model",
".",
"_meta",
".",
"verbose_name",
")",
"setattr",
"(",
"model",
",",
"\"add_url\"",
",",
"admin_url",
"(",
"model",
",",
"\"add\"",
")",
")",
"models",
".",
"append",
"(",
"model",
")",
"return",
"models"
] | Return all subclasses that are admin registered. | [
"Return",
"all",
"subclasses",
"that",
"are",
"admin",
"registered",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L352-L366 |
247,793 | minhhoit/yacms | yacms/core/admin.py | SitePermissionUserAdmin.save_model | def save_model(self, request, obj, form, change):
"""
Provides a warning if the user is an active admin with no admin access.
"""
super(SitePermissionUserAdmin, self).save_model(
request, obj, form, change)
user = self.model.objects.get(id=obj.id)
has_perms = len(user.get_all_permissions()) > 0
has_sites = SitePermission.objects.filter(user=user).count() > 0
if user.is_active and user.is_staff and not user.is_superuser and not (
has_perms and has_sites):
error(request, "The user is active but won't be able to access "
"the admin, due to no edit/site permissions being "
"selected") | python | def save_model(self, request, obj, form, change):
"""
Provides a warning if the user is an active admin with no admin access.
"""
super(SitePermissionUserAdmin, self).save_model(
request, obj, form, change)
user = self.model.objects.get(id=obj.id)
has_perms = len(user.get_all_permissions()) > 0
has_sites = SitePermission.objects.filter(user=user).count() > 0
if user.is_active and user.is_staff and not user.is_superuser and not (
has_perms and has_sites):
error(request, "The user is active but won't be able to access "
"the admin, due to no edit/site permissions being "
"selected") | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"super",
"(",
"SitePermissionUserAdmin",
",",
"self",
")",
".",
"save_model",
"(",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
"user",
"=",
"self",
".",
"model",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"obj",
".",
"id",
")",
"has_perms",
"=",
"len",
"(",
"user",
".",
"get_all_permissions",
"(",
")",
")",
">",
"0",
"has_sites",
"=",
"SitePermission",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
")",
".",
"count",
"(",
")",
">",
"0",
"if",
"user",
".",
"is_active",
"and",
"user",
".",
"is_staff",
"and",
"not",
"user",
".",
"is_superuser",
"and",
"not",
"(",
"has_perms",
"and",
"has_sites",
")",
":",
"error",
"(",
"request",
",",
"\"The user is active but won't be able to access \"",
"\"the admin, due to no edit/site permissions being \"",
"\"selected\"",
")"
] | Provides a warning if the user is an active admin with no admin access. | [
"Provides",
"a",
"warning",
"if",
"the",
"user",
"is",
"an",
"active",
"admin",
"with",
"no",
"admin",
"access",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/admin.py#L383-L396 |
247,794 | zyga/call | call/__init__.py | _PythonCall.bind | def bind(self, args, kwargs):
"""
Bind arguments and keyword arguments to the encapsulated function.
Returns a dictionary of parameters (named according to function
parameters) with the values that were bound to each name.
"""
spec = self._spec
resolution = self.resolve(args, kwargs)
params = dict(zip(spec.args, resolution.slots))
if spec.varargs:
params[spec.varargs] = resolution.varargs
if spec.varkw:
params[spec.varkw] = resolution.varkw
if spec.kwonlyargs:
params.update(resolution.kwonlyargs)
return params | python | def bind(self, args, kwargs):
"""
Bind arguments and keyword arguments to the encapsulated function.
Returns a dictionary of parameters (named according to function
parameters) with the values that were bound to each name.
"""
spec = self._spec
resolution = self.resolve(args, kwargs)
params = dict(zip(spec.args, resolution.slots))
if spec.varargs:
params[spec.varargs] = resolution.varargs
if spec.varkw:
params[spec.varkw] = resolution.varkw
if spec.kwonlyargs:
params.update(resolution.kwonlyargs)
return params | [
"def",
"bind",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"spec",
"=",
"self",
".",
"_spec",
"resolution",
"=",
"self",
".",
"resolve",
"(",
"args",
",",
"kwargs",
")",
"params",
"=",
"dict",
"(",
"zip",
"(",
"spec",
".",
"args",
",",
"resolution",
".",
"slots",
")",
")",
"if",
"spec",
".",
"varargs",
":",
"params",
"[",
"spec",
".",
"varargs",
"]",
"=",
"resolution",
".",
"varargs",
"if",
"spec",
".",
"varkw",
":",
"params",
"[",
"spec",
".",
"varkw",
"]",
"=",
"resolution",
".",
"varkw",
"if",
"spec",
".",
"kwonlyargs",
":",
"params",
".",
"update",
"(",
"resolution",
".",
"kwonlyargs",
")",
"return",
"params"
] | Bind arguments and keyword arguments to the encapsulated function.
Returns a dictionary of parameters (named according to function
parameters) with the values that were bound to each name. | [
"Bind",
"arguments",
"and",
"keyword",
"arguments",
"to",
"the",
"encapsulated",
"function",
"."
] | dcef9a5aac7f9085bd4829dd6bcedc5fc2945d87 | https://github.com/zyga/call/blob/dcef9a5aac7f9085bd4829dd6bcedc5fc2945d87/call/__init__.py#L46-L62 |
247,795 | zyga/call | call/__init__.py | _PythonCall.apply | def apply(self, args, kwargs):
"""
Replicate a call to the encapsulated function.
Unlike func(*args, **kwargs) the call is deterministic in the order
kwargs are being checked by python. In other words, it behaves exactly
the same as if typed into the repl prompt.
This is usually only a problem when a function is given two invalid
keyword arguments. In such cases func(*args, **kwargs) syntax will
result in random error on either of those invalid keyword arguments.
This is most likely caused by a temporary dictionary created by the
runtime.
For testing a OderedDictionary instance may be passed as kwargs. In
such case the call, and the error message, is fully deterministic.
This function is implemented with eval()
"""
# Construct helper locals that only contain the function to call as
# 'func', all positional arguments as 'argX' and all keyword arguments
# as 'kwX'
_locals = {'func': self._func}
if args is not None:
_locals.update({
"arg{}".format(index): args[index]
for index, value in enumerate(args)})
if kwargs is not None:
# Explicitly build a list of keyword arguments so that we never
# traverse kwargs more than once
kw_list = list(kwargs.keys())
_locals.update({
"kw{}".format(index): kwargs[key]
for index, key in enumerate(kw_list)})
# Construct the call expression string by carefully
# placing each positional and keyword arguments in right
# order that _exactly_ matches how apply() was called.
params = []
if args is not None:
params.extend([
"arg{}".format(index)
for index in range(len(args))])
if kwargs is not None:
params.extend([
"{}=kw{}".format(key, index)
for index, key in enumerate(kw_list)])
expr = "func({})".format(", ".join(params))
return eval(expr, globals(), _locals) | python | def apply(self, args, kwargs):
"""
Replicate a call to the encapsulated function.
Unlike func(*args, **kwargs) the call is deterministic in the order
kwargs are being checked by python. In other words, it behaves exactly
the same as if typed into the repl prompt.
This is usually only a problem when a function is given two invalid
keyword arguments. In such cases func(*args, **kwargs) syntax will
result in random error on either of those invalid keyword arguments.
This is most likely caused by a temporary dictionary created by the
runtime.
For testing a OderedDictionary instance may be passed as kwargs. In
such case the call, and the error message, is fully deterministic.
This function is implemented with eval()
"""
# Construct helper locals that only contain the function to call as
# 'func', all positional arguments as 'argX' and all keyword arguments
# as 'kwX'
_locals = {'func': self._func}
if args is not None:
_locals.update({
"arg{}".format(index): args[index]
for index, value in enumerate(args)})
if kwargs is not None:
# Explicitly build a list of keyword arguments so that we never
# traverse kwargs more than once
kw_list = list(kwargs.keys())
_locals.update({
"kw{}".format(index): kwargs[key]
for index, key in enumerate(kw_list)})
# Construct the call expression string by carefully
# placing each positional and keyword arguments in right
# order that _exactly_ matches how apply() was called.
params = []
if args is not None:
params.extend([
"arg{}".format(index)
for index in range(len(args))])
if kwargs is not None:
params.extend([
"{}=kw{}".format(key, index)
for index, key in enumerate(kw_list)])
expr = "func({})".format(", ".join(params))
return eval(expr, globals(), _locals) | [
"def",
"apply",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"# Construct helper locals that only contain the function to call as",
"# 'func', all positional arguments as 'argX' and all keyword arguments",
"# as 'kwX'",
"_locals",
"=",
"{",
"'func'",
":",
"self",
".",
"_func",
"}",
"if",
"args",
"is",
"not",
"None",
":",
"_locals",
".",
"update",
"(",
"{",
"\"arg{}\"",
".",
"format",
"(",
"index",
")",
":",
"args",
"[",
"index",
"]",
"for",
"index",
",",
"value",
"in",
"enumerate",
"(",
"args",
")",
"}",
")",
"if",
"kwargs",
"is",
"not",
"None",
":",
"# Explicitly build a list of keyword arguments so that we never",
"# traverse kwargs more than once",
"kw_list",
"=",
"list",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"_locals",
".",
"update",
"(",
"{",
"\"kw{}\"",
".",
"format",
"(",
"index",
")",
":",
"kwargs",
"[",
"key",
"]",
"for",
"index",
",",
"key",
"in",
"enumerate",
"(",
"kw_list",
")",
"}",
")",
"# Construct the call expression string by carefully",
"# placing each positional and keyword arguments in right",
"# order that _exactly_ matches how apply() was called.",
"params",
"=",
"[",
"]",
"if",
"args",
"is",
"not",
"None",
":",
"params",
".",
"extend",
"(",
"[",
"\"arg{}\"",
".",
"format",
"(",
"index",
")",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"args",
")",
")",
"]",
")",
"if",
"kwargs",
"is",
"not",
"None",
":",
"params",
".",
"extend",
"(",
"[",
"\"{}=kw{}\"",
".",
"format",
"(",
"key",
",",
"index",
")",
"for",
"index",
",",
"key",
"in",
"enumerate",
"(",
"kw_list",
")",
"]",
")",
"expr",
"=",
"\"func({})\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"params",
")",
")",
"return",
"eval",
"(",
"expr",
",",
"globals",
"(",
")",
",",
"_locals",
")"
] | Replicate a call to the encapsulated function.
Unlike func(*args, **kwargs) the call is deterministic in the order
kwargs are being checked by python. In other words, it behaves exactly
the same as if typed into the repl prompt.
This is usually only a problem when a function is given two invalid
keyword arguments. In such cases func(*args, **kwargs) syntax will
result in random error on either of those invalid keyword arguments.
This is most likely caused by a temporary dictionary created by the
runtime.
For testing a OderedDictionary instance may be passed as kwargs. In
such case the call, and the error message, is fully deterministic.
This function is implemented with eval() | [
"Replicate",
"a",
"call",
"to",
"the",
"encapsulated",
"function",
"."
] | dcef9a5aac7f9085bd4829dd6bcedc5fc2945d87 | https://github.com/zyga/call/blob/dcef9a5aac7f9085bd4829dd6bcedc5fc2945d87/call/__init__.py#L103-L150 |
247,796 | mrallen1/pygett | pygett/shares.py | GettShare.update | def update(self, **kwargs):
"""
Add, remove or modify a share's title.
Input:
* ``title`` The share title, if any (optional)
**NOTE**: Passing ``None`` or calling this method with an empty argument list will remove the share's title.
Output:
* None
Example::
share = client.get_share("4ddfds")
share.update(title="Example") # Set title to Example
share.update() # Remove title
"""
if 'title' in kwargs:
params = {"title": kwargs['title']}
else:
params = {"title": None}
response = GettRequest().post("/shares/%s/update?accesstoken=%s" % (self.sharename, self.user.access_token()), params)
if response.http_status == 200:
self.__init__(self.user, **response.response) | python | def update(self, **kwargs):
"""
Add, remove or modify a share's title.
Input:
* ``title`` The share title, if any (optional)
**NOTE**: Passing ``None`` or calling this method with an empty argument list will remove the share's title.
Output:
* None
Example::
share = client.get_share("4ddfds")
share.update(title="Example") # Set title to Example
share.update() # Remove title
"""
if 'title' in kwargs:
params = {"title": kwargs['title']}
else:
params = {"title": None}
response = GettRequest().post("/shares/%s/update?accesstoken=%s" % (self.sharename, self.user.access_token()), params)
if response.http_status == 200:
self.__init__(self.user, **response.response) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'title'",
"in",
"kwargs",
":",
"params",
"=",
"{",
"\"title\"",
":",
"kwargs",
"[",
"'title'",
"]",
"}",
"else",
":",
"params",
"=",
"{",
"\"title\"",
":",
"None",
"}",
"response",
"=",
"GettRequest",
"(",
")",
".",
"post",
"(",
"\"/shares/%s/update?accesstoken=%s\"",
"%",
"(",
"self",
".",
"sharename",
",",
"self",
".",
"user",
".",
"access_token",
"(",
")",
")",
",",
"params",
")",
"if",
"response",
".",
"http_status",
"==",
"200",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"user",
",",
"*",
"*",
"response",
".",
"response",
")"
] | Add, remove or modify a share's title.
Input:
* ``title`` The share title, if any (optional)
**NOTE**: Passing ``None`` or calling this method with an empty argument list will remove the share's title.
Output:
* None
Example::
share = client.get_share("4ddfds")
share.update(title="Example") # Set title to Example
share.update() # Remove title | [
"Add",
"remove",
"or",
"modify",
"a",
"share",
"s",
"title",
"."
] | 1e21f8674a3634a901af054226670174b5ce2d87 | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/shares.py#L38-L64 |
247,797 | mrallen1/pygett | pygett/shares.py | GettShare.destroy | def destroy(self):
"""
This method removes this share and all of its associated files. There is no way to recover a share or its contents
once this method has been called.
Input:
* None
Output:
* ``True``
Example::
client.get_share("4ddfds").destroy()
"""
response = GettRequest().post("/shares/%s/destroy?accesstoken=%s" % (self.sharename, self.user.access_token()), None)
if response.http_status == 200:
return True | python | def destroy(self):
"""
This method removes this share and all of its associated files. There is no way to recover a share or its contents
once this method has been called.
Input:
* None
Output:
* ``True``
Example::
client.get_share("4ddfds").destroy()
"""
response = GettRequest().post("/shares/%s/destroy?accesstoken=%s" % (self.sharename, self.user.access_token()), None)
if response.http_status == 200:
return True | [
"def",
"destroy",
"(",
"self",
")",
":",
"response",
"=",
"GettRequest",
"(",
")",
".",
"post",
"(",
"\"/shares/%s/destroy?accesstoken=%s\"",
"%",
"(",
"self",
".",
"sharename",
",",
"self",
".",
"user",
".",
"access_token",
"(",
")",
")",
",",
"None",
")",
"if",
"response",
".",
"http_status",
"==",
"200",
":",
"return",
"True"
] | This method removes this share and all of its associated files. There is no way to recover a share or its contents
once this method has been called.
Input:
* None
Output:
* ``True``
Example::
client.get_share("4ddfds").destroy() | [
"This",
"method",
"removes",
"this",
"share",
"and",
"all",
"of",
"its",
"associated",
"files",
".",
"There",
"is",
"no",
"way",
"to",
"recover",
"a",
"share",
"or",
"its",
"contents",
"once",
"this",
"method",
"has",
"been",
"called",
"."
] | 1e21f8674a3634a901af054226670174b5ce2d87 | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/shares.py#L66-L84 |
247,798 | mrallen1/pygett | pygett/shares.py | GettShare.refresh | def refresh(self):
"""
This method refreshes the object with current metadata from the Gett service.
Input:
* None
Output:
* None
Example::
share = client.get_share("4ddfds")
print share.files[0].filename # prints 'foobar'
if share.files[0].destroy():
share.refresh()
print share.files[0].filename # now prints 'barbaz'
"""
response = GettRequest().get("/shares/%s" % self.sharename)
if response.http_status == 200:
self.__init__(self.user, **response.response) | python | def refresh(self):
"""
This method refreshes the object with current metadata from the Gett service.
Input:
* None
Output:
* None
Example::
share = client.get_share("4ddfds")
print share.files[0].filename # prints 'foobar'
if share.files[0].destroy():
share.refresh()
print share.files[0].filename # now prints 'barbaz'
"""
response = GettRequest().get("/shares/%s" % self.sharename)
if response.http_status == 200:
self.__init__(self.user, **response.response) | [
"def",
"refresh",
"(",
"self",
")",
":",
"response",
"=",
"GettRequest",
"(",
")",
".",
"get",
"(",
"\"/shares/%s\"",
"%",
"self",
".",
"sharename",
")",
"if",
"response",
".",
"http_status",
"==",
"200",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"user",
",",
"*",
"*",
"response",
".",
"response",
")"
] | This method refreshes the object with current metadata from the Gett service.
Input:
* None
Output:
* None
Example::
share = client.get_share("4ddfds")
print share.files[0].filename # prints 'foobar'
if share.files[0].destroy():
share.refresh()
print share.files[0].filename # now prints 'barbaz' | [
"This",
"method",
"refreshes",
"the",
"object",
"with",
"current",
"metadata",
"from",
"the",
"Gett",
"service",
"."
] | 1e21f8674a3634a901af054226670174b5ce2d87 | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/shares.py#L86-L107 |
247,799 | KnowledgeLinks/rdfframework | rdfframework/utilities/codetimer.py | code_timer | def code_timer(reset=False):
'''Sets a global variable for tracking the timer accross multiple
files '''
global CODE_TIMER
if reset:
CODE_TIMER = CodeTimer()
else:
if CODE_TIMER is None:
return CodeTimer()
else:
return CODE_TIMER | python | def code_timer(reset=False):
'''Sets a global variable for tracking the timer accross multiple
files '''
global CODE_TIMER
if reset:
CODE_TIMER = CodeTimer()
else:
if CODE_TIMER is None:
return CodeTimer()
else:
return CODE_TIMER | [
"def",
"code_timer",
"(",
"reset",
"=",
"False",
")",
":",
"global",
"CODE_TIMER",
"if",
"reset",
":",
"CODE_TIMER",
"=",
"CodeTimer",
"(",
")",
"else",
":",
"if",
"CODE_TIMER",
"is",
"None",
":",
"return",
"CodeTimer",
"(",
")",
"else",
":",
"return",
"CODE_TIMER"
] | Sets a global variable for tracking the timer accross multiple
files | [
"Sets",
"a",
"global",
"variable",
"for",
"tracking",
"the",
"timer",
"accross",
"multiple",
"files"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/codetimer.py#L55-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.