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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
243,400
|
django-py/django-doberman
|
doberman/models.py
|
AbstractFailedAccessAttempt.expiration_time
|
def expiration_time(self):
"""
Returns the time until this access attempt is forgotten.
"""
logging_forgotten_time = configuration.behavior.login_forgotten_seconds
if logging_forgotten_time <= 0:
return None
now = timezone.now()
delta = now - self.modified
time_remaining = logging_forgotten_time - delta.seconds
return time_remaining
|
python
|
def expiration_time(self):
"""
Returns the time until this access attempt is forgotten.
"""
logging_forgotten_time = configuration.behavior.login_forgotten_seconds
if logging_forgotten_time <= 0:
return None
now = timezone.now()
delta = now - self.modified
time_remaining = logging_forgotten_time - delta.seconds
return time_remaining
|
[
"def",
"expiration_time",
"(",
"self",
")",
":",
"logging_forgotten_time",
"=",
"configuration",
".",
"behavior",
".",
"login_forgotten_seconds",
"if",
"logging_forgotten_time",
"<=",
"0",
":",
"return",
"None",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"delta",
"=",
"now",
"-",
"self",
".",
"modified",
"time_remaining",
"=",
"logging_forgotten_time",
"-",
"delta",
".",
"seconds",
"return",
"time_remaining"
] |
Returns the time until this access attempt is forgotten.
|
[
"Returns",
"the",
"time",
"until",
"this",
"access",
"attempt",
"is",
"forgotten",
"."
] |
2e5959737a1b64234ed5a179c93f96a0de1c3e5c
|
https://github.com/django-py/django-doberman/blob/2e5959737a1b64234ed5a179c93f96a0de1c3e5c/doberman/models.py#L73-L86
|
243,401
|
sarenji/pyrc
|
example.py
|
GangstaBot.bling
|
def bling(self, target, sender):
"will print yo"
if target.startswith("#"):
self.message(target, "%s: yo" % sender)
else:
self.message(sender, "yo")
|
python
|
def bling(self, target, sender):
"will print yo"
if target.startswith("#"):
self.message(target, "%s: yo" % sender)
else:
self.message(sender, "yo")
|
[
"def",
"bling",
"(",
"self",
",",
"target",
",",
"sender",
")",
":",
"if",
"target",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"self",
".",
"message",
"(",
"target",
",",
"\"%s: yo\"",
"%",
"sender",
")",
"else",
":",
"self",
".",
"message",
"(",
"sender",
",",
"\"yo\"",
")"
] |
will print yo
|
[
"will",
"print",
"yo"
] |
5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68
|
https://github.com/sarenji/pyrc/blob/5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68/example.py#L11-L16
|
243,402
|
sarenji/pyrc
|
example.py
|
GangstaBot.repeat
|
def repeat(self, target, sender, **kwargs):
"will repeat whatever yo say"
if target.startswith("#"):
self.message(target, kwargs["msg"])
else:
self.message(sender, kwargs["msg"])
|
python
|
def repeat(self, target, sender, **kwargs):
"will repeat whatever yo say"
if target.startswith("#"):
self.message(target, kwargs["msg"])
else:
self.message(sender, kwargs["msg"])
|
[
"def",
"repeat",
"(",
"self",
",",
"target",
",",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"target",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"self",
".",
"message",
"(",
"target",
",",
"kwargs",
"[",
"\"msg\"",
"]",
")",
"else",
":",
"self",
".",
"message",
"(",
"sender",
",",
"kwargs",
"[",
"\"msg\"",
"]",
")"
] |
will repeat whatever yo say
|
[
"will",
"repeat",
"whatever",
"yo",
"say"
] |
5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68
|
https://github.com/sarenji/pyrc/blob/5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68/example.py#L19-L24
|
243,403
|
sarenji/pyrc
|
example.py
|
GangstaBot.stopword
|
def stopword(self, target, sender, *args):
"""
will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message
only applies to channel messages
"""
if target.startswith("#"):
self.message(target, args[0])
|
python
|
def stopword(self, target, sender, *args):
"""
will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message
only applies to channel messages
"""
if target.startswith("#"):
self.message(target, args[0])
|
[
"def",
"stopword",
"(",
"self",
",",
"target",
",",
"sender",
",",
"*",
"args",
")",
":",
"if",
"target",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"self",
".",
"message",
"(",
"target",
",",
"args",
"[",
"0",
"]",
")"
] |
will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message
only applies to channel messages
|
[
"will",
"repeat",
"lol",
"lmao",
"rofl",
"or",
"roflmao",
"when",
"seen",
"in",
"a",
"message",
"only",
"applies",
"to",
"channel",
"messages"
] |
5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68
|
https://github.com/sarenji/pyrc/blob/5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68/example.py#L27-L33
|
243,404
|
20tab/twentytab-utils
|
twentytab/utils.py
|
compare_dicts
|
def compare_dicts(dict1, dict2):
"""
Checks if dict1 equals dict2
"""
for k, v in dict2.items():
if v != dict1[k]:
return False
return True
|
python
|
def compare_dicts(dict1, dict2):
"""
Checks if dict1 equals dict2
"""
for k, v in dict2.items():
if v != dict1[k]:
return False
return True
|
[
"def",
"compare_dicts",
"(",
"dict1",
",",
"dict2",
")",
":",
"for",
"k",
",",
"v",
"in",
"dict2",
".",
"items",
"(",
")",
":",
"if",
"v",
"!=",
"dict1",
"[",
"k",
"]",
":",
"return",
"False",
"return",
"True"
] |
Checks if dict1 equals dict2
|
[
"Checks",
"if",
"dict1",
"equals",
"dict2"
] |
e02d55b1fd848c8e11ca9b7e97a5916780544d34
|
https://github.com/20tab/twentytab-utils/blob/e02d55b1fd848c8e11ca9b7e97a5916780544d34/twentytab/utils.py#L21-L28
|
243,405
|
20tab/twentytab-utils
|
twentytab/utils.py
|
getItalianAccentedVocal
|
def getItalianAccentedVocal(vocal, acc_type="g"):
"""
It returns given vocal with grave or acute accent
"""
vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'},
'e': {'g': u'\xe8', 'a': u'\xe9'},
'i': {'g': u'\xec', 'a': u'\xed'},
'o': {'g': u'\xf2', 'a': u'\xf3'},
'u': {'g': u'\xf9', 'a': u'\xfa'}}
return vocals[vocal][acc_type]
|
python
|
def getItalianAccentedVocal(vocal, acc_type="g"):
"""
It returns given vocal with grave or acute accent
"""
vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'},
'e': {'g': u'\xe8', 'a': u'\xe9'},
'i': {'g': u'\xec', 'a': u'\xed'},
'o': {'g': u'\xf2', 'a': u'\xf3'},
'u': {'g': u'\xf9', 'a': u'\xfa'}}
return vocals[vocal][acc_type]
|
[
"def",
"getItalianAccentedVocal",
"(",
"vocal",
",",
"acc_type",
"=",
"\"g\"",
")",
":",
"vocals",
"=",
"{",
"'a'",
":",
"{",
"'g'",
":",
"u'\\xe0'",
",",
"'a'",
":",
"u'\\xe1'",
"}",
",",
"'e'",
":",
"{",
"'g'",
":",
"u'\\xe8'",
",",
"'a'",
":",
"u'\\xe9'",
"}",
",",
"'i'",
":",
"{",
"'g'",
":",
"u'\\xec'",
",",
"'a'",
":",
"u'\\xed'",
"}",
",",
"'o'",
":",
"{",
"'g'",
":",
"u'\\xf2'",
",",
"'a'",
":",
"u'\\xf3'",
"}",
",",
"'u'",
":",
"{",
"'g'",
":",
"u'\\xf9'",
",",
"'a'",
":",
"u'\\xfa'",
"}",
"}",
"return",
"vocals",
"[",
"vocal",
"]",
"[",
"acc_type",
"]"
] |
It returns given vocal with grave or acute accent
|
[
"It",
"returns",
"given",
"vocal",
"with",
"grave",
"or",
"acute",
"accent"
] |
e02d55b1fd848c8e11ca9b7e97a5916780544d34
|
https://github.com/20tab/twentytab-utils/blob/e02d55b1fd848c8e11ca9b7e97a5916780544d34/twentytab/utils.py#L31-L40
|
243,406
|
collectiveacuity/labPack
|
labpack/authentication/aws/iam.py
|
iamClient.read_certificate
|
def read_certificate(self, certificate_name):
'''
a method to retrieve the details about a server certificate
:param certificate_name: string with name of server certificate
:return: dictionary with certificate details
'''
title = '%s.read_certificate' % self.__class__.__name__
# validate inputs
input_fields = {
'certificate_name': certificate_name
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# verify existence of server certificate
if not certificate_name in self.certificate_list:
self.printer_on = False
self.list_certificates()
self.printer_on = True
if not certificate_name in self.certificate_list:
raise Exception('\nServer certificate %s does not exist.' % certificate_name)
# send request for certificate details
try:
cert_kwargs = { 'ServerCertificateName': certificate_name }
response = self.connection.get_server_certificate(**cert_kwargs)
except:
raise AWSConnectionError(title)
# construct certificate details from response
from labpack.records.time import labDT
from labpack.parsing.conversion import camelcase_to_lowercase
cert_dict = response['ServerCertificate']
cert_details = camelcase_to_lowercase(cert_dict)
for key, value in cert_details['server_certificate_metadata'].item():
cert_details.update(**{key:value})
del cert_details['server_certificate_metadata']
date_time = cert_details['expiration']
epoch_time = labDT(date_time).epoch()
cert_details['expiration'] = epoch_time
return cert_details
|
python
|
def read_certificate(self, certificate_name):
'''
a method to retrieve the details about a server certificate
:param certificate_name: string with name of server certificate
:return: dictionary with certificate details
'''
title = '%s.read_certificate' % self.__class__.__name__
# validate inputs
input_fields = {
'certificate_name': certificate_name
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# verify existence of server certificate
if not certificate_name in self.certificate_list:
self.printer_on = False
self.list_certificates()
self.printer_on = True
if not certificate_name in self.certificate_list:
raise Exception('\nServer certificate %s does not exist.' % certificate_name)
# send request for certificate details
try:
cert_kwargs = { 'ServerCertificateName': certificate_name }
response = self.connection.get_server_certificate(**cert_kwargs)
except:
raise AWSConnectionError(title)
# construct certificate details from response
from labpack.records.time import labDT
from labpack.parsing.conversion import camelcase_to_lowercase
cert_dict = response['ServerCertificate']
cert_details = camelcase_to_lowercase(cert_dict)
for key, value in cert_details['server_certificate_metadata'].item():
cert_details.update(**{key:value})
del cert_details['server_certificate_metadata']
date_time = cert_details['expiration']
epoch_time = labDT(date_time).epoch()
cert_details['expiration'] = epoch_time
return cert_details
|
[
"def",
"read_certificate",
"(",
"self",
",",
"certificate_name",
")",
":",
"title",
"=",
"'%s.read_certificate'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
"'certificate_name'",
":",
"certificate_name",
"}",
"for",
"key",
",",
"value",
"in",
"input_fields",
".",
"items",
"(",
")",
":",
"object_title",
"=",
"'%s(%s=%s)'",
"%",
"(",
"title",
",",
"key",
",",
"str",
"(",
"value",
")",
")",
"self",
".",
"fields",
".",
"validate",
"(",
"value",
",",
"'.%s'",
"%",
"key",
",",
"object_title",
")",
"# verify existence of server certificate",
"if",
"not",
"certificate_name",
"in",
"self",
".",
"certificate_list",
":",
"self",
".",
"printer_on",
"=",
"False",
"self",
".",
"list_certificates",
"(",
")",
"self",
".",
"printer_on",
"=",
"True",
"if",
"not",
"certificate_name",
"in",
"self",
".",
"certificate_list",
":",
"raise",
"Exception",
"(",
"'\\nServer certificate %s does not exist.'",
"%",
"certificate_name",
")",
"# send request for certificate details",
"try",
":",
"cert_kwargs",
"=",
"{",
"'ServerCertificateName'",
":",
"certificate_name",
"}",
"response",
"=",
"self",
".",
"connection",
".",
"get_server_certificate",
"(",
"*",
"*",
"cert_kwargs",
")",
"except",
":",
"raise",
"AWSConnectionError",
"(",
"title",
")",
"# construct certificate details from response",
"from",
"labpack",
".",
"records",
".",
"time",
"import",
"labDT",
"from",
"labpack",
".",
"parsing",
".",
"conversion",
"import",
"camelcase_to_lowercase",
"cert_dict",
"=",
"response",
"[",
"'ServerCertificate'",
"]",
"cert_details",
"=",
"camelcase_to_lowercase",
"(",
"cert_dict",
")",
"for",
"key",
",",
"value",
"in",
"cert_details",
"[",
"'server_certificate_metadata'",
"]",
".",
"item",
"(",
")",
":",
"cert_details",
".",
"update",
"(",
"*",
"*",
"{",
"key",
":",
"value",
"}",
")",
"del",
"cert_details",
"[",
"'server_certificate_metadata'",
"]",
"date_time",
"=",
"cert_details",
"[",
"'expiration'",
"]",
"epoch_time",
"=",
"labDT",
"(",
"date_time",
")",
".",
"epoch",
"(",
")",
"cert_details",
"[",
"'expiration'",
"]",
"=",
"epoch_time",
"return",
"cert_details"
] |
a method to retrieve the details about a server certificate
:param certificate_name: string with name of server certificate
:return: dictionary with certificate details
|
[
"a",
"method",
"to",
"retrieve",
"the",
"details",
"about",
"a",
"server",
"certificate"
] |
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
|
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/authentication/aws/iam.py#L164-L210
|
243,407
|
stephanepechard/projy
|
projy/TerminalView.py
|
TerminalView.text_in_color
|
def text_in_color(self, message, color_code):
""" Print with a beautiful color. See codes at the top of this file. """
return self.term.color(color_code) + message + self.term.normal
|
python
|
def text_in_color(self, message, color_code):
""" Print with a beautiful color. See codes at the top of this file. """
return self.term.color(color_code) + message + self.term.normal
|
[
"def",
"text_in_color",
"(",
"self",
",",
"message",
",",
"color_code",
")",
":",
"return",
"self",
".",
"term",
".",
"color",
"(",
"color_code",
")",
"+",
"message",
"+",
"self",
".",
"term",
".",
"normal"
] |
Print with a beautiful color. See codes at the top of this file.
|
[
"Print",
"with",
"a",
"beautiful",
"color",
".",
"See",
"codes",
"at",
"the",
"top",
"of",
"this",
"file",
"."
] |
3146b0e3c207b977e1b51fcb33138746dae83c23
|
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/TerminalView.py#L39-L41
|
243,408
|
SkyLothar/shcmd
|
shcmd/tar.py
|
TarGenerator.files
|
def files(self):
"""files that will be add to tar file later
should be tuple, list or generator that returns strings
"""
ios_names = [info.name for info in self._ios_to_add.keys()]
return set(self.files_to_add + ios_names)
|
python
|
def files(self):
"""files that will be add to tar file later
should be tuple, list or generator that returns strings
"""
ios_names = [info.name for info in self._ios_to_add.keys()]
return set(self.files_to_add + ios_names)
|
[
"def",
"files",
"(",
"self",
")",
":",
"ios_names",
"=",
"[",
"info",
".",
"name",
"for",
"info",
"in",
"self",
".",
"_ios_to_add",
".",
"keys",
"(",
")",
"]",
"return",
"set",
"(",
"self",
".",
"files_to_add",
"+",
"ios_names",
")"
] |
files that will be add to tar file later
should be tuple, list or generator that returns strings
|
[
"files",
"that",
"will",
"be",
"add",
"to",
"tar",
"file",
"later",
"should",
"be",
"tuple",
"list",
"or",
"generator",
"that",
"returns",
"strings"
] |
d8cad6311a4da7ef09f3419c86b58e30388b7ee3
|
https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/tar.py#L44-L49
|
243,409
|
SkyLothar/shcmd
|
shcmd/tar.py
|
TarGenerator.add_fileobj
|
def add_fileobj(self, fname, fcontent):
"""add file like object, it will be add to tar file later
:param fname: name in tar file
:param fcontent: content. bytes, string, BytesIO or StringIO
"""
tar_info = tarfile.TarInfo(fname)
if isinstance(fcontent, io.BytesIO):
tar_info.size = len(fcontent.getvalue())
elif isinstance(fcontent, io.StringIO):
tar_info.size = len(fcontent.getvalue())
fcontent = io.BytesIO(fcontent.getvalue().encode("utf8"))
else:
if hasattr(fcontent, "readable"):
fcontent = fcontent
tar_info.size = len(fcontent)
if isinstance(fcontent, str):
fcontent = fcontent.encode("utf8")
fcontent = io.BytesIO(fcontent)
self._ios_to_add[tar_info] = fcontent
|
python
|
def add_fileobj(self, fname, fcontent):
"""add file like object, it will be add to tar file later
:param fname: name in tar file
:param fcontent: content. bytes, string, BytesIO or StringIO
"""
tar_info = tarfile.TarInfo(fname)
if isinstance(fcontent, io.BytesIO):
tar_info.size = len(fcontent.getvalue())
elif isinstance(fcontent, io.StringIO):
tar_info.size = len(fcontent.getvalue())
fcontent = io.BytesIO(fcontent.getvalue().encode("utf8"))
else:
if hasattr(fcontent, "readable"):
fcontent = fcontent
tar_info.size = len(fcontent)
if isinstance(fcontent, str):
fcontent = fcontent.encode("utf8")
fcontent = io.BytesIO(fcontent)
self._ios_to_add[tar_info] = fcontent
|
[
"def",
"add_fileobj",
"(",
"self",
",",
"fname",
",",
"fcontent",
")",
":",
"tar_info",
"=",
"tarfile",
".",
"TarInfo",
"(",
"fname",
")",
"if",
"isinstance",
"(",
"fcontent",
",",
"io",
".",
"BytesIO",
")",
":",
"tar_info",
".",
"size",
"=",
"len",
"(",
"fcontent",
".",
"getvalue",
"(",
")",
")",
"elif",
"isinstance",
"(",
"fcontent",
",",
"io",
".",
"StringIO",
")",
":",
"tar_info",
".",
"size",
"=",
"len",
"(",
"fcontent",
".",
"getvalue",
"(",
")",
")",
"fcontent",
"=",
"io",
".",
"BytesIO",
"(",
"fcontent",
".",
"getvalue",
"(",
")",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"else",
":",
"if",
"hasattr",
"(",
"fcontent",
",",
"\"readable\"",
")",
":",
"fcontent",
"=",
"fcontent",
"tar_info",
".",
"size",
"=",
"len",
"(",
"fcontent",
")",
"if",
"isinstance",
"(",
"fcontent",
",",
"str",
")",
":",
"fcontent",
"=",
"fcontent",
".",
"encode",
"(",
"\"utf8\"",
")",
"fcontent",
"=",
"io",
".",
"BytesIO",
"(",
"fcontent",
")",
"self",
".",
"_ios_to_add",
"[",
"tar_info",
"]",
"=",
"fcontent"
] |
add file like object, it will be add to tar file later
:param fname: name in tar file
:param fcontent: content. bytes, string, BytesIO or StringIO
|
[
"add",
"file",
"like",
"object",
"it",
"will",
"be",
"add",
"to",
"tar",
"file",
"later"
] |
d8cad6311a4da7ef09f3419c86b58e30388b7ee3
|
https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/tar.py#L59-L78
|
243,410
|
SkyLothar/shcmd
|
shcmd/tar.py
|
TarGenerator.generate
|
def generate(self):
"""generate tar file
..Usage::
>>> tarfile = b"".join(data for data in tg.generate())
"""
if self._tar_buffer.tell():
self._tar_buffer.seek(0, 0)
yield self._tar_buffer.read()
for fname in self._files_to_add:
last = self._tar_buffer.tell()
self._tar_obj.add(fname)
self._tar_buffer.seek(last, os.SEEK_SET)
data = self._tar_buffer.read()
yield data
for info, content in self._ios_to_add.items():
last = self._tar_buffer.tell()
self._tar_obj.addfile(info, content)
self._tar_buffer.seek(last, os.SEEK_SET)
data = self._tar_buffer.read()
yield data
self._tar_obj.close()
yield self._tar_buffer.read()
self._generated = True
|
python
|
def generate(self):
"""generate tar file
..Usage::
>>> tarfile = b"".join(data for data in tg.generate())
"""
if self._tar_buffer.tell():
self._tar_buffer.seek(0, 0)
yield self._tar_buffer.read()
for fname in self._files_to_add:
last = self._tar_buffer.tell()
self._tar_obj.add(fname)
self._tar_buffer.seek(last, os.SEEK_SET)
data = self._tar_buffer.read()
yield data
for info, content in self._ios_to_add.items():
last = self._tar_buffer.tell()
self._tar_obj.addfile(info, content)
self._tar_buffer.seek(last, os.SEEK_SET)
data = self._tar_buffer.read()
yield data
self._tar_obj.close()
yield self._tar_buffer.read()
self._generated = True
|
[
"def",
"generate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tar_buffer",
".",
"tell",
"(",
")",
":",
"self",
".",
"_tar_buffer",
".",
"seek",
"(",
"0",
",",
"0",
")",
"yield",
"self",
".",
"_tar_buffer",
".",
"read",
"(",
")",
"for",
"fname",
"in",
"self",
".",
"_files_to_add",
":",
"last",
"=",
"self",
".",
"_tar_buffer",
".",
"tell",
"(",
")",
"self",
".",
"_tar_obj",
".",
"add",
"(",
"fname",
")",
"self",
".",
"_tar_buffer",
".",
"seek",
"(",
"last",
",",
"os",
".",
"SEEK_SET",
")",
"data",
"=",
"self",
".",
"_tar_buffer",
".",
"read",
"(",
")",
"yield",
"data",
"for",
"info",
",",
"content",
"in",
"self",
".",
"_ios_to_add",
".",
"items",
"(",
")",
":",
"last",
"=",
"self",
".",
"_tar_buffer",
".",
"tell",
"(",
")",
"self",
".",
"_tar_obj",
".",
"addfile",
"(",
"info",
",",
"content",
")",
"self",
".",
"_tar_buffer",
".",
"seek",
"(",
"last",
",",
"os",
".",
"SEEK_SET",
")",
"data",
"=",
"self",
".",
"_tar_buffer",
".",
"read",
"(",
")",
"yield",
"data",
"self",
".",
"_tar_obj",
".",
"close",
"(",
")",
"yield",
"self",
".",
"_tar_buffer",
".",
"read",
"(",
")",
"self",
".",
"_generated",
"=",
"True"
] |
generate tar file
..Usage::
>>> tarfile = b"".join(data for data in tg.generate())
|
[
"generate",
"tar",
"file"
] |
d8cad6311a4da7ef09f3419c86b58e30388b7ee3
|
https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/tar.py#L80-L107
|
243,411
|
SkyLothar/shcmd
|
shcmd/tar.py
|
TarGenerator.tar
|
def tar(self):
"""tar in bytes format"""
if not self.generated:
for data in self.generate():
pass
return self._tar_buffer.getvalue()
|
python
|
def tar(self):
"""tar in bytes format"""
if not self.generated:
for data in self.generate():
pass
return self._tar_buffer.getvalue()
|
[
"def",
"tar",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"generated",
":",
"for",
"data",
"in",
"self",
".",
"generate",
"(",
")",
":",
"pass",
"return",
"self",
".",
"_tar_buffer",
".",
"getvalue",
"(",
")"
] |
tar in bytes format
|
[
"tar",
"in",
"bytes",
"format"
] |
d8cad6311a4da7ef09f3419c86b58e30388b7ee3
|
https://github.com/SkyLothar/shcmd/blob/d8cad6311a4da7ef09f3419c86b58e30388b7ee3/shcmd/tar.py#L114-L119
|
243,412
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.connect
|
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
|
python
|
def connect(self):
"""
Starts the mongodb connection. Must be called before anything else
will work.
"""
self.client = MongoClient(self.mongo_uri)
self.db = self.client[self.db_name]
|
[
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"MongoClient",
"(",
"self",
".",
"mongo_uri",
")",
"self",
".",
"db",
"=",
"self",
".",
"client",
"[",
"self",
".",
"db_name",
"]"
] |
Starts the mongodb connection. Must be called before anything else
will work.
|
[
"Starts",
"the",
"mongodb",
"connection",
".",
"Must",
"be",
"called",
"before",
"anything",
"else",
"will",
"work",
"."
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L68-L74
|
243,413
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.find
|
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
|
python
|
def find(self, collection, query):
"""
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find(query)
return result
|
[
"def",
"find",
"(",
"self",
",",
"collection",
",",
"query",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
".",
"db",
",",
"collection",
")",
"result",
"=",
"obj",
".",
"find",
"(",
"query",
")",
"return",
"result"
] |
Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
|
[
"Search",
"a",
"collection",
"for",
"the",
"query",
"provided",
".",
"Just",
"a",
"raw",
"interface",
"to",
"mongo",
"to",
"do",
"any",
"query",
"you",
"want",
"."
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L76-L89
|
243,414
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.find_all
|
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
|
python
|
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result = obj.find()
return result
|
[
"def",
"find_all",
"(",
"self",
",",
"collection",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
".",
"db",
",",
"collection",
")",
"result",
"=",
"obj",
".",
"find",
"(",
")",
"return",
"result"
] |
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
|
[
"Search",
"a",
"collection",
"for",
"all",
"available",
"items",
"."
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L91-L102
|
243,415
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.find_one
|
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
|
python
|
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
"""
obj = getattr(self.db, collection)
result = obj.find_one(query)
return result
|
[
"def",
"find_one",
"(",
"self",
",",
"collection",
",",
"query",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
".",
"db",
",",
"collection",
")",
"result",
"=",
"obj",
".",
"find_one",
"(",
"query",
")",
"return",
"result"
] |
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.
|
[
"Search",
"a",
"collection",
"for",
"the",
"query",
"provided",
"and",
"return",
"one",
"result",
".",
"Just",
"a",
"raw",
"interface",
"to",
"mongo",
"to",
"do",
"any",
"query",
"you",
"want",
"."
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L104-L117
|
243,416
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.find_distinct
|
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
|
python
|
def find_distinct(self, collection, key):
"""
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
"""
obj = getattr(self.db, collection)
result = obj.distinct(key)
return result
|
[
"def",
"find_distinct",
"(",
"self",
",",
"collection",
",",
"key",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
".",
"db",
",",
"collection",
")",
"result",
"=",
"obj",
".",
"distinct",
"(",
"key",
")",
"return",
"result"
] |
Search a collection for the distinct key values provided.
Args:
collection: The db collection. See main class documentation.
key: The name of the key to find distinct values. For example with
the indicators collection, the key could be "type".
Returns:
List of distinct values.
|
[
"Search",
"a",
"collection",
"for",
"the",
"distinct",
"key",
"values",
"provided",
"."
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L119-L132
|
243,417
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.add_embedded_campaign
|
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
|
python
|
def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result
|
[
"def",
"add_embedded_campaign",
"(",
"self",
",",
"id",
",",
"collection",
",",
"campaign",
",",
"confidence",
",",
"analyst",
",",
"date",
",",
"description",
")",
":",
"if",
"type",
"(",
"id",
")",
"is",
"not",
"ObjectId",
":",
"id",
"=",
"ObjectId",
"(",
"id",
")",
"# TODO: Make sure the object does not already have the campaign",
"# Return if it does. Add it if it doesn't",
"obj",
"=",
"getattr",
"(",
"self",
".",
"db",
",",
"collection",
")",
"result",
"=",
"obj",
".",
"find",
"(",
"{",
"'_id'",
":",
"id",
",",
"'campaign.name'",
":",
"campaign",
"}",
")",
"if",
"result",
".",
"count",
"(",
")",
">",
"0",
":",
"return",
"else",
":",
"log",
".",
"debug",
"(",
"'Adding campaign to set: {}'",
".",
"format",
"(",
"campaign",
")",
")",
"campaign_obj",
"=",
"{",
"'analyst'",
":",
"analyst",
",",
"'confidence'",
":",
"confidence",
",",
"'date'",
":",
"date",
",",
"'description'",
":",
"description",
",",
"'name'",
":",
"campaign",
"}",
"result",
"=",
"obj",
".",
"update",
"(",
"{",
"'_id'",
":",
"id",
"}",
",",
"{",
"'$push'",
":",
"{",
"'campaign'",
":",
"campaign_obj",
"}",
"}",
")",
"return",
"result"
] |
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
|
[
"Adds",
"an",
"embedded",
"campaign",
"to",
"the",
"TLO",
"."
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L134-L171
|
243,418
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.remove_bucket_list_item
|
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
|
python
|
def remove_bucket_list_item(self, id, collection, item):
"""
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
"""
if type(id) is not ObjectId:
id = ObjectId(id)
obj = getattr(self.db, collection)
result = obj.update(
{'_id': id},
{'$pull': {'bucket_list': item}}
)
return result
|
[
"def",
"remove_bucket_list_item",
"(",
"self",
",",
"id",
",",
"collection",
",",
"item",
")",
":",
"if",
"type",
"(",
"id",
")",
"is",
"not",
"ObjectId",
":",
"id",
"=",
"ObjectId",
"(",
"id",
")",
"obj",
"=",
"getattr",
"(",
"self",
".",
"db",
",",
"collection",
")",
"result",
"=",
"obj",
".",
"update",
"(",
"{",
"'_id'",
":",
"id",
"}",
",",
"{",
"'$pull'",
":",
"{",
"'bucket_list'",
":",
"item",
"}",
"}",
")",
"return",
"result"
] |
Removes an item from the bucket list
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
item: the bucket list item to remove
Returns:
The mongodb result
|
[
"Removes",
"an",
"item",
"from",
"the",
"bucket",
"list"
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L173-L191
|
243,419
|
IntegralDefense/critsapi
|
critsapi/critsdbapi.py
|
CRITsDBAPI.get_campaign_name_list
|
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
python
|
def get_campaign_name_list(self):
"""
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
"""
campaigns = self.find('campaigns', {})
campaign_names = []
for campaign in campaigns:
if 'name' in campaign:
campaign_names.append(campaign['name'])
return campaign_names
|
[
"def",
"get_campaign_name_list",
"(",
"self",
")",
":",
"campaigns",
"=",
"self",
".",
"find",
"(",
"'campaigns'",
",",
"{",
"}",
")",
"campaign_names",
"=",
"[",
"]",
"for",
"campaign",
"in",
"campaigns",
":",
"if",
"'name'",
"in",
"campaign",
":",
"campaign_names",
".",
"append",
"(",
"campaign",
"[",
"'name'",
"]",
")",
"return",
"campaign_names"
] |
Returns a list of all valid campaign names
Returns:
List of strings containing all valid campaign names
|
[
"Returns",
"a",
"list",
"of",
"all",
"valid",
"campaign",
"names"
] |
e770bd81e124eaaeb5f1134ba95f4a35ff345c5a
|
https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L213-L225
|
243,420
|
sassoo/goldman
|
goldman/deserializers/json_7159.py
|
Deserializer.deserialize
|
def deserialize(self):
""" Invoke the RFC 7159 spec compliant parser
:return:
the parsed & vetted request body
"""
super(Deserializer, self).deserialize()
try:
return json.loads(self.req.get_body())
except TypeError:
link = 'tools.ietf.org/html/rfc7159'
self.fail('Typically, this error is due to a missing JSON '
'payload in your request when one was required. '
'Otherwise, it could be a bug in our API.', link)
except UnicodeDecodeError:
link = 'tools.ietf.org/html/rfc7159#section-8.1'
self.fail('We failed to process your JSON payload & it is '
'most likely due to non UTF-8 encoded characters '
'in your JSON.', link)
except ValueError as exc:
link = 'tools.ietf.org/html/rfc7159'
self.fail('The JSON payload appears to be malformed & we '
'failed to process it. The error with line & column '
'numbers is: %s' % exc.message, link)
|
python
|
def deserialize(self):
""" Invoke the RFC 7159 spec compliant parser
:return:
the parsed & vetted request body
"""
super(Deserializer, self).deserialize()
try:
return json.loads(self.req.get_body())
except TypeError:
link = 'tools.ietf.org/html/rfc7159'
self.fail('Typically, this error is due to a missing JSON '
'payload in your request when one was required. '
'Otherwise, it could be a bug in our API.', link)
except UnicodeDecodeError:
link = 'tools.ietf.org/html/rfc7159#section-8.1'
self.fail('We failed to process your JSON payload & it is '
'most likely due to non UTF-8 encoded characters '
'in your JSON.', link)
except ValueError as exc:
link = 'tools.ietf.org/html/rfc7159'
self.fail('The JSON payload appears to be malformed & we '
'failed to process it. The error with line & column '
'numbers is: %s' % exc.message, link)
|
[
"def",
"deserialize",
"(",
"self",
")",
":",
"super",
"(",
"Deserializer",
",",
"self",
")",
".",
"deserialize",
"(",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"req",
".",
"get_body",
"(",
")",
")",
"except",
"TypeError",
":",
"link",
"=",
"'tools.ietf.org/html/rfc7159'",
"self",
".",
"fail",
"(",
"'Typically, this error is due to a missing JSON '",
"'payload in your request when one was required. '",
"'Otherwise, it could be a bug in our API.'",
",",
"link",
")",
"except",
"UnicodeDecodeError",
":",
"link",
"=",
"'tools.ietf.org/html/rfc7159#section-8.1'",
"self",
".",
"fail",
"(",
"'We failed to process your JSON payload & it is '",
"'most likely due to non UTF-8 encoded characters '",
"'in your JSON.'",
",",
"link",
")",
"except",
"ValueError",
"as",
"exc",
":",
"link",
"=",
"'tools.ietf.org/html/rfc7159'",
"self",
".",
"fail",
"(",
"'The JSON payload appears to be malformed & we '",
"'failed to process it. The error with line & column '",
"'numbers is: %s'",
"%",
"exc",
".",
"message",
",",
"link",
")"
] |
Invoke the RFC 7159 spec compliant parser
:return:
the parsed & vetted request body
|
[
"Invoke",
"the",
"RFC",
"7159",
"spec",
"compliant",
"parser"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/deserializers/json_7159.py#L22-L47
|
243,421
|
callowayproject/Transmogrify
|
transmogrify/images2gif.py
|
NeuQuant.quantize_without_scipy
|
def quantize_without_scipy(self, image):
"""" This function can be used if no scipy is availabe.
It's 7 times slower though.
"""
w, h = image.size
px = np.asarray(image).copy()
memo = {}
for j in range(w):
for i in range(h):
key = (px[i, j, 0], px[i, j, 1], px[i, j, 2])
try:
val = memo[key]
except KeyError:
val = self.convert(*key)
memo[key] = val
px[i, j, 0], px[i, j, 1], px[i, j, 2] = val
return Image.fromarray(px).convert("RGB").quantize(palette=self.palette_image())
|
python
|
def quantize_without_scipy(self, image):
"""" This function can be used if no scipy is availabe.
It's 7 times slower though.
"""
w, h = image.size
px = np.asarray(image).copy()
memo = {}
for j in range(w):
for i in range(h):
key = (px[i, j, 0], px[i, j, 1], px[i, j, 2])
try:
val = memo[key]
except KeyError:
val = self.convert(*key)
memo[key] = val
px[i, j, 0], px[i, j, 1], px[i, j, 2] = val
return Image.fromarray(px).convert("RGB").quantize(palette=self.palette_image())
|
[
"def",
"quantize_without_scipy",
"(",
"self",
",",
"image",
")",
":",
"w",
",",
"h",
"=",
"image",
".",
"size",
"px",
"=",
"np",
".",
"asarray",
"(",
"image",
")",
".",
"copy",
"(",
")",
"memo",
"=",
"{",
"}",
"for",
"j",
"in",
"range",
"(",
"w",
")",
":",
"for",
"i",
"in",
"range",
"(",
"h",
")",
":",
"key",
"=",
"(",
"px",
"[",
"i",
",",
"j",
",",
"0",
"]",
",",
"px",
"[",
"i",
",",
"j",
",",
"1",
"]",
",",
"px",
"[",
"i",
",",
"j",
",",
"2",
"]",
")",
"try",
":",
"val",
"=",
"memo",
"[",
"key",
"]",
"except",
"KeyError",
":",
"val",
"=",
"self",
".",
"convert",
"(",
"*",
"key",
")",
"memo",
"[",
"key",
"]",
"=",
"val",
"px",
"[",
"i",
",",
"j",
",",
"0",
"]",
",",
"px",
"[",
"i",
",",
"j",
",",
"1",
"]",
",",
"px",
"[",
"i",
",",
"j",
",",
"2",
"]",
"=",
"val",
"return",
"Image",
".",
"fromarray",
"(",
"px",
")",
".",
"convert",
"(",
"\"RGB\"",
")",
".",
"quantize",
"(",
"palette",
"=",
"self",
".",
"palette_image",
"(",
")",
")"
] |
This function can be used if no scipy is availabe.
It's 7 times slower though.
|
[
"This",
"function",
"can",
"be",
"used",
"if",
"no",
"scipy",
"is",
"availabe",
".",
"It",
"s",
"7",
"times",
"slower",
"though",
"."
] |
f1f891b8b923b3a1ede5eac7f60531c1c472379e
|
https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/images2gif.py#L1015-L1031
|
243,422
|
espenak/djangosenchatools
|
djangosenchatools/management/commands/senchatoolsbuild.py
|
get_installed_extjs_apps
|
def get_installed_extjs_apps():
"""
Get all installed extjs apps.
:return: List of ``(appdir, module, appname)``.
"""
installed_apps = []
checked = set()
for app in settings.INSTALLED_APPS:
if not app.startswith('django.') and not app in checked:
checked.add(app)
try:
installed_apps.append(get_appinfo(app))
except LookupError, e:
pass
return installed_apps
|
python
|
def get_installed_extjs_apps():
"""
Get all installed extjs apps.
:return: List of ``(appdir, module, appname)``.
"""
installed_apps = []
checked = set()
for app in settings.INSTALLED_APPS:
if not app.startswith('django.') and not app in checked:
checked.add(app)
try:
installed_apps.append(get_appinfo(app))
except LookupError, e:
pass
return installed_apps
|
[
"def",
"get_installed_extjs_apps",
"(",
")",
":",
"installed_apps",
"=",
"[",
"]",
"checked",
"=",
"set",
"(",
")",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"if",
"not",
"app",
".",
"startswith",
"(",
"'django.'",
")",
"and",
"not",
"app",
"in",
"checked",
":",
"checked",
".",
"add",
"(",
"app",
")",
"try",
":",
"installed_apps",
".",
"append",
"(",
"get_appinfo",
"(",
"app",
")",
")",
"except",
"LookupError",
",",
"e",
":",
"pass",
"return",
"installed_apps"
] |
Get all installed extjs apps.
:return: List of ``(appdir, module, appname)``.
|
[
"Get",
"all",
"installed",
"extjs",
"apps",
"."
] |
da1bca9365300de303e833de4b4bd57671c1d11a
|
https://github.com/espenak/djangosenchatools/blob/da1bca9365300de303e833de4b4bd57671c1d11a/djangosenchatools/management/commands/senchatoolsbuild.py#L34-L49
|
243,423
|
espenak/djangosenchatools
|
djangosenchatools/management/commands/senchatoolsbuild.py
|
SenchaToolsWrapper.createJsbConfig
|
def createJsbConfig(self):
"""
Create JSB config file using ``sencha create jsb``.
:return: The created jsb3 config as a string.
"""
tempdir = mkdtemp()
tempfile = join(tempdir, 'app.jsb3')
cmd = ['sencha', 'create', 'jsb', '-a', self.url, '-p', tempfile]
log.debug('Running: %s', ' '.join(cmd))
call(cmd)
jsb3 = open(tempfile).read()
rmtree(tempdir)
return jsb3
|
python
|
def createJsbConfig(self):
"""
Create JSB config file using ``sencha create jsb``.
:return: The created jsb3 config as a string.
"""
tempdir = mkdtemp()
tempfile = join(tempdir, 'app.jsb3')
cmd = ['sencha', 'create', 'jsb', '-a', self.url, '-p', tempfile]
log.debug('Running: %s', ' '.join(cmd))
call(cmd)
jsb3 = open(tempfile).read()
rmtree(tempdir)
return jsb3
|
[
"def",
"createJsbConfig",
"(",
"self",
")",
":",
"tempdir",
"=",
"mkdtemp",
"(",
")",
"tempfile",
"=",
"join",
"(",
"tempdir",
",",
"'app.jsb3'",
")",
"cmd",
"=",
"[",
"'sencha'",
",",
"'create'",
",",
"'jsb'",
",",
"'-a'",
",",
"self",
".",
"url",
",",
"'-p'",
",",
"tempfile",
"]",
"log",
".",
"debug",
"(",
"'Running: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"call",
"(",
"cmd",
")",
"jsb3",
"=",
"open",
"(",
"tempfile",
")",
".",
"read",
"(",
")",
"rmtree",
"(",
"tempdir",
")",
"return",
"jsb3"
] |
Create JSB config file using ``sencha create jsb``.
:return: The created jsb3 config as a string.
|
[
"Create",
"JSB",
"config",
"file",
"using",
"sencha",
"create",
"jsb",
"."
] |
da1bca9365300de303e833de4b4bd57671c1d11a
|
https://github.com/espenak/djangosenchatools/blob/da1bca9365300de303e833de4b4bd57671c1d11a/djangosenchatools/management/commands/senchatoolsbuild.py#L76-L89
|
243,424
|
espenak/djangosenchatools
|
djangosenchatools/management/commands/senchatoolsbuild.py
|
SenchaToolsWrapper.cleanJsbConfig
|
def cleanJsbConfig(self, jsbconfig):
"""
Clean up the JSB config.
"""
config = json.loads(jsbconfig)
self._cleanJsbAllClassesSection(config)
self._cleanJsbAppAllSection(config)
return json.dumps(config, indent=4)
|
python
|
def cleanJsbConfig(self, jsbconfig):
"""
Clean up the JSB config.
"""
config = json.loads(jsbconfig)
self._cleanJsbAllClassesSection(config)
self._cleanJsbAppAllSection(config)
return json.dumps(config, indent=4)
|
[
"def",
"cleanJsbConfig",
"(",
"self",
",",
"jsbconfig",
")",
":",
"config",
"=",
"json",
".",
"loads",
"(",
"jsbconfig",
")",
"self",
".",
"_cleanJsbAllClassesSection",
"(",
"config",
")",
"self",
".",
"_cleanJsbAppAllSection",
"(",
"config",
")",
"return",
"json",
".",
"dumps",
"(",
"config",
",",
"indent",
"=",
"4",
")"
] |
Clean up the JSB config.
|
[
"Clean",
"up",
"the",
"JSB",
"config",
"."
] |
da1bca9365300de303e833de4b4bd57671c1d11a
|
https://github.com/espenak/djangosenchatools/blob/da1bca9365300de303e833de4b4bd57671c1d11a/djangosenchatools/management/commands/senchatoolsbuild.py#L91-L98
|
243,425
|
espenak/djangosenchatools
|
djangosenchatools/management/commands/senchatoolsbuild.py
|
SenchaToolsWrapper.buildFromJsbString
|
def buildFromJsbString(self, jsb, nocompressjs=False):
"""
Build from the given config file using ``sencha build``.
:param jsb: The JSB config as a string.
:param nocompressjs: Compress the javascript? If ``True``, run ``sencha build --nocompress``.
"""
tempconffile = 'temp-app.jsb3'
cmd = ['sencha', 'build', '-p', tempconffile, '-d', self.outdir]
if nocompressjs:
cmd.append('--nocompress')
open(tempconffile, 'w').write(jsb)
log.info('Running: %s', ' '.join(cmd))
try:
call(cmd)
finally:
remove(tempconffile)
|
python
|
def buildFromJsbString(self, jsb, nocompressjs=False):
"""
Build from the given config file using ``sencha build``.
:param jsb: The JSB config as a string.
:param nocompressjs: Compress the javascript? If ``True``, run ``sencha build --nocompress``.
"""
tempconffile = 'temp-app.jsb3'
cmd = ['sencha', 'build', '-p', tempconffile, '-d', self.outdir]
if nocompressjs:
cmd.append('--nocompress')
open(tempconffile, 'w').write(jsb)
log.info('Running: %s', ' '.join(cmd))
try:
call(cmd)
finally:
remove(tempconffile)
|
[
"def",
"buildFromJsbString",
"(",
"self",
",",
"jsb",
",",
"nocompressjs",
"=",
"False",
")",
":",
"tempconffile",
"=",
"'temp-app.jsb3'",
"cmd",
"=",
"[",
"'sencha'",
",",
"'build'",
",",
"'-p'",
",",
"tempconffile",
",",
"'-d'",
",",
"self",
".",
"outdir",
"]",
"if",
"nocompressjs",
":",
"cmd",
".",
"append",
"(",
"'--nocompress'",
")",
"open",
"(",
"tempconffile",
",",
"'w'",
")",
".",
"write",
"(",
"jsb",
")",
"log",
".",
"info",
"(",
"'Running: %s'",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"try",
":",
"call",
"(",
"cmd",
")",
"finally",
":",
"remove",
"(",
"tempconffile",
")"
] |
Build from the given config file using ``sencha build``.
:param jsb: The JSB config as a string.
:param nocompressjs: Compress the javascript? If ``True``, run ``sencha build --nocompress``.
|
[
"Build",
"from",
"the",
"given",
"config",
"file",
"using",
"sencha",
"build",
"."
] |
da1bca9365300de303e833de4b4bd57671c1d11a
|
https://github.com/espenak/djangosenchatools/blob/da1bca9365300de303e833de4b4bd57671c1d11a/djangosenchatools/management/commands/senchatoolsbuild.py#L149-L165
|
243,426
|
ronaldguillen/wave
|
wave/metadata.py
|
SimpleMetadata.determine_actions
|
def determine_actions(self, request, view):
"""
For generic class based views we return information about
the fields that are accepted for 'PUT' and 'POST' methods.
"""
actions = {}
for method in {'PUT', 'POST'} & set(view.allowed_methods):
view.request = clone_request(request, method)
try:
# Test global permissions
if hasattr(view, 'check_permissions'):
view.check_permissions(view.request)
# Test object permissions
if method == 'PUT' and hasattr(view, 'get_object'):
view.get_object()
except (exceptions.APIException, PermissionDenied, Http404):
pass
else:
# If user has appropriate permissions for the view, include
# appropriate metadata about the fields that should be supplied.
serializer = view.get_serializer()
actions[method] = self.get_serializer_info(serializer)
finally:
view.request = request
return actions
|
python
|
def determine_actions(self, request, view):
"""
For generic class based views we return information about
the fields that are accepted for 'PUT' and 'POST' methods.
"""
actions = {}
for method in {'PUT', 'POST'} & set(view.allowed_methods):
view.request = clone_request(request, method)
try:
# Test global permissions
if hasattr(view, 'check_permissions'):
view.check_permissions(view.request)
# Test object permissions
if method == 'PUT' and hasattr(view, 'get_object'):
view.get_object()
except (exceptions.APIException, PermissionDenied, Http404):
pass
else:
# If user has appropriate permissions for the view, include
# appropriate metadata about the fields that should be supplied.
serializer = view.get_serializer()
actions[method] = self.get_serializer_info(serializer)
finally:
view.request = request
return actions
|
[
"def",
"determine_actions",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"actions",
"=",
"{",
"}",
"for",
"method",
"in",
"{",
"'PUT'",
",",
"'POST'",
"}",
"&",
"set",
"(",
"view",
".",
"allowed_methods",
")",
":",
"view",
".",
"request",
"=",
"clone_request",
"(",
"request",
",",
"method",
")",
"try",
":",
"# Test global permissions",
"if",
"hasattr",
"(",
"view",
",",
"'check_permissions'",
")",
":",
"view",
".",
"check_permissions",
"(",
"view",
".",
"request",
")",
"# Test object permissions",
"if",
"method",
"==",
"'PUT'",
"and",
"hasattr",
"(",
"view",
",",
"'get_object'",
")",
":",
"view",
".",
"get_object",
"(",
")",
"except",
"(",
"exceptions",
".",
"APIException",
",",
"PermissionDenied",
",",
"Http404",
")",
":",
"pass",
"else",
":",
"# If user has appropriate permissions for the view, include",
"# appropriate metadata about the fields that should be supplied.",
"serializer",
"=",
"view",
".",
"get_serializer",
"(",
")",
"actions",
"[",
"method",
"]",
"=",
"self",
".",
"get_serializer_info",
"(",
"serializer",
")",
"finally",
":",
"view",
".",
"request",
"=",
"request",
"return",
"actions"
] |
For generic class based views we return information about
the fields that are accepted for 'PUT' and 'POST' methods.
|
[
"For",
"generic",
"class",
"based",
"views",
"we",
"return",
"information",
"about",
"the",
"fields",
"that",
"are",
"accepted",
"for",
"PUT",
"and",
"POST",
"methods",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/metadata.py#L74-L99
|
243,427
|
dasevilla/rovi-python
|
roviclient/search.py
|
SearchApi.music_search
|
def music_search(self, entitiy_type, query, **kwargs):
"""
Search the music database
Where ``entitiy_type`` is a comma separated list of:
``song``
songs
``album``
albums
``composition``
compositions
``artist``
people working in music
"""
return self.make_request('music', entitiy_type, query, kwargs)
|
python
|
def music_search(self, entitiy_type, query, **kwargs):
"""
Search the music database
Where ``entitiy_type`` is a comma separated list of:
``song``
songs
``album``
albums
``composition``
compositions
``artist``
people working in music
"""
return self.make_request('music', entitiy_type, query, kwargs)
|
[
"def",
"music_search",
"(",
"self",
",",
"entitiy_type",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"make_request",
"(",
"'music'",
",",
"entitiy_type",
",",
"query",
",",
"kwargs",
")"
] |
Search the music database
Where ``entitiy_type`` is a comma separated list of:
``song``
songs
``album``
albums
``composition``
compositions
``artist``
people working in music
|
[
"Search",
"the",
"music",
"database"
] |
46039d6ebfcf2ff20b4edb4636cb972682cf6af4
|
https://github.com/dasevilla/rovi-python/blob/46039d6ebfcf2ff20b4edb4636cb972682cf6af4/roviclient/search.py#L30-L48
|
243,428
|
dasevilla/rovi-python
|
roviclient/search.py
|
SearchApi.amg_video_search
|
def amg_video_search(self, entitiy_type, query, **kwargs):
"""
Search the Movies and TV database
Where ``entitiy_type`` is a comma separated list of:
``movie``
Movies
``tvseries``
TV series
``credit``
people working in TV or movies
"""
return self.make_request('amgvideo', entitiy_type, query, kwargs)
|
python
|
def amg_video_search(self, entitiy_type, query, **kwargs):
"""
Search the Movies and TV database
Where ``entitiy_type`` is a comma separated list of:
``movie``
Movies
``tvseries``
TV series
``credit``
people working in TV or movies
"""
return self.make_request('amgvideo', entitiy_type, query, kwargs)
|
[
"def",
"amg_video_search",
"(",
"self",
",",
"entitiy_type",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"make_request",
"(",
"'amgvideo'",
",",
"entitiy_type",
",",
"query",
",",
"kwargs",
")"
] |
Search the Movies and TV database
Where ``entitiy_type`` is a comma separated list of:
``movie``
Movies
``tvseries``
TV series
``credit``
people working in TV or movies
|
[
"Search",
"the",
"Movies",
"and",
"TV",
"database"
] |
46039d6ebfcf2ff20b4edb4636cb972682cf6af4
|
https://github.com/dasevilla/rovi-python/blob/46039d6ebfcf2ff20b4edb4636cb972682cf6af4/roviclient/search.py#L50-L65
|
243,429
|
dasevilla/rovi-python
|
roviclient/search.py
|
SearchApi.video_search
|
def video_search(self, entitiy_type, query, **kwargs):
"""
Search the TV schedule database
Where ``entitiy_type`` is a comma separated list of:
``movie``
Movie
``tvseries``
TV series
``episode``
Episode titles
``onetimeonly``
TV programs
``credit``
People working in TV or movies
"""
return self.make_request('video', entitiy_type, query, kwargs)
|
python
|
def video_search(self, entitiy_type, query, **kwargs):
"""
Search the TV schedule database
Where ``entitiy_type`` is a comma separated list of:
``movie``
Movie
``tvseries``
TV series
``episode``
Episode titles
``onetimeonly``
TV programs
``credit``
People working in TV or movies
"""
return self.make_request('video', entitiy_type, query, kwargs)
|
[
"def",
"video_search",
"(",
"self",
",",
"entitiy_type",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"make_request",
"(",
"'video'",
",",
"entitiy_type",
",",
"query",
",",
"kwargs",
")"
] |
Search the TV schedule database
Where ``entitiy_type`` is a comma separated list of:
``movie``
Movie
``tvseries``
TV series
``episode``
Episode titles
``onetimeonly``
TV programs
``credit``
People working in TV or movies
|
[
"Search",
"the",
"TV",
"schedule",
"database"
] |
46039d6ebfcf2ff20b4edb4636cb972682cf6af4
|
https://github.com/dasevilla/rovi-python/blob/46039d6ebfcf2ff20b4edb4636cb972682cf6af4/roviclient/search.py#L67-L88
|
243,430
|
TC01/calcpkg
|
calcrepo/index.py
|
structureOutput
|
def structureOutput(fileUrl, fileName, searchFiles, format=True, space=40):
"""Formats the output of a list of packages"""
#First, remove the filename
if format:
splitUrls = fileUrl[1:].split('/')
fileUrl = ""
for splitUrl in splitUrls:
# This is a gimmicky fix to make formatting consistent
# Cemetech doesn't have /pub/ at the front of it's repo paths
# Also, Omnimaga has a /files/ we need to get rid of similarly
# This probably *should* be repo-dependent, but oh well
if splitUrl != "" and (not "." in splitUrl) and (splitUrl != "pub" and splitUrl != "files"):
fileUrl += splitUrl + '/'
elif "." in splitUrl:
archiveName = splitUrl
#Now, format the output
if searchFiles:
fileName = archiveName
pause = (space - len(fileUrl))
output = fileUrl
output += (" " * pause)
output += fileName
return output
|
python
|
def structureOutput(fileUrl, fileName, searchFiles, format=True, space=40):
"""Formats the output of a list of packages"""
#First, remove the filename
if format:
splitUrls = fileUrl[1:].split('/')
fileUrl = ""
for splitUrl in splitUrls:
# This is a gimmicky fix to make formatting consistent
# Cemetech doesn't have /pub/ at the front of it's repo paths
# Also, Omnimaga has a /files/ we need to get rid of similarly
# This probably *should* be repo-dependent, but oh well
if splitUrl != "" and (not "." in splitUrl) and (splitUrl != "pub" and splitUrl != "files"):
fileUrl += splitUrl + '/'
elif "." in splitUrl:
archiveName = splitUrl
#Now, format the output
if searchFiles:
fileName = archiveName
pause = (space - len(fileUrl))
output = fileUrl
output += (" " * pause)
output += fileName
return output
|
[
"def",
"structureOutput",
"(",
"fileUrl",
",",
"fileName",
",",
"searchFiles",
",",
"format",
"=",
"True",
",",
"space",
"=",
"40",
")",
":",
"#First, remove the filename",
"if",
"format",
":",
"splitUrls",
"=",
"fileUrl",
"[",
"1",
":",
"]",
".",
"split",
"(",
"'/'",
")",
"fileUrl",
"=",
"\"\"",
"for",
"splitUrl",
"in",
"splitUrls",
":",
"# This is a gimmicky fix to make formatting consistent",
"# Cemetech doesn't have /pub/ at the front of it's repo paths",
"# Also, Omnimaga has a /files/ we need to get rid of similarly",
"# This probably *should* be repo-dependent, but oh well",
"if",
"splitUrl",
"!=",
"\"\"",
"and",
"(",
"not",
"\".\"",
"in",
"splitUrl",
")",
"and",
"(",
"splitUrl",
"!=",
"\"pub\"",
"and",
"splitUrl",
"!=",
"\"files\"",
")",
":",
"fileUrl",
"+=",
"splitUrl",
"+",
"'/'",
"elif",
"\".\"",
"in",
"splitUrl",
":",
"archiveName",
"=",
"splitUrl",
"#Now, format the output",
"if",
"searchFiles",
":",
"fileName",
"=",
"archiveName",
"pause",
"=",
"(",
"space",
"-",
"len",
"(",
"fileUrl",
")",
")",
"output",
"=",
"fileUrl",
"output",
"+=",
"(",
"\" \"",
"*",
"pause",
")",
"output",
"+=",
"fileName",
"return",
"output"
] |
Formats the output of a list of packages
|
[
"Formats",
"the",
"output",
"of",
"a",
"list",
"of",
"packages"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/index.py#L257-L280
|
243,431
|
TC01/calcpkg
|
calcrepo/index.py
|
Index.count
|
def count(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""):
"""Counts the number of ticalc.org files containing some search term, doesn't return them"""
fileData = {}
nameData = {}
#Search the index
if searchFiles:
fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension)
else:
nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString)
#Now search the other index
if searchFiles:
nameData, fileData = self.searchFilesIndex(fileData, nameData, self.nameIndex, searchString)
else:
fileData, nameData = self.searchFilesIndex(nameData, fileData, self.fileIndex, searchString, category, math, game, extension)
# Bail out if we failed to do either of those things.
if fileData is None or nameData is None:
self.repo.printd("Error: failed to load one or more of the index files for this repo. Exiting.")
self.repo.printd("Please run 'calcpkg update' and retry this command.")
sys.exit(1)
#Now obtain a count (exclude "none" elements)
count = 0
for element in nameData:
if not nameData[element] is None:
count += 1
self.repo.printd("Search for '" + searchString + "' returned " + str(count) + " result(s) in " + self.repo.name)
return count
|
python
|
def count(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""):
"""Counts the number of ticalc.org files containing some search term, doesn't return them"""
fileData = {}
nameData = {}
#Search the index
if searchFiles:
fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension)
else:
nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString)
#Now search the other index
if searchFiles:
nameData, fileData = self.searchFilesIndex(fileData, nameData, self.nameIndex, searchString)
else:
fileData, nameData = self.searchFilesIndex(nameData, fileData, self.fileIndex, searchString, category, math, game, extension)
# Bail out if we failed to do either of those things.
if fileData is None or nameData is None:
self.repo.printd("Error: failed to load one or more of the index files for this repo. Exiting.")
self.repo.printd("Please run 'calcpkg update' and retry this command.")
sys.exit(1)
#Now obtain a count (exclude "none" elements)
count = 0
for element in nameData:
if not nameData[element] is None:
count += 1
self.repo.printd("Search for '" + searchString + "' returned " + str(count) + " result(s) in " + self.repo.name)
return count
|
[
"def",
"count",
"(",
"self",
",",
"searchString",
",",
"category",
"=",
"\"\"",
",",
"math",
"=",
"False",
",",
"game",
"=",
"False",
",",
"searchFiles",
"=",
"False",
",",
"extension",
"=",
"\"\"",
")",
":",
"fileData",
"=",
"{",
"}",
"nameData",
"=",
"{",
"}",
"#Search the index",
"if",
"searchFiles",
":",
"fileData",
"=",
"self",
".",
"searchNamesIndex",
"(",
"self",
".",
"fileIndex",
",",
"fileData",
",",
"searchString",
",",
"category",
",",
"math",
",",
"game",
",",
"extension",
")",
"else",
":",
"nameData",
"=",
"self",
".",
"searchNamesIndex",
"(",
"self",
".",
"nameIndex",
",",
"nameData",
",",
"searchString",
")",
"#Now search the other index",
"if",
"searchFiles",
":",
"nameData",
",",
"fileData",
"=",
"self",
".",
"searchFilesIndex",
"(",
"fileData",
",",
"nameData",
",",
"self",
".",
"nameIndex",
",",
"searchString",
")",
"else",
":",
"fileData",
",",
"nameData",
"=",
"self",
".",
"searchFilesIndex",
"(",
"nameData",
",",
"fileData",
",",
"self",
".",
"fileIndex",
",",
"searchString",
",",
"category",
",",
"math",
",",
"game",
",",
"extension",
")",
"# Bail out if we failed to do either of those things.",
"if",
"fileData",
"is",
"None",
"or",
"nameData",
"is",
"None",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Error: failed to load one or more of the index files for this repo. Exiting.\"",
")",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Please run 'calcpkg update' and retry this command.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"#Now obtain a count (exclude \"none\" elements)",
"count",
"=",
"0",
"for",
"element",
"in",
"nameData",
":",
"if",
"not",
"nameData",
"[",
"element",
"]",
"is",
"None",
":",
"count",
"+=",
"1",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Search for '\"",
"+",
"searchString",
"+",
"\"' returned \"",
"+",
"str",
"(",
"count",
")",
"+",
"\" result(s) in \"",
"+",
"self",
".",
"repo",
".",
"name",
")",
"return",
"count"
] |
Counts the number of ticalc.org files containing some search term, doesn't return them
|
[
"Counts",
"the",
"number",
"of",
"ticalc",
".",
"org",
"files",
"containing",
"some",
"search",
"term",
"doesn",
"t",
"return",
"them"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/index.py#L19-L49
|
243,432
|
TC01/calcpkg
|
calcrepo/index.py
|
Index.searchHierarchy
|
def searchHierarchy(self, fparent):
"""Core function to search directory structure for child files and folders of a parent"""
data = []
returnData = []
parentslashes = fparent.count('/')
filecount = 0
foldercount = 0
#open files for folder searching
try:
dirFile = open(self.dirIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.dirIndex)
return
#search for folders
for fldr in dirFile:
fldr = fldr.split('|')
fldr = fldr[0]
if fparent in fldr and parentslashes+1 == fldr.count('/'):
returnData.append([fldr, fldr[fldr.rfind('/',1,-1):-1], ResultType.FOLDER])
foldercount += 1
dirFile.close()
#open files for file searching
try:
fileFile = open(self.fileIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.fileIndex)
return
try:
nameFile = open(self.nameIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.nameIndex)
return
#search for files
for (path,name) in zip(fileFile,nameFile):
if fparent in path and parentslashes == path.count('/'):
returnData.append([path.strip(), name, ResultType.FILE])
filecount += 1
fileFile.close()
nameFile.close()
return [returnData, foldercount, filecount]
|
python
|
def searchHierarchy(self, fparent):
"""Core function to search directory structure for child files and folders of a parent"""
data = []
returnData = []
parentslashes = fparent.count('/')
filecount = 0
foldercount = 0
#open files for folder searching
try:
dirFile = open(self.dirIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.dirIndex)
return
#search for folders
for fldr in dirFile:
fldr = fldr.split('|')
fldr = fldr[0]
if fparent in fldr and parentslashes+1 == fldr.count('/'):
returnData.append([fldr, fldr[fldr.rfind('/',1,-1):-1], ResultType.FOLDER])
foldercount += 1
dirFile.close()
#open files for file searching
try:
fileFile = open(self.fileIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.fileIndex)
return
try:
nameFile = open(self.nameIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.nameIndex)
return
#search for files
for (path,name) in zip(fileFile,nameFile):
if fparent in path and parentslashes == path.count('/'):
returnData.append([path.strip(), name, ResultType.FILE])
filecount += 1
fileFile.close()
nameFile.close()
return [returnData, foldercount, filecount]
|
[
"def",
"searchHierarchy",
"(",
"self",
",",
"fparent",
")",
":",
"data",
"=",
"[",
"]",
"returnData",
"=",
"[",
"]",
"parentslashes",
"=",
"fparent",
".",
"count",
"(",
"'/'",
")",
"filecount",
"=",
"0",
"foldercount",
"=",
"0",
"#open files for folder searching",
"try",
":",
"dirFile",
"=",
"open",
"(",
"self",
".",
"dirIndex",
",",
"'rt'",
")",
"except",
"IOError",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Error: Unable to read index file \"",
"+",
"self",
".",
"dirIndex",
")",
"return",
"#search for folders",
"for",
"fldr",
"in",
"dirFile",
":",
"fldr",
"=",
"fldr",
".",
"split",
"(",
"'|'",
")",
"fldr",
"=",
"fldr",
"[",
"0",
"]",
"if",
"fparent",
"in",
"fldr",
"and",
"parentslashes",
"+",
"1",
"==",
"fldr",
".",
"count",
"(",
"'/'",
")",
":",
"returnData",
".",
"append",
"(",
"[",
"fldr",
",",
"fldr",
"[",
"fldr",
".",
"rfind",
"(",
"'/'",
",",
"1",
",",
"-",
"1",
")",
":",
"-",
"1",
"]",
",",
"ResultType",
".",
"FOLDER",
"]",
")",
"foldercount",
"+=",
"1",
"dirFile",
".",
"close",
"(",
")",
"#open files for file searching",
"try",
":",
"fileFile",
"=",
"open",
"(",
"self",
".",
"fileIndex",
",",
"'rt'",
")",
"except",
"IOError",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Error: Unable to read index file \"",
"+",
"self",
".",
"fileIndex",
")",
"return",
"try",
":",
"nameFile",
"=",
"open",
"(",
"self",
".",
"nameIndex",
",",
"'rt'",
")",
"except",
"IOError",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Error: Unable to read index file \"",
"+",
"self",
".",
"nameIndex",
")",
"return",
"#search for files",
"for",
"(",
"path",
",",
"name",
")",
"in",
"zip",
"(",
"fileFile",
",",
"nameFile",
")",
":",
"if",
"fparent",
"in",
"path",
"and",
"parentslashes",
"==",
"path",
".",
"count",
"(",
"'/'",
")",
":",
"returnData",
".",
"append",
"(",
"[",
"path",
".",
"strip",
"(",
")",
",",
"name",
",",
"ResultType",
".",
"FILE",
"]",
")",
"filecount",
"+=",
"1",
"fileFile",
".",
"close",
"(",
")",
"nameFile",
".",
"close",
"(",
")",
"return",
"[",
"returnData",
",",
"foldercount",
",",
"filecount",
"]"
] |
Core function to search directory structure for child files and folders of a parent
|
[
"Core",
"function",
"to",
"search",
"directory",
"structure",
"for",
"child",
"files",
"and",
"folders",
"of",
"a",
"parent"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/index.py#L51-L98
|
243,433
|
TC01/calcpkg
|
calcrepo/index.py
|
Index.search
|
def search(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""):
"""Core function to search the indexes and return data"""
data = []
nameData = {}
fileData = {}
#Search the name index
if searchFiles:
fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension, searchFiles)
else:
nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString)
#Now search the file index
if searchFiles:
nameData, fileData = self.searchFilesIndex(fileData, nameData, self.nameIndex, searchString)
else:
fileData, nameData = self.searchFilesIndex(nameData, fileData, self.fileIndex, searchString, category, math, game, extension)
# Bail out if we failed to do either of those things.
if fileData is None or nameData is None:
self.repo.printd("Error: failed to load one or more of the index files for this repo. Exiting.")
self.repo.printd("Please run 'calcpkg update' and retry this command.")
sys.exit(1)
# Prepare output to parse
space = 0
longestFile = len("File Name:")
for key, value in nameData.iteritems():
fileValue = fileData[key]
data.append([fileValue, value])
if not fileValue is None:
folder = fileValue.rpartition("/")[0]
if space < len(folder):
space = len(folder)
if not value is None:
if longestFile < len(value):
longestFile = len(value)
#Print output
space += 5
if len(data) != 0:
self.repo.printd("Results for repo: " + self.repo.name)
self.repo.printd(structureOutput("File Category:", "File Name:", False, False, space))
self.repo.printd("-" * (space + longestFile))
else:
self.repo.printd("No packages found")
returnData = []
for datum in data:
try:
self.repo.printd(structureOutput(datum[0], datum[1], searchFiles, True, space))
returnData.append([datum[0], datum[1]])
except:
pass
self.repo.printd(" ")
#Return data
return returnData
|
python
|
def search(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""):
"""Core function to search the indexes and return data"""
data = []
nameData = {}
fileData = {}
#Search the name index
if searchFiles:
fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension, searchFiles)
else:
nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString)
#Now search the file index
if searchFiles:
nameData, fileData = self.searchFilesIndex(fileData, nameData, self.nameIndex, searchString)
else:
fileData, nameData = self.searchFilesIndex(nameData, fileData, self.fileIndex, searchString, category, math, game, extension)
# Bail out if we failed to do either of those things.
if fileData is None or nameData is None:
self.repo.printd("Error: failed to load one or more of the index files for this repo. Exiting.")
self.repo.printd("Please run 'calcpkg update' and retry this command.")
sys.exit(1)
# Prepare output to parse
space = 0
longestFile = len("File Name:")
for key, value in nameData.iteritems():
fileValue = fileData[key]
data.append([fileValue, value])
if not fileValue is None:
folder = fileValue.rpartition("/")[0]
if space < len(folder):
space = len(folder)
if not value is None:
if longestFile < len(value):
longestFile = len(value)
#Print output
space += 5
if len(data) != 0:
self.repo.printd("Results for repo: " + self.repo.name)
self.repo.printd(structureOutput("File Category:", "File Name:", False, False, space))
self.repo.printd("-" * (space + longestFile))
else:
self.repo.printd("No packages found")
returnData = []
for datum in data:
try:
self.repo.printd(structureOutput(datum[0], datum[1], searchFiles, True, space))
returnData.append([datum[0], datum[1]])
except:
pass
self.repo.printd(" ")
#Return data
return returnData
|
[
"def",
"search",
"(",
"self",
",",
"searchString",
",",
"category",
"=",
"\"\"",
",",
"math",
"=",
"False",
",",
"game",
"=",
"False",
",",
"searchFiles",
"=",
"False",
",",
"extension",
"=",
"\"\"",
")",
":",
"data",
"=",
"[",
"]",
"nameData",
"=",
"{",
"}",
"fileData",
"=",
"{",
"}",
"#Search the name index",
"if",
"searchFiles",
":",
"fileData",
"=",
"self",
".",
"searchNamesIndex",
"(",
"self",
".",
"fileIndex",
",",
"fileData",
",",
"searchString",
",",
"category",
",",
"math",
",",
"game",
",",
"extension",
",",
"searchFiles",
")",
"else",
":",
"nameData",
"=",
"self",
".",
"searchNamesIndex",
"(",
"self",
".",
"nameIndex",
",",
"nameData",
",",
"searchString",
")",
"#Now search the file index",
"if",
"searchFiles",
":",
"nameData",
",",
"fileData",
"=",
"self",
".",
"searchFilesIndex",
"(",
"fileData",
",",
"nameData",
",",
"self",
".",
"nameIndex",
",",
"searchString",
")",
"else",
":",
"fileData",
",",
"nameData",
"=",
"self",
".",
"searchFilesIndex",
"(",
"nameData",
",",
"fileData",
",",
"self",
".",
"fileIndex",
",",
"searchString",
",",
"category",
",",
"math",
",",
"game",
",",
"extension",
")",
"# Bail out if we failed to do either of those things.",
"if",
"fileData",
"is",
"None",
"or",
"nameData",
"is",
"None",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Error: failed to load one or more of the index files for this repo. Exiting.\"",
")",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Please run 'calcpkg update' and retry this command.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# Prepare output to parse",
"space",
"=",
"0",
"longestFile",
"=",
"len",
"(",
"\"File Name:\"",
")",
"for",
"key",
",",
"value",
"in",
"nameData",
".",
"iteritems",
"(",
")",
":",
"fileValue",
"=",
"fileData",
"[",
"key",
"]",
"data",
".",
"append",
"(",
"[",
"fileValue",
",",
"value",
"]",
")",
"if",
"not",
"fileValue",
"is",
"None",
":",
"folder",
"=",
"fileValue",
".",
"rpartition",
"(",
"\"/\"",
")",
"[",
"0",
"]",
"if",
"space",
"<",
"len",
"(",
"folder",
")",
":",
"space",
"=",
"len",
"(",
"folder",
")",
"if",
"not",
"value",
"is",
"None",
":",
"if",
"longestFile",
"<",
"len",
"(",
"value",
")",
":",
"longestFile",
"=",
"len",
"(",
"value",
")",
"#Print output",
"space",
"+=",
"5",
"if",
"len",
"(",
"data",
")",
"!=",
"0",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Results for repo: \"",
"+",
"self",
".",
"repo",
".",
"name",
")",
"self",
".",
"repo",
".",
"printd",
"(",
"structureOutput",
"(",
"\"File Category:\"",
",",
"\"File Name:\"",
",",
"False",
",",
"False",
",",
"space",
")",
")",
"self",
".",
"repo",
".",
"printd",
"(",
"\"-\"",
"*",
"(",
"space",
"+",
"longestFile",
")",
")",
"else",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"No packages found\"",
")",
"returnData",
"=",
"[",
"]",
"for",
"datum",
"in",
"data",
":",
"try",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"structureOutput",
"(",
"datum",
"[",
"0",
"]",
",",
"datum",
"[",
"1",
"]",
",",
"searchFiles",
",",
"True",
",",
"space",
")",
")",
"returnData",
".",
"append",
"(",
"[",
"datum",
"[",
"0",
"]",
",",
"datum",
"[",
"1",
"]",
"]",
")",
"except",
":",
"pass",
"self",
".",
"repo",
".",
"printd",
"(",
"\" \"",
")",
"#Return data",
"return",
"returnData"
] |
Core function to search the indexes and return data
|
[
"Core",
"function",
"to",
"search",
"the",
"indexes",
"and",
"return",
"data"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/index.py#L101-L157
|
243,434
|
TC01/calcpkg
|
calcrepo/index.py
|
Index.searchFilesIndex
|
def searchFilesIndex(self, nameData, fileData, fileIndex, searchString, category="", math=False, game=False, extension=""):
"""Search the files index using the namedata and returns the filedata"""
try:
fileFile = open(fileIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.fileIndex)
return None, None
count = 1
for line in fileFile:
count += 1
try:
if nameData[count] != None:
#category argument
if category in line:
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
#extension argument
if extension in line:
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
#Both game and math
if (game and math):
if ("/games/" in line or "/math/" in line or "/science" in line):
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#game option switch
elif game:
if "/games/" in line:
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
#math option switch
elif math:
if ("/math/" in line or "/science/" in line):
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
except:
pass
#Close the file and return
fileFile.close()
return fileData, nameData
|
python
|
def searchFilesIndex(self, nameData, fileData, fileIndex, searchString, category="", math=False, game=False, extension=""):
"""Search the files index using the namedata and returns the filedata"""
try:
fileFile = open(fileIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.fileIndex)
return None, None
count = 1
for line in fileFile:
count += 1
try:
if nameData[count] != None:
#category argument
if category in line:
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
#extension argument
if extension in line:
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
#Both game and math
if (game and math):
if ("/games/" in line or "/math/" in line or "/science" in line):
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#game option switch
elif game:
if "/games/" in line:
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
#math option switch
elif math:
if ("/math/" in line or "/science/" in line):
fileData[count] = line[:len(line) - 1]
else:
nameData[count] = None
fileData[count] = None
except:
pass
#Close the file and return
fileFile.close()
return fileData, nameData
|
[
"def",
"searchFilesIndex",
"(",
"self",
",",
"nameData",
",",
"fileData",
",",
"fileIndex",
",",
"searchString",
",",
"category",
"=",
"\"\"",
",",
"math",
"=",
"False",
",",
"game",
"=",
"False",
",",
"extension",
"=",
"\"\"",
")",
":",
"try",
":",
"fileFile",
"=",
"open",
"(",
"fileIndex",
",",
"'rt'",
")",
"except",
"IOError",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Error: Unable to read index file \"",
"+",
"self",
".",
"fileIndex",
")",
"return",
"None",
",",
"None",
"count",
"=",
"1",
"for",
"line",
"in",
"fileFile",
":",
"count",
"+=",
"1",
"try",
":",
"if",
"nameData",
"[",
"count",
"]",
"!=",
"None",
":",
"#category argument",
"if",
"category",
"in",
"line",
":",
"fileData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"fileData",
"[",
"count",
"]",
"=",
"None",
"#extension argument",
"if",
"extension",
"in",
"line",
":",
"fileData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"fileData",
"[",
"count",
"]",
"=",
"None",
"#Both game and math",
"if",
"(",
"game",
"and",
"math",
")",
":",
"if",
"(",
"\"/games/\"",
"in",
"line",
"or",
"\"/math/\"",
"in",
"line",
"or",
"\"/science\"",
"in",
"line",
")",
":",
"nameData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"#game option switch",
"elif",
"game",
":",
"if",
"\"/games/\"",
"in",
"line",
":",
"fileData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"fileData",
"[",
"count",
"]",
"=",
"None",
"#math option switch",
"elif",
"math",
":",
"if",
"(",
"\"/math/\"",
"in",
"line",
"or",
"\"/science/\"",
"in",
"line",
")",
":",
"fileData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"fileData",
"[",
"count",
"]",
"=",
"None",
"except",
":",
"pass",
"#Close the file and return",
"fileFile",
".",
"close",
"(",
")",
"return",
"fileData",
",",
"nameData"
] |
Search the files index using the namedata and returns the filedata
|
[
"Search",
"the",
"files",
"index",
"using",
"the",
"namedata",
"and",
"returns",
"the",
"filedata"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/index.py#L159-L209
|
243,435
|
TC01/calcpkg
|
calcrepo/index.py
|
Index.searchNamesIndex
|
def searchNamesIndex(self, nameIndex, nameData, searchString, category="", math=False, game=False, extension="", searchFiles=False):
"""Search the names index for a string and returns the namedata"""
nameData = {}
try:
nameFile = open(nameIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.fileIndex)
return None
count = 1
for line in nameFile:
count += 1
if searchString.lower() in line.lower():
#Extension argument
if extension in line:
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#category arg
if category in line and extension in line:
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Both game and math
if (game and math):
if ("/games/" in line or "/math/" in line or "/science" in line):
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Game option switch
elif game:
if "/games/" in line:
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Math option switch
elif math:
if ("/math/" in line or "/science/" in line):
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Close the name index and return
nameFile.close()
return nameData
|
python
|
def searchNamesIndex(self, nameIndex, nameData, searchString, category="", math=False, game=False, extension="", searchFiles=False):
"""Search the names index for a string and returns the namedata"""
nameData = {}
try:
nameFile = open(nameIndex, 'rt')
except IOError:
self.repo.printd("Error: Unable to read index file " + self.fileIndex)
return None
count = 1
for line in nameFile:
count += 1
if searchString.lower() in line.lower():
#Extension argument
if extension in line:
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#category arg
if category in line and extension in line:
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Both game and math
if (game and math):
if ("/games/" in line or "/math/" in line or "/science" in line):
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Game option switch
elif game:
if "/games/" in line:
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Math option switch
elif math:
if ("/math/" in line or "/science/" in line):
nameData[count] = line[:len(line) - 1]
else:
nameData[count] = None
#Close the name index and return
nameFile.close()
return nameData
|
[
"def",
"searchNamesIndex",
"(",
"self",
",",
"nameIndex",
",",
"nameData",
",",
"searchString",
",",
"category",
"=",
"\"\"",
",",
"math",
"=",
"False",
",",
"game",
"=",
"False",
",",
"extension",
"=",
"\"\"",
",",
"searchFiles",
"=",
"False",
")",
":",
"nameData",
"=",
"{",
"}",
"try",
":",
"nameFile",
"=",
"open",
"(",
"nameIndex",
",",
"'rt'",
")",
"except",
"IOError",
":",
"self",
".",
"repo",
".",
"printd",
"(",
"\"Error: Unable to read index file \"",
"+",
"self",
".",
"fileIndex",
")",
"return",
"None",
"count",
"=",
"1",
"for",
"line",
"in",
"nameFile",
":",
"count",
"+=",
"1",
"if",
"searchString",
".",
"lower",
"(",
")",
"in",
"line",
".",
"lower",
"(",
")",
":",
"#Extension argument",
"if",
"extension",
"in",
"line",
":",
"nameData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"#category arg",
"if",
"category",
"in",
"line",
"and",
"extension",
"in",
"line",
":",
"nameData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"#Both game and math",
"if",
"(",
"game",
"and",
"math",
")",
":",
"if",
"(",
"\"/games/\"",
"in",
"line",
"or",
"\"/math/\"",
"in",
"line",
"or",
"\"/science\"",
"in",
"line",
")",
":",
"nameData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"#Game option switch",
"elif",
"game",
":",
"if",
"\"/games/\"",
"in",
"line",
":",
"nameData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"#Math option switch",
"elif",
"math",
":",
"if",
"(",
"\"/math/\"",
"in",
"line",
"or",
"\"/science/\"",
"in",
"line",
")",
":",
"nameData",
"[",
"count",
"]",
"=",
"line",
"[",
":",
"len",
"(",
"line",
")",
"-",
"1",
"]",
"else",
":",
"nameData",
"[",
"count",
"]",
"=",
"None",
"#Close the name index and return",
"nameFile",
".",
"close",
"(",
")",
"return",
"nameData"
] |
Search the names index for a string and returns the namedata
|
[
"Search",
"the",
"names",
"index",
"for",
"a",
"string",
"and",
"returns",
"the",
"namedata"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/index.py#L211-L255
|
243,436
|
ronaldguillen/wave
|
wave/negotiation.py
|
DefaultContentNegotiation.select_parser
|
def select_parser(self, request, parsers):
"""
Given a list of parsers and a media type, return the appropriate
parser to handle the incoming request.
"""
for parser in parsers:
if media_type_matches(parser.media_type, request.content_type):
return parser
return None
|
python
|
def select_parser(self, request, parsers):
"""
Given a list of parsers and a media type, return the appropriate
parser to handle the incoming request.
"""
for parser in parsers:
if media_type_matches(parser.media_type, request.content_type):
return parser
return None
|
[
"def",
"select_parser",
"(",
"self",
",",
"request",
",",
"parsers",
")",
":",
"for",
"parser",
"in",
"parsers",
":",
"if",
"media_type_matches",
"(",
"parser",
".",
"media_type",
",",
"request",
".",
"content_type",
")",
":",
"return",
"parser",
"return",
"None"
] |
Given a list of parsers and a media type, return the appropriate
parser to handle the incoming request.
|
[
"Given",
"a",
"list",
"of",
"parsers",
"and",
"a",
"media",
"type",
"return",
"the",
"appropriate",
"parser",
"to",
"handle",
"the",
"incoming",
"request",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/negotiation.py#L27-L35
|
243,437
|
ronaldguillen/wave
|
wave/negotiation.py
|
DefaultContentNegotiation.filter_renderers
|
def filter_renderers(self, renderers, format):
"""
If there is a '.json' style format suffix, filter the renderers
so that we only negotiation against those that accept that format.
"""
renderers = [renderer for renderer in renderers
if renderer.format == format]
if not renderers:
raise Http404
return renderers
|
python
|
def filter_renderers(self, renderers, format):
"""
If there is a '.json' style format suffix, filter the renderers
so that we only negotiation against those that accept that format.
"""
renderers = [renderer for renderer in renderers
if renderer.format == format]
if not renderers:
raise Http404
return renderers
|
[
"def",
"filter_renderers",
"(",
"self",
",",
"renderers",
",",
"format",
")",
":",
"renderers",
"=",
"[",
"renderer",
"for",
"renderer",
"in",
"renderers",
"if",
"renderer",
".",
"format",
"==",
"format",
"]",
"if",
"not",
"renderers",
":",
"raise",
"Http404",
"return",
"renderers"
] |
If there is a '.json' style format suffix, filter the renderers
so that we only negotiation against those that accept that format.
|
[
"If",
"there",
"is",
"a",
".",
"json",
"style",
"format",
"suffix",
"filter",
"the",
"renderers",
"so",
"that",
"we",
"only",
"negotiation",
"against",
"those",
"that",
"accept",
"that",
"format",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/negotiation.py#L80-L89
|
243,438
|
ronaldguillen/wave
|
wave/negotiation.py
|
DefaultContentNegotiation.get_accept_list
|
def get_accept_list(self, request):
"""
Given the incoming request, return a tokenised list of media
type strings.
"""
header = request.META.get('HTTP_ACCEPT', '*/*')
return [token.strip() for token in header.split(',')]
|
python
|
def get_accept_list(self, request):
"""
Given the incoming request, return a tokenised list of media
type strings.
"""
header = request.META.get('HTTP_ACCEPT', '*/*')
return [token.strip() for token in header.split(',')]
|
[
"def",
"get_accept_list",
"(",
"self",
",",
"request",
")",
":",
"header",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT'",
",",
"'*/*'",
")",
"return",
"[",
"token",
".",
"strip",
"(",
")",
"for",
"token",
"in",
"header",
".",
"split",
"(",
"','",
")",
"]"
] |
Given the incoming request, return a tokenised list of media
type strings.
|
[
"Given",
"the",
"incoming",
"request",
"return",
"a",
"tokenised",
"list",
"of",
"media",
"type",
"strings",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/negotiation.py#L91-L97
|
243,439
|
etcher-be/emiz
|
emiz/parking_spots.py
|
unit_pos_to_spot
|
def unit_pos_to_spot(unit_pos) -> ParkingSpot:
"""
Translates a unit position to a known parking spot
Args:
unit_pos: unit position as Vec2
Returns: ParkingSpot object
"""
min_ = 50
res = None
for airport in parkings:
for spot in parkings[airport]: # type: ignore
spot_pos = parkings[airport][spot] # type: ignore
dist = math.hypot(unit_pos[0] - spot_pos[0], unit_pos[1] - spot_pos[1])
if dist < min_:
min_ = dist # type: ignore
res = ParkingSpot(airport=airport, spot=spot)
return res
|
python
|
def unit_pos_to_spot(unit_pos) -> ParkingSpot:
"""
Translates a unit position to a known parking spot
Args:
unit_pos: unit position as Vec2
Returns: ParkingSpot object
"""
min_ = 50
res = None
for airport in parkings:
for spot in parkings[airport]: # type: ignore
spot_pos = parkings[airport][spot] # type: ignore
dist = math.hypot(unit_pos[0] - spot_pos[0], unit_pos[1] - spot_pos[1])
if dist < min_:
min_ = dist # type: ignore
res = ParkingSpot(airport=airport, spot=spot)
return res
|
[
"def",
"unit_pos_to_spot",
"(",
"unit_pos",
")",
"->",
"ParkingSpot",
":",
"min_",
"=",
"50",
"res",
"=",
"None",
"for",
"airport",
"in",
"parkings",
":",
"for",
"spot",
"in",
"parkings",
"[",
"airport",
"]",
":",
"# type: ignore",
"spot_pos",
"=",
"parkings",
"[",
"airport",
"]",
"[",
"spot",
"]",
"# type: ignore",
"dist",
"=",
"math",
".",
"hypot",
"(",
"unit_pos",
"[",
"0",
"]",
"-",
"spot_pos",
"[",
"0",
"]",
",",
"unit_pos",
"[",
"1",
"]",
"-",
"spot_pos",
"[",
"1",
"]",
")",
"if",
"dist",
"<",
"min_",
":",
"min_",
"=",
"dist",
"# type: ignore",
"res",
"=",
"ParkingSpot",
"(",
"airport",
"=",
"airport",
",",
"spot",
"=",
"spot",
")",
"return",
"res"
] |
Translates a unit position to a known parking spot
Args:
unit_pos: unit position as Vec2
Returns: ParkingSpot object
|
[
"Translates",
"a",
"unit",
"position",
"to",
"a",
"known",
"parking",
"spot"
] |
1c3e32711921d7e600e85558ffe5d337956372de
|
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/parking_spots.py#L39-L58
|
243,440
|
stephanepechard/projy
|
projy/collectors/Collector.py
|
Collector.collect
|
def collect(self):
""" Select the best suited data of all available in the subclasses.
In each subclass, the functions alphabetical order should
correspond to their importance.
Here, the first non null value is returned.
"""
class_functions = []
for key in self.__class__.__dict__.keys():
func = self.__class__.__dict__[key]
if (inspect.isfunction(func)):
class_functions.append(func)
functions = sorted(class_functions, key=lambda func: func.__name__)
for function in functions:
value = function(self)
if value:
return value
|
python
|
def collect(self):
""" Select the best suited data of all available in the subclasses.
In each subclass, the functions alphabetical order should
correspond to their importance.
Here, the first non null value is returned.
"""
class_functions = []
for key in self.__class__.__dict__.keys():
func = self.__class__.__dict__[key]
if (inspect.isfunction(func)):
class_functions.append(func)
functions = sorted(class_functions, key=lambda func: func.__name__)
for function in functions:
value = function(self)
if value:
return value
|
[
"def",
"collect",
"(",
"self",
")",
":",
"class_functions",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"__class__",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"func",
"=",
"self",
".",
"__class__",
".",
"__dict__",
"[",
"key",
"]",
"if",
"(",
"inspect",
".",
"isfunction",
"(",
"func",
")",
")",
":",
"class_functions",
".",
"append",
"(",
"func",
")",
"functions",
"=",
"sorted",
"(",
"class_functions",
",",
"key",
"=",
"lambda",
"func",
":",
"func",
".",
"__name__",
")",
"for",
"function",
"in",
"functions",
":",
"value",
"=",
"function",
"(",
"self",
")",
"if",
"value",
":",
"return",
"value"
] |
Select the best suited data of all available in the subclasses.
In each subclass, the functions alphabetical order should
correspond to their importance.
Here, the first non null value is returned.
|
[
"Select",
"the",
"best",
"suited",
"data",
"of",
"all",
"available",
"in",
"the",
"subclasses",
".",
"In",
"each",
"subclass",
"the",
"functions",
"alphabetical",
"order",
"should",
"correspond",
"to",
"their",
"importance",
".",
"Here",
"the",
"first",
"non",
"null",
"value",
"is",
"returned",
"."
] |
3146b0e3c207b977e1b51fcb33138746dae83c23
|
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/collectors/Collector.py#L15-L31
|
243,441
|
raags/passdb
|
passdb/manage_passdb.py
|
MPassdb.init
|
def init(self):
"""
Initialize a new password db store
"""
self.y = {"version": int(time.time())}
recipient_email = raw_input("Enter Email ID: ")
self.import_key(emailid=recipient_email)
self.encrypt(emailid_list=[recipient_email])
|
python
|
def init(self):
"""
Initialize a new password db store
"""
self.y = {"version": int(time.time())}
recipient_email = raw_input("Enter Email ID: ")
self.import_key(emailid=recipient_email)
self.encrypt(emailid_list=[recipient_email])
|
[
"def",
"init",
"(",
"self",
")",
":",
"self",
".",
"y",
"=",
"{",
"\"version\"",
":",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"}",
"recipient_email",
"=",
"raw_input",
"(",
"\"Enter Email ID: \"",
")",
"self",
".",
"import_key",
"(",
"emailid",
"=",
"recipient_email",
")",
"self",
".",
"encrypt",
"(",
"emailid_list",
"=",
"[",
"recipient_email",
"]",
")"
] |
Initialize a new password db store
|
[
"Initialize",
"a",
"new",
"password",
"db",
"store"
] |
7fd6665e291bbfb4db59c1230ae0257e48ad503e
|
https://github.com/raags/passdb/blob/7fd6665e291bbfb4db59c1230ae0257e48ad503e/passdb/manage_passdb.py#L28-L35
|
243,442
|
raags/passdb
|
passdb/manage_passdb.py
|
MPassdb.list_users
|
def list_users(self):
"""
Get user list from the encrypted passdb file
"""
crypt = self._decrypt_file()
self.logger.info(crypt.stderr)
raw_userlist = crypt.stderr.split('\n')
userlist = list()
for index, line in enumerate(raw_userlist):
if 'gpg: encrypted' in line:
m = re.search('ID (\w+)', line)
keyid = m.group(1).strip()
userline = raw_userlist[index+1].strip()
userlist.append((keyid, userline))
return userlist
|
python
|
def list_users(self):
"""
Get user list from the encrypted passdb file
"""
crypt = self._decrypt_file()
self.logger.info(crypt.stderr)
raw_userlist = crypt.stderr.split('\n')
userlist = list()
for index, line in enumerate(raw_userlist):
if 'gpg: encrypted' in line:
m = re.search('ID (\w+)', line)
keyid = m.group(1).strip()
userline = raw_userlist[index+1].strip()
userlist.append((keyid, userline))
return userlist
|
[
"def",
"list_users",
"(",
"self",
")",
":",
"crypt",
"=",
"self",
".",
"_decrypt_file",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"crypt",
".",
"stderr",
")",
"raw_userlist",
"=",
"crypt",
".",
"stderr",
".",
"split",
"(",
"'\\n'",
")",
"userlist",
"=",
"list",
"(",
")",
"for",
"index",
",",
"line",
"in",
"enumerate",
"(",
"raw_userlist",
")",
":",
"if",
"'gpg: encrypted'",
"in",
"line",
":",
"m",
"=",
"re",
".",
"search",
"(",
"'ID (\\w+)'",
",",
"line",
")",
"keyid",
"=",
"m",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"userline",
"=",
"raw_userlist",
"[",
"index",
"+",
"1",
"]",
".",
"strip",
"(",
")",
"userlist",
".",
"append",
"(",
"(",
"keyid",
",",
"userline",
")",
")",
"return",
"userlist"
] |
Get user list from the encrypted passdb file
|
[
"Get",
"user",
"list",
"from",
"the",
"encrypted",
"passdb",
"file"
] |
7fd6665e291bbfb4db59c1230ae0257e48ad503e
|
https://github.com/raags/passdb/blob/7fd6665e291bbfb4db59c1230ae0257e48ad503e/passdb/manage_passdb.py#L37-L52
|
243,443
|
raags/passdb
|
passdb/manage_passdb.py
|
MPassdb.add_user
|
def add_user(self, recipient_email):
"""
Add user to encryption
"""
self.import_key(emailid=recipient_email)
emailid_list = self.list_user_emails()
self.y = self.decrypt()
emailid_list.append(recipient_email)
self.encrypt(emailid_list=emailid_list)
|
python
|
def add_user(self, recipient_email):
"""
Add user to encryption
"""
self.import_key(emailid=recipient_email)
emailid_list = self.list_user_emails()
self.y = self.decrypt()
emailid_list.append(recipient_email)
self.encrypt(emailid_list=emailid_list)
|
[
"def",
"add_user",
"(",
"self",
",",
"recipient_email",
")",
":",
"self",
".",
"import_key",
"(",
"emailid",
"=",
"recipient_email",
")",
"emailid_list",
"=",
"self",
".",
"list_user_emails",
"(",
")",
"self",
".",
"y",
"=",
"self",
".",
"decrypt",
"(",
")",
"emailid_list",
".",
"append",
"(",
"recipient_email",
")",
"self",
".",
"encrypt",
"(",
"emailid_list",
"=",
"emailid_list",
")"
] |
Add user to encryption
|
[
"Add",
"user",
"to",
"encryption"
] |
7fd6665e291bbfb4db59c1230ae0257e48ad503e
|
https://github.com/raags/passdb/blob/7fd6665e291bbfb4db59c1230ae0257e48ad503e/passdb/manage_passdb.py#L72-L80
|
243,444
|
raags/passdb
|
passdb/manage_passdb.py
|
MPassdb.delete_user
|
def delete_user(self, recipient_email):
"""
Remove user from encryption
"""
emailid_list = self.list_user_emails()
if recipient_email not in emailid_list:
raise Exception("User {0} not present!".format(recipient_email))
else:
emailid_list.remove(recipient_email)
self.y = self.decrypt()
self.encrypt(emailid_list=emailid_list)
|
python
|
def delete_user(self, recipient_email):
"""
Remove user from encryption
"""
emailid_list = self.list_user_emails()
if recipient_email not in emailid_list:
raise Exception("User {0} not present!".format(recipient_email))
else:
emailid_list.remove(recipient_email)
self.y = self.decrypt()
self.encrypt(emailid_list=emailid_list)
|
[
"def",
"delete_user",
"(",
"self",
",",
"recipient_email",
")",
":",
"emailid_list",
"=",
"self",
".",
"list_user_emails",
"(",
")",
"if",
"recipient_email",
"not",
"in",
"emailid_list",
":",
"raise",
"Exception",
"(",
"\"User {0} not present!\"",
".",
"format",
"(",
"recipient_email",
")",
")",
"else",
":",
"emailid_list",
".",
"remove",
"(",
"recipient_email",
")",
"self",
".",
"y",
"=",
"self",
".",
"decrypt",
"(",
")",
"self",
".",
"encrypt",
"(",
"emailid_list",
"=",
"emailid_list",
")"
] |
Remove user from encryption
|
[
"Remove",
"user",
"from",
"encryption"
] |
7fd6665e291bbfb4db59c1230ae0257e48ad503e
|
https://github.com/raags/passdb/blob/7fd6665e291bbfb4db59c1230ae0257e48ad503e/passdb/manage_passdb.py#L82-L92
|
243,445
|
edeposit/edeposit.amqp.ftp
|
src/edeposit/amqp/ftp/decoders/__init__.py
|
parse_meta
|
def parse_meta(filename, data):
"""
Parse `data` to EPublication.
Args:
filename (str): Used to choose right parser based at suffix.
data (str): Content of the metadata file.
Returns:
EPublication: object.
"""
if "." not in filename:
raise MetaParsingException(
"Can't recognize type of your metadata ('%s')!" % filename
)
suffix = filename.rsplit(".", 1)[1].lower()
if suffix not in SUPPORTED_FILES:
raise MetaParsingException("Can't parse file of type '%s'!" % suffix)
fp = validator.FieldParser()
for key, val in SUPPORTED_FILES[suffix](data).items():
fp.process(key, val)
return fp.get_epublication()
|
python
|
def parse_meta(filename, data):
"""
Parse `data` to EPublication.
Args:
filename (str): Used to choose right parser based at suffix.
data (str): Content of the metadata file.
Returns:
EPublication: object.
"""
if "." not in filename:
raise MetaParsingException(
"Can't recognize type of your metadata ('%s')!" % filename
)
suffix = filename.rsplit(".", 1)[1].lower()
if suffix not in SUPPORTED_FILES:
raise MetaParsingException("Can't parse file of type '%s'!" % suffix)
fp = validator.FieldParser()
for key, val in SUPPORTED_FILES[suffix](data).items():
fp.process(key, val)
return fp.get_epublication()
|
[
"def",
"parse_meta",
"(",
"filename",
",",
"data",
")",
":",
"if",
"\".\"",
"not",
"in",
"filename",
":",
"raise",
"MetaParsingException",
"(",
"\"Can't recognize type of your metadata ('%s')!\"",
"%",
"filename",
")",
"suffix",
"=",
"filename",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"suffix",
"not",
"in",
"SUPPORTED_FILES",
":",
"raise",
"MetaParsingException",
"(",
"\"Can't parse file of type '%s'!\"",
"%",
"suffix",
")",
"fp",
"=",
"validator",
".",
"FieldParser",
"(",
")",
"for",
"key",
",",
"val",
"in",
"SUPPORTED_FILES",
"[",
"suffix",
"]",
"(",
"data",
")",
".",
"items",
"(",
")",
":",
"fp",
".",
"process",
"(",
"key",
",",
"val",
")",
"return",
"fp",
".",
"get_epublication",
"(",
")"
] |
Parse `data` to EPublication.
Args:
filename (str): Used to choose right parser based at suffix.
data (str): Content of the metadata file.
Returns:
EPublication: object.
|
[
"Parse",
"data",
"to",
"EPublication",
"."
] |
fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71
|
https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/decoders/__init__.py#L30-L55
|
243,446
|
nefarioustim/parker
|
parker/consumemodel.py
|
get_instance
|
def get_instance(page_to_consume):
"""Return an instance of ConsumeModel."""
global _instances
if isinstance(page_to_consume, basestring):
uri = page_to_consume
page_to_consume = consumepage.get_instance(uri)
elif isinstance(page_to_consume, consumepage.ConsumePage):
uri = page_to_consume.uri
else:
raise TypeError(
"get_instance() expects a parker.ConsumePage "
"or basestring derivative."
)
try:
instance = _instances[uri]
except KeyError:
instance = ConsumeModel(page_to_consume)
_instances[uri] = instance
return instance
|
python
|
def get_instance(page_to_consume):
"""Return an instance of ConsumeModel."""
global _instances
if isinstance(page_to_consume, basestring):
uri = page_to_consume
page_to_consume = consumepage.get_instance(uri)
elif isinstance(page_to_consume, consumepage.ConsumePage):
uri = page_to_consume.uri
else:
raise TypeError(
"get_instance() expects a parker.ConsumePage "
"or basestring derivative."
)
try:
instance = _instances[uri]
except KeyError:
instance = ConsumeModel(page_to_consume)
_instances[uri] = instance
return instance
|
[
"def",
"get_instance",
"(",
"page_to_consume",
")",
":",
"global",
"_instances",
"if",
"isinstance",
"(",
"page_to_consume",
",",
"basestring",
")",
":",
"uri",
"=",
"page_to_consume",
"page_to_consume",
"=",
"consumepage",
".",
"get_instance",
"(",
"uri",
")",
"elif",
"isinstance",
"(",
"page_to_consume",
",",
"consumepage",
".",
"ConsumePage",
")",
":",
"uri",
"=",
"page_to_consume",
".",
"uri",
"else",
":",
"raise",
"TypeError",
"(",
"\"get_instance() expects a parker.ConsumePage \"",
"\"or basestring derivative.\"",
")",
"try",
":",
"instance",
"=",
"_instances",
"[",
"uri",
"]",
"except",
"KeyError",
":",
"instance",
"=",
"ConsumeModel",
"(",
"page_to_consume",
")",
"_instances",
"[",
"uri",
"]",
"=",
"instance",
"return",
"instance"
] |
Return an instance of ConsumeModel.
|
[
"Return",
"an",
"instance",
"of",
"ConsumeModel",
"."
] |
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
|
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/consumemodel.py#L12-L32
|
243,447
|
nefarioustim/parker
|
parker/consumemodel.py
|
ConsumeModel.get_dict
|
def get_dict(self):
"""Return a dictionary of the object primed for dumping."""
data = self.data_dict.copy()
data.update({
"class": self.classification,
"tags": self.tags,
"key_value_data": self.key_value_dict,
"crumbs": self.crumb_list if len(self.crumb_list) > 0 else None,
"media": [
mediafile.filename
if mediafile.filename is not None
else mediafile.uri
for mediafile in self.media_list
] if len(self.media_list) > 0 else None,
"uri": self.uri,
"dumped": datetime.utcnow().isoformat(),
})
return data
|
python
|
def get_dict(self):
"""Return a dictionary of the object primed for dumping."""
data = self.data_dict.copy()
data.update({
"class": self.classification,
"tags": self.tags,
"key_value_data": self.key_value_dict,
"crumbs": self.crumb_list if len(self.crumb_list) > 0 else None,
"media": [
mediafile.filename
if mediafile.filename is not None
else mediafile.uri
for mediafile in self.media_list
] if len(self.media_list) > 0 else None,
"uri": self.uri,
"dumped": datetime.utcnow().isoformat(),
})
return data
|
[
"def",
"get_dict",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data_dict",
".",
"copy",
"(",
")",
"data",
".",
"update",
"(",
"{",
"\"class\"",
":",
"self",
".",
"classification",
",",
"\"tags\"",
":",
"self",
".",
"tags",
",",
"\"key_value_data\"",
":",
"self",
".",
"key_value_dict",
",",
"\"crumbs\"",
":",
"self",
".",
"crumb_list",
"if",
"len",
"(",
"self",
".",
"crumb_list",
")",
">",
"0",
"else",
"None",
",",
"\"media\"",
":",
"[",
"mediafile",
".",
"filename",
"if",
"mediafile",
".",
"filename",
"is",
"not",
"None",
"else",
"mediafile",
".",
"uri",
"for",
"mediafile",
"in",
"self",
".",
"media_list",
"]",
"if",
"len",
"(",
"self",
".",
"media_list",
")",
">",
"0",
"else",
"None",
",",
"\"uri\"",
":",
"self",
".",
"uri",
",",
"\"dumped\"",
":",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
",",
"}",
")",
"return",
"data"
] |
Return a dictionary of the object primed for dumping.
|
[
"Return",
"a",
"dictionary",
"of",
"the",
"object",
"primed",
"for",
"dumping",
"."
] |
ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6
|
https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/consumemodel.py#L75-L94
|
243,448
|
GemHQ/round-py
|
round/devices.py
|
Devices.create
|
def create(self, name, redirect_uri=None):
"""Create a new Device object.
Devices tie Users and Applications together. For your Application to
access and act on behalf of a User, the User must authorize a Device
created by your Application.
This function will return a `device_token` which you must store and use
after the Device is approved in
`client.authenticate_device(api_token, device_token)`
The second value returned is an `mfa_uri` which is the location the User
must visit to approve the new device. After this function completes,
you should launch a new browser tab or webview with this value as the
location. After the User approves the Device, they will be redirected to
the redirect_uri you specify in this call.
Args:
name (str): Human-readable name for the device
(e.g. "Suzanne's iPhone")
redirect_uri (str, optional): A URI to which to redirect the User after
they approve the new Device.
Returns: A tuple of (device_token, mfa_uri)
"""
data = dict(name=name)
if redirect_uri:
data['redirect_uri'] = redirect_uri
auth_request_resource = self.resource.create(data)
return (auth_request_resource.attributes['metadata']['device_token'],
auth_request_resource.attributes['mfa_uri'])
|
python
|
def create(self, name, redirect_uri=None):
"""Create a new Device object.
Devices tie Users and Applications together. For your Application to
access and act on behalf of a User, the User must authorize a Device
created by your Application.
This function will return a `device_token` which you must store and use
after the Device is approved in
`client.authenticate_device(api_token, device_token)`
The second value returned is an `mfa_uri` which is the location the User
must visit to approve the new device. After this function completes,
you should launch a new browser tab or webview with this value as the
location. After the User approves the Device, they will be redirected to
the redirect_uri you specify in this call.
Args:
name (str): Human-readable name for the device
(e.g. "Suzanne's iPhone")
redirect_uri (str, optional): A URI to which to redirect the User after
they approve the new Device.
Returns: A tuple of (device_token, mfa_uri)
"""
data = dict(name=name)
if redirect_uri:
data['redirect_uri'] = redirect_uri
auth_request_resource = self.resource.create(data)
return (auth_request_resource.attributes['metadata']['device_token'],
auth_request_resource.attributes['mfa_uri'])
|
[
"def",
"create",
"(",
"self",
",",
"name",
",",
"redirect_uri",
"=",
"None",
")",
":",
"data",
"=",
"dict",
"(",
"name",
"=",
"name",
")",
"if",
"redirect_uri",
":",
"data",
"[",
"'redirect_uri'",
"]",
"=",
"redirect_uri",
"auth_request_resource",
"=",
"self",
".",
"resource",
".",
"create",
"(",
"data",
")",
"return",
"(",
"auth_request_resource",
".",
"attributes",
"[",
"'metadata'",
"]",
"[",
"'device_token'",
"]",
",",
"auth_request_resource",
".",
"attributes",
"[",
"'mfa_uri'",
"]",
")"
] |
Create a new Device object.
Devices tie Users and Applications together. For your Application to
access and act on behalf of a User, the User must authorize a Device
created by your Application.
This function will return a `device_token` which you must store and use
after the Device is approved in
`client.authenticate_device(api_token, device_token)`
The second value returned is an `mfa_uri` which is the location the User
must visit to approve the new device. After this function completes,
you should launch a new browser tab or webview with this value as the
location. After the User approves the Device, they will be redirected to
the redirect_uri you specify in this call.
Args:
name (str): Human-readable name for the device
(e.g. "Suzanne's iPhone")
redirect_uri (str, optional): A URI to which to redirect the User after
they approve the new Device.
Returns: A tuple of (device_token, mfa_uri)
|
[
"Create",
"a",
"new",
"Device",
"object",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/devices.py#L16-L49
|
243,449
|
rdo-management/python-rdomanager-oscplugin
|
rdomanager_oscplugin/plugin.py
|
build_option_parser
|
def build_option_parser(parser):
"""Hook to add global options
Called from openstackclient.shell.OpenStackShell.__init__()
after the builtin parser has been initialized. This is
where a plugin can add global options such as an API version setting.
:param argparse.ArgumentParser parser: The parser object that has been
initialized by OpenStackShell.
"""
parser.add_argument(
'--os-rdomanager-oscplugin-api-version',
metavar='<rdomanager-oscplugin-api-version>',
default=utils.env(
'OS_RDOMANAGER_OSCPLUGIN_API_VERSION',
default=DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION),
help='RDO Manager OSC Plugin API version, default=' +
DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION +
' (Env: OS_RDOMANAGER_OSCPLUGIN_API_VERSION)')
return parser
|
python
|
def build_option_parser(parser):
"""Hook to add global options
Called from openstackclient.shell.OpenStackShell.__init__()
after the builtin parser has been initialized. This is
where a plugin can add global options such as an API version setting.
:param argparse.ArgumentParser parser: The parser object that has been
initialized by OpenStackShell.
"""
parser.add_argument(
'--os-rdomanager-oscplugin-api-version',
metavar='<rdomanager-oscplugin-api-version>',
default=utils.env(
'OS_RDOMANAGER_OSCPLUGIN_API_VERSION',
default=DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION),
help='RDO Manager OSC Plugin API version, default=' +
DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION +
' (Env: OS_RDOMANAGER_OSCPLUGIN_API_VERSION)')
return parser
|
[
"def",
"build_option_parser",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--os-rdomanager-oscplugin-api-version'",
",",
"metavar",
"=",
"'<rdomanager-oscplugin-api-version>'",
",",
"default",
"=",
"utils",
".",
"env",
"(",
"'OS_RDOMANAGER_OSCPLUGIN_API_VERSION'",
",",
"default",
"=",
"DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION",
")",
",",
"help",
"=",
"'RDO Manager OSC Plugin API version, default='",
"+",
"DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION",
"+",
"' (Env: OS_RDOMANAGER_OSCPLUGIN_API_VERSION)'",
")",
"return",
"parser"
] |
Hook to add global options
Called from openstackclient.shell.OpenStackShell.__init__()
after the builtin parser has been initialized. This is
where a plugin can add global options such as an API version setting.
:param argparse.ArgumentParser parser: The parser object that has been
initialized by OpenStackShell.
|
[
"Hook",
"to",
"add",
"global",
"options"
] |
165a166fb2e5a2598380779b35812b8b8478c4fb
|
https://github.com/rdo-management/python-rdomanager-oscplugin/blob/165a166fb2e5a2598380779b35812b8b8478c4fb/rdomanager_oscplugin/plugin.py#L42-L61
|
243,450
|
rdo-management/python-rdomanager-oscplugin
|
rdomanager_oscplugin/plugin.py
|
ClientWrapper.baremetal
|
def baremetal(self):
"""Returns an baremetal service client"""
# TODO(d0ugal): When the ironicclient has it's own OSC plugin, the
# following client handling code should be removed in favor of the
# upstream version.
if self._baremetal is not None:
return self._baremetal
endpoint = self._instance.get_endpoint_for_service_type(
"baremetal",
region_name=self._instance._region_name,
)
token = self._instance.auth.get_token(self._instance.session)
self._baremetal = ironic_client.get_client(
1, os_auth_token=token, ironic_url=endpoint,
ca_file=self._instance._cli_options.os_cacert)
return self._baremetal
|
python
|
def baremetal(self):
"""Returns an baremetal service client"""
# TODO(d0ugal): When the ironicclient has it's own OSC plugin, the
# following client handling code should be removed in favor of the
# upstream version.
if self._baremetal is not None:
return self._baremetal
endpoint = self._instance.get_endpoint_for_service_type(
"baremetal",
region_name=self._instance._region_name,
)
token = self._instance.auth.get_token(self._instance.session)
self._baremetal = ironic_client.get_client(
1, os_auth_token=token, ironic_url=endpoint,
ca_file=self._instance._cli_options.os_cacert)
return self._baremetal
|
[
"def",
"baremetal",
"(",
"self",
")",
":",
"# TODO(d0ugal): When the ironicclient has it's own OSC plugin, the",
"# following client handling code should be removed in favor of the",
"# upstream version.",
"if",
"self",
".",
"_baremetal",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_baremetal",
"endpoint",
"=",
"self",
".",
"_instance",
".",
"get_endpoint_for_service_type",
"(",
"\"baremetal\"",
",",
"region_name",
"=",
"self",
".",
"_instance",
".",
"_region_name",
",",
")",
"token",
"=",
"self",
".",
"_instance",
".",
"auth",
".",
"get_token",
"(",
"self",
".",
"_instance",
".",
"session",
")",
"self",
".",
"_baremetal",
"=",
"ironic_client",
".",
"get_client",
"(",
"1",
",",
"os_auth_token",
"=",
"token",
",",
"ironic_url",
"=",
"endpoint",
",",
"ca_file",
"=",
"self",
".",
"_instance",
".",
"_cli_options",
".",
"os_cacert",
")",
"return",
"self",
".",
"_baremetal"
] |
Returns an baremetal service client
|
[
"Returns",
"an",
"baremetal",
"service",
"client"
] |
165a166fb2e5a2598380779b35812b8b8478c4fb
|
https://github.com/rdo-management/python-rdomanager-oscplugin/blob/165a166fb2e5a2598380779b35812b8b8478c4fb/rdomanager_oscplugin/plugin.py#L72-L93
|
243,451
|
rdo-management/python-rdomanager-oscplugin
|
rdomanager_oscplugin/plugin.py
|
ClientWrapper.orchestration
|
def orchestration(self):
"""Returns an orchestration service client"""
# TODO(d0ugal): This code is based on the upstream WIP implementation
# and should be removed when it lands:
# https://review.openstack.org/#/c/111786
if self._orchestration is not None:
return self._orchestration
API_VERSIONS = {
'1': 'heatclient.v1.client.Client',
}
heat_client = utils.get_client_class(
API_NAME,
self._instance._api_version[API_NAME],
API_VERSIONS)
LOG.debug('Instantiating orchestration client: %s', heat_client)
endpoint = self._instance.get_endpoint_for_service_type(
'orchestration')
token = self._instance.auth.get_token(self._instance.session)
client = heat_client(
endpoint=endpoint,
auth_url=self._instance._auth_url,
token=token,
username=self._instance._username,
password=self._instance._password,
region_name=self._instance._region_name,
insecure=self._instance._insecure,
ca_file=self._instance._cli_options.os_cacert,
)
self._orchestration = client
return self._orchestration
|
python
|
def orchestration(self):
"""Returns an orchestration service client"""
# TODO(d0ugal): This code is based on the upstream WIP implementation
# and should be removed when it lands:
# https://review.openstack.org/#/c/111786
if self._orchestration is not None:
return self._orchestration
API_VERSIONS = {
'1': 'heatclient.v1.client.Client',
}
heat_client = utils.get_client_class(
API_NAME,
self._instance._api_version[API_NAME],
API_VERSIONS)
LOG.debug('Instantiating orchestration client: %s', heat_client)
endpoint = self._instance.get_endpoint_for_service_type(
'orchestration')
token = self._instance.auth.get_token(self._instance.session)
client = heat_client(
endpoint=endpoint,
auth_url=self._instance._auth_url,
token=token,
username=self._instance._username,
password=self._instance._password,
region_name=self._instance._region_name,
insecure=self._instance._insecure,
ca_file=self._instance._cli_options.os_cacert,
)
self._orchestration = client
return self._orchestration
|
[
"def",
"orchestration",
"(",
"self",
")",
":",
"# TODO(d0ugal): This code is based on the upstream WIP implementation",
"# and should be removed when it lands:",
"# https://review.openstack.org/#/c/111786",
"if",
"self",
".",
"_orchestration",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_orchestration",
"API_VERSIONS",
"=",
"{",
"'1'",
":",
"'heatclient.v1.client.Client'",
",",
"}",
"heat_client",
"=",
"utils",
".",
"get_client_class",
"(",
"API_NAME",
",",
"self",
".",
"_instance",
".",
"_api_version",
"[",
"API_NAME",
"]",
",",
"API_VERSIONS",
")",
"LOG",
".",
"debug",
"(",
"'Instantiating orchestration client: %s'",
",",
"heat_client",
")",
"endpoint",
"=",
"self",
".",
"_instance",
".",
"get_endpoint_for_service_type",
"(",
"'orchestration'",
")",
"token",
"=",
"self",
".",
"_instance",
".",
"auth",
".",
"get_token",
"(",
"self",
".",
"_instance",
".",
"session",
")",
"client",
"=",
"heat_client",
"(",
"endpoint",
"=",
"endpoint",
",",
"auth_url",
"=",
"self",
".",
"_instance",
".",
"_auth_url",
",",
"token",
"=",
"token",
",",
"username",
"=",
"self",
".",
"_instance",
".",
"_username",
",",
"password",
"=",
"self",
".",
"_instance",
".",
"_password",
",",
"region_name",
"=",
"self",
".",
"_instance",
".",
"_region_name",
",",
"insecure",
"=",
"self",
".",
"_instance",
".",
"_insecure",
",",
"ca_file",
"=",
"self",
".",
"_instance",
".",
"_cli_options",
".",
"os_cacert",
",",
")",
"self",
".",
"_orchestration",
"=",
"client",
"return",
"self",
".",
"_orchestration"
] |
Returns an orchestration service client
|
[
"Returns",
"an",
"orchestration",
"service",
"client"
] |
165a166fb2e5a2598380779b35812b8b8478c4fb
|
https://github.com/rdo-management/python-rdomanager-oscplugin/blob/165a166fb2e5a2598380779b35812b8b8478c4fb/rdomanager_oscplugin/plugin.py#L95-L131
|
243,452
|
rdo-management/python-rdomanager-oscplugin
|
rdomanager_oscplugin/plugin.py
|
ClientWrapper.management
|
def management(self):
"""Returns an management service client"""
endpoint = self._instance.get_endpoint_for_service_type(
"management",
region_name=self._instance._region_name,
)
token = self._instance.auth.get_token(self._instance.session)
self._management = tuskar_client.get_client(
2, os_auth_token=token, tuskar_url=endpoint)
return self._management
|
python
|
def management(self):
"""Returns an management service client"""
endpoint = self._instance.get_endpoint_for_service_type(
"management",
region_name=self._instance._region_name,
)
token = self._instance.auth.get_token(self._instance.session)
self._management = tuskar_client.get_client(
2, os_auth_token=token, tuskar_url=endpoint)
return self._management
|
[
"def",
"management",
"(",
"self",
")",
":",
"endpoint",
"=",
"self",
".",
"_instance",
".",
"get_endpoint_for_service_type",
"(",
"\"management\"",
",",
"region_name",
"=",
"self",
".",
"_instance",
".",
"_region_name",
",",
")",
"token",
"=",
"self",
".",
"_instance",
".",
"auth",
".",
"get_token",
"(",
"self",
".",
"_instance",
".",
"session",
")",
"self",
".",
"_management",
"=",
"tuskar_client",
".",
"get_client",
"(",
"2",
",",
"os_auth_token",
"=",
"token",
",",
"tuskar_url",
"=",
"endpoint",
")",
"return",
"self",
".",
"_management"
] |
Returns an management service client
|
[
"Returns",
"an",
"management",
"service",
"client"
] |
165a166fb2e5a2598380779b35812b8b8478c4fb
|
https://github.com/rdo-management/python-rdomanager-oscplugin/blob/165a166fb2e5a2598380779b35812b8b8478c4fb/rdomanager_oscplugin/plugin.py#L133-L146
|
243,453
|
ronaldguillen/wave
|
wave/utils/mediatypes.py
|
media_type_matches
|
def media_type_matches(lhs, rhs):
"""
Returns ``True`` if the media type in the first argument <= the
media type in the second argument. The media types are strings
as described by the HTTP spec.
Valid media type strings include:
'application/json; indent=4'
'application/json'
'text/*'
'*/*'
"""
lhs = _MediaType(lhs)
rhs = _MediaType(rhs)
return lhs.match(rhs)
|
python
|
def media_type_matches(lhs, rhs):
"""
Returns ``True`` if the media type in the first argument <= the
media type in the second argument. The media types are strings
as described by the HTTP spec.
Valid media type strings include:
'application/json; indent=4'
'application/json'
'text/*'
'*/*'
"""
lhs = _MediaType(lhs)
rhs = _MediaType(rhs)
return lhs.match(rhs)
|
[
"def",
"media_type_matches",
"(",
"lhs",
",",
"rhs",
")",
":",
"lhs",
"=",
"_MediaType",
"(",
"lhs",
")",
"rhs",
"=",
"_MediaType",
"(",
"rhs",
")",
"return",
"lhs",
".",
"match",
"(",
"rhs",
")"
] |
Returns ``True`` if the media type in the first argument <= the
media type in the second argument. The media types are strings
as described by the HTTP spec.
Valid media type strings include:
'application/json; indent=4'
'application/json'
'text/*'
'*/*'
|
[
"Returns",
"True",
"if",
"the",
"media",
"type",
"in",
"the",
"first",
"argument",
"<",
"=",
"the",
"media",
"type",
"in",
"the",
"second",
"argument",
".",
"The",
"media",
"types",
"are",
"strings",
"as",
"described",
"by",
"the",
"HTTP",
"spec",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/mediatypes.py#L14-L29
|
243,454
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
subclasses
|
def subclasses(cls, lst=None):
'''Recursively gather subclasses of cls.
'''
if lst is None:
lst = []
for sc in cls.__subclasses__():
if sc not in lst:
lst.append(sc)
subclasses(sc, lst=lst)
return lst
|
python
|
def subclasses(cls, lst=None):
'''Recursively gather subclasses of cls.
'''
if lst is None:
lst = []
for sc in cls.__subclasses__():
if sc not in lst:
lst.append(sc)
subclasses(sc, lst=lst)
return lst
|
[
"def",
"subclasses",
"(",
"cls",
",",
"lst",
"=",
"None",
")",
":",
"if",
"lst",
"is",
"None",
":",
"lst",
"=",
"[",
"]",
"for",
"sc",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"if",
"sc",
"not",
"in",
"lst",
":",
"lst",
".",
"append",
"(",
"sc",
")",
"subclasses",
"(",
"sc",
",",
"lst",
"=",
"lst",
")",
"return",
"lst"
] |
Recursively gather subclasses of cls.
|
[
"Recursively",
"gather",
"subclasses",
"of",
"cls",
"."
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L50-L59
|
243,455
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
nearest_base
|
def nearest_base(cls, bases):
'''Returns the closest ancestor to cls in bases.
'''
if cls in bases:
return cls
dists = {base: index(mro(cls), base) for base in bases}
dists2 = {dist: base for base, dist in dists.items() if dist is not None}
if not dists2:
return None
return dists2[min(dists2)]
|
python
|
def nearest_base(cls, bases):
'''Returns the closest ancestor to cls in bases.
'''
if cls in bases:
return cls
dists = {base: index(mro(cls), base) for base in bases}
dists2 = {dist: base for base, dist in dists.items() if dist is not None}
if not dists2:
return None
return dists2[min(dists2)]
|
[
"def",
"nearest_base",
"(",
"cls",
",",
"bases",
")",
":",
"if",
"cls",
"in",
"bases",
":",
"return",
"cls",
"dists",
"=",
"{",
"base",
":",
"index",
"(",
"mro",
"(",
"cls",
")",
",",
"base",
")",
"for",
"base",
"in",
"bases",
"}",
"dists2",
"=",
"{",
"dist",
":",
"base",
"for",
"base",
",",
"dist",
"in",
"dists",
".",
"items",
"(",
")",
"if",
"dist",
"is",
"not",
"None",
"}",
"if",
"not",
"dists2",
":",
"return",
"None",
"return",
"dists2",
"[",
"min",
"(",
"dists2",
")",
"]"
] |
Returns the closest ancestor to cls in bases.
|
[
"Returns",
"the",
"closest",
"ancestor",
"to",
"cls",
"in",
"bases",
"."
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L93-L103
|
243,456
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
get_typename
|
def get_typename(x):
'''Returns the name of the type of x, if x is an object. Otherwise, returns the name of x.
'''
if isinstance(x, type):
ret = x.__name__
else:
ret = x.__class__.__name__
return ret
|
python
|
def get_typename(x):
'''Returns the name of the type of x, if x is an object. Otherwise, returns the name of x.
'''
if isinstance(x, type):
ret = x.__name__
else:
ret = x.__class__.__name__
return ret
|
[
"def",
"get_typename",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"type",
")",
":",
"ret",
"=",
"x",
".",
"__name__",
"else",
":",
"ret",
"=",
"x",
".",
"__class__",
".",
"__name__",
"return",
"ret"
] |
Returns the name of the type of x, if x is an object. Otherwise, returns the name of x.
|
[
"Returns",
"the",
"name",
"of",
"the",
"type",
"of",
"x",
"if",
"x",
"is",
"an",
"object",
".",
"Otherwise",
"returns",
"the",
"name",
"of",
"x",
"."
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L105-L112
|
243,457
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
getfunc
|
def getfunc(obj, name=''):
'''Get the function corresponding to name from obj, not the method.'''
if name:
obj = getattr(obj, name)
return getattr(obj, '__func__', obj)
|
python
|
def getfunc(obj, name=''):
'''Get the function corresponding to name from obj, not the method.'''
if name:
obj = getattr(obj, name)
return getattr(obj, '__func__', obj)
|
[
"def",
"getfunc",
"(",
"obj",
",",
"name",
"=",
"''",
")",
":",
"if",
"name",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"name",
")",
"return",
"getattr",
"(",
"obj",
",",
"'__func__'",
",",
"obj",
")"
] |
Get the function corresponding to name from obj, not the method.
|
[
"Get",
"the",
"function",
"corresponding",
"to",
"name",
"from",
"obj",
"not",
"the",
"method",
"."
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L220-L224
|
243,458
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
get_mod
|
def get_mod(cls):
'''Returns the string identifying the module that cls is defined in.
'''
if isinstance(cls, (type, types.FunctionType)):
ret = cls.__module__
else:
ret = cls.__class__.__module__
return ret
|
python
|
def get_mod(cls):
'''Returns the string identifying the module that cls is defined in.
'''
if isinstance(cls, (type, types.FunctionType)):
ret = cls.__module__
else:
ret = cls.__class__.__module__
return ret
|
[
"def",
"get_mod",
"(",
"cls",
")",
":",
"if",
"isinstance",
"(",
"cls",
",",
"(",
"type",
",",
"types",
".",
"FunctionType",
")",
")",
":",
"ret",
"=",
"cls",
".",
"__module__",
"else",
":",
"ret",
"=",
"cls",
".",
"__class__",
".",
"__module__",
"return",
"ret"
] |
Returns the string identifying the module that cls is defined in.
|
[
"Returns",
"the",
"string",
"identifying",
"the",
"module",
"that",
"cls",
"is",
"defined",
"in",
"."
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L315-L323
|
243,459
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
this_module
|
def this_module(npop=1):
'''Returns the module object of the module this function is called from
'''
stack = inspect.stack()
st = stack[npop]
frame = st[0]
return inspect.getmodule(frame)
|
python
|
def this_module(npop=1):
'''Returns the module object of the module this function is called from
'''
stack = inspect.stack()
st = stack[npop]
frame = st[0]
return inspect.getmodule(frame)
|
[
"def",
"this_module",
"(",
"npop",
"=",
"1",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"st",
"=",
"stack",
"[",
"npop",
"]",
"frame",
"=",
"st",
"[",
"0",
"]",
"return",
"inspect",
".",
"getmodule",
"(",
"frame",
")"
] |
Returns the module object of the module this function is called from
|
[
"Returns",
"the",
"module",
"object",
"of",
"the",
"module",
"this",
"function",
"is",
"called",
"from"
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L333-L339
|
243,460
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
assert_equivalent
|
def assert_equivalent(o1, o2):
'''Asserts that o1 and o2 are distinct, yet equivalent objects
'''
if not (isinstance(o1, type) and isinstance(o2, type)):
assert o1 is not o2
assert o1 == o2
assert o2 == o1
|
python
|
def assert_equivalent(o1, o2):
'''Asserts that o1 and o2 are distinct, yet equivalent objects
'''
if not (isinstance(o1, type) and isinstance(o2, type)):
assert o1 is not o2
assert o1 == o2
assert o2 == o1
|
[
"def",
"assert_equivalent",
"(",
"o1",
",",
"o2",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"o1",
",",
"type",
")",
"and",
"isinstance",
"(",
"o2",
",",
"type",
")",
")",
":",
"assert",
"o1",
"is",
"not",
"o2",
"assert",
"o1",
"==",
"o2",
"assert",
"o2",
"==",
"o1"
] |
Asserts that o1 and o2 are distinct, yet equivalent objects
|
[
"Asserts",
"that",
"o1",
"and",
"o2",
"are",
"distinct",
"yet",
"equivalent",
"objects"
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L421-L427
|
243,461
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
assert_inequivalent
|
def assert_inequivalent(o1, o2):
'''Asserts that o1 and o2 are distinct and inequivalent objects
'''
if not (isinstance(o1, type) and isinstance(o2, type)):
assert o1 is not o2
assert not o1 == o2 and o1 != o2
assert not o2 == o1 and o2 != o1
|
python
|
def assert_inequivalent(o1, o2):
'''Asserts that o1 and o2 are distinct and inequivalent objects
'''
if not (isinstance(o1, type) and isinstance(o2, type)):
assert o1 is not o2
assert not o1 == o2 and o1 != o2
assert not o2 == o1 and o2 != o1
|
[
"def",
"assert_inequivalent",
"(",
"o1",
",",
"o2",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"o1",
",",
"type",
")",
"and",
"isinstance",
"(",
"o2",
",",
"type",
")",
")",
":",
"assert",
"o1",
"is",
"not",
"o2",
"assert",
"not",
"o1",
"==",
"o2",
"and",
"o1",
"!=",
"o2",
"assert",
"not",
"o2",
"==",
"o1",
"and",
"o2",
"!=",
"o1"
] |
Asserts that o1 and o2 are distinct and inequivalent objects
|
[
"Asserts",
"that",
"o1",
"and",
"o2",
"are",
"distinct",
"and",
"inequivalent",
"objects"
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L429-L435
|
243,462
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
assert_type_equivalent
|
def assert_type_equivalent(o1, o2):
'''Asserts that o1 and o2 are distinct, yet equivalent objects of the same type
'''
assert o1 == o2
assert o2 == o1
assert type(o1) is type(o2)
|
python
|
def assert_type_equivalent(o1, o2):
'''Asserts that o1 and o2 are distinct, yet equivalent objects of the same type
'''
assert o1 == o2
assert o2 == o1
assert type(o1) is type(o2)
|
[
"def",
"assert_type_equivalent",
"(",
"o1",
",",
"o2",
")",
":",
"assert",
"o1",
"==",
"o2",
"assert",
"o2",
"==",
"o1",
"assert",
"type",
"(",
"o1",
")",
"is",
"type",
"(",
"o2",
")"
] |
Asserts that o1 and o2 are distinct, yet equivalent objects of the same type
|
[
"Asserts",
"that",
"o1",
"and",
"o2",
"are",
"distinct",
"yet",
"equivalent",
"objects",
"of",
"the",
"same",
"type"
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L437-L442
|
243,463
|
mbodenhamer/syn
|
syn/base_utils/py.py
|
elog
|
def elog(exc, func, args=None, kwargs=None, str=str, pretty=True, name=''):
'''For logging exception-raising function invocations during randomized unit tests.
'''
from .str import safe_str
args = args if args else ()
kwargs = kwargs if kwargs else {}
name = '{}.{}'.format(get_mod(func), name) if name else full_funcname(func)
if pretty:
invocation = ', '.join([safe_str(arg) for arg in args])
if kwargs:
invocation += ', '
invocation += ', '.join(['{}={}'.format(key, safe_str(value))
for key, value in sorted(kwargs.items())])
else:
invocation = 'args={}, kwargs={}'.format(safe_str(args), safe_str(kwargs))
msg = '***{}***: "{}" --- {}({})'.format(get_typename(exc),
message(exc),
name,
invocation)
elogger.error(msg)
|
python
|
def elog(exc, func, args=None, kwargs=None, str=str, pretty=True, name=''):
'''For logging exception-raising function invocations during randomized unit tests.
'''
from .str import safe_str
args = args if args else ()
kwargs = kwargs if kwargs else {}
name = '{}.{}'.format(get_mod(func), name) if name else full_funcname(func)
if pretty:
invocation = ', '.join([safe_str(arg) for arg in args])
if kwargs:
invocation += ', '
invocation += ', '.join(['{}={}'.format(key, safe_str(value))
for key, value in sorted(kwargs.items())])
else:
invocation = 'args={}, kwargs={}'.format(safe_str(args), safe_str(kwargs))
msg = '***{}***: "{}" --- {}({})'.format(get_typename(exc),
message(exc),
name,
invocation)
elogger.error(msg)
|
[
"def",
"elog",
"(",
"exc",
",",
"func",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"str",
"=",
"str",
",",
"pretty",
"=",
"True",
",",
"name",
"=",
"''",
")",
":",
"from",
".",
"str",
"import",
"safe_str",
"args",
"=",
"args",
"if",
"args",
"else",
"(",
")",
"kwargs",
"=",
"kwargs",
"if",
"kwargs",
"else",
"{",
"}",
"name",
"=",
"'{}.{}'",
".",
"format",
"(",
"get_mod",
"(",
"func",
")",
",",
"name",
")",
"if",
"name",
"else",
"full_funcname",
"(",
"func",
")",
"if",
"pretty",
":",
"invocation",
"=",
"', '",
".",
"join",
"(",
"[",
"safe_str",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
")",
"if",
"kwargs",
":",
"invocation",
"+=",
"', '",
"invocation",
"+=",
"', '",
".",
"join",
"(",
"[",
"'{}={}'",
".",
"format",
"(",
"key",
",",
"safe_str",
"(",
"value",
")",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
"]",
")",
"else",
":",
"invocation",
"=",
"'args={}, kwargs={}'",
".",
"format",
"(",
"safe_str",
"(",
"args",
")",
",",
"safe_str",
"(",
"kwargs",
")",
")",
"msg",
"=",
"'***{}***: \"{}\" --- {}({})'",
".",
"format",
"(",
"get_typename",
"(",
"exc",
")",
",",
"message",
"(",
"exc",
")",
",",
"name",
",",
"invocation",
")",
"elogger",
".",
"error",
"(",
"msg",
")"
] |
For logging exception-raising function invocations during randomized unit tests.
|
[
"For",
"logging",
"exception",
"-",
"raising",
"function",
"invocations",
"during",
"randomized",
"unit",
"tests",
"."
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L468-L490
|
243,464
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/message.py
|
Message.get_body
|
def get_body(self):
"""Get the body of the email message"""
if self.is_multipart():
# get the plain text version only
text_parts = [part
for part in typed_subpart_iterator(self,
'text',
'plain')]
body = []
for part in text_parts:
charset = get_charset(part, get_charset(self))
body.append(unicode(part.get_payload(decode=True),
charset,
"replace"))
return u"\n".join(body).strip()
else: # if it is not multipart, the payload will be a string
# representing the message body
body = unicode(self.get_payload(decode=True),
get_charset(self),
"replace")
return body.strip()
|
python
|
def get_body(self):
"""Get the body of the email message"""
if self.is_multipart():
# get the plain text version only
text_parts = [part
for part in typed_subpart_iterator(self,
'text',
'plain')]
body = []
for part in text_parts:
charset = get_charset(part, get_charset(self))
body.append(unicode(part.get_payload(decode=True),
charset,
"replace"))
return u"\n".join(body).strip()
else: # if it is not multipart, the payload will be a string
# representing the message body
body = unicode(self.get_payload(decode=True),
get_charset(self),
"replace")
return body.strip()
|
[
"def",
"get_body",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_multipart",
"(",
")",
":",
"# get the plain text version only",
"text_parts",
"=",
"[",
"part",
"for",
"part",
"in",
"typed_subpart_iterator",
"(",
"self",
",",
"'text'",
",",
"'plain'",
")",
"]",
"body",
"=",
"[",
"]",
"for",
"part",
"in",
"text_parts",
":",
"charset",
"=",
"get_charset",
"(",
"part",
",",
"get_charset",
"(",
"self",
")",
")",
"body",
".",
"append",
"(",
"unicode",
"(",
"part",
".",
"get_payload",
"(",
"decode",
"=",
"True",
")",
",",
"charset",
",",
"\"replace\"",
")",
")",
"return",
"u\"\\n\"",
".",
"join",
"(",
"body",
")",
".",
"strip",
"(",
")",
"else",
":",
"# if it is not multipart, the payload will be a string",
"# representing the message body",
"body",
"=",
"unicode",
"(",
"self",
".",
"get_payload",
"(",
"decode",
"=",
"True",
")",
",",
"get_charset",
"(",
"self",
")",
",",
"\"replace\"",
")",
"return",
"body",
".",
"strip",
"(",
")"
] |
Get the body of the email message
|
[
"Get",
"the",
"body",
"of",
"the",
"email",
"message"
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/message.py#L56-L79
|
243,465
|
Akhail/Tebless
|
tebless/widgets/window.py
|
Window.listen
|
def listen(self):
"""Blocking call on widgets.
"""
while self._listen:
key = u''
key = self.term.inkey(timeout=0.2)
try:
if key.code == KEY_ENTER:
self.on_enter(key=key)
elif key.code in (KEY_DOWN, KEY_UP):
self.on_key_arrow(key=key)
elif key.code == KEY_ESCAPE or key == chr(3):
self.on_exit(key=key)
elif key != '':
self.on_key(key=key)
except KeyboardInterrupt:
self.on_exit(key=key)
|
python
|
def listen(self):
"""Blocking call on widgets.
"""
while self._listen:
key = u''
key = self.term.inkey(timeout=0.2)
try:
if key.code == KEY_ENTER:
self.on_enter(key=key)
elif key.code in (KEY_DOWN, KEY_UP):
self.on_key_arrow(key=key)
elif key.code == KEY_ESCAPE or key == chr(3):
self.on_exit(key=key)
elif key != '':
self.on_key(key=key)
except KeyboardInterrupt:
self.on_exit(key=key)
|
[
"def",
"listen",
"(",
"self",
")",
":",
"while",
"self",
".",
"_listen",
":",
"key",
"=",
"u''",
"key",
"=",
"self",
".",
"term",
".",
"inkey",
"(",
"timeout",
"=",
"0.2",
")",
"try",
":",
"if",
"key",
".",
"code",
"==",
"KEY_ENTER",
":",
"self",
".",
"on_enter",
"(",
"key",
"=",
"key",
")",
"elif",
"key",
".",
"code",
"in",
"(",
"KEY_DOWN",
",",
"KEY_UP",
")",
":",
"self",
".",
"on_key_arrow",
"(",
"key",
"=",
"key",
")",
"elif",
"key",
".",
"code",
"==",
"KEY_ESCAPE",
"or",
"key",
"==",
"chr",
"(",
"3",
")",
":",
"self",
".",
"on_exit",
"(",
"key",
"=",
"key",
")",
"elif",
"key",
"!=",
"''",
":",
"self",
".",
"on_key",
"(",
"key",
"=",
"key",
")",
"except",
"KeyboardInterrupt",
":",
"self",
".",
"on_exit",
"(",
"key",
"=",
"key",
")"
] |
Blocking call on widgets.
|
[
"Blocking",
"call",
"on",
"widgets",
"."
] |
369ff76f06e7a0b6d04fabc287fa6c4095e158d4
|
https://github.com/Akhail/Tebless/blob/369ff76f06e7a0b6d04fabc287fa6c4095e158d4/tebless/widgets/window.py#L81-L98
|
243,466
|
Akhail/Tebless
|
tebless/widgets/window.py
|
Window.add
|
def add(self, widget, *args, **kwargs):
"""Insert new element.
Usage:
window.add(widget, **{
'prop1': val,
'prop2': val2
})
"""
ins_widget = widget(*args, **kwargs)
self.__iadd__(ins_widget)
return ins_widget
|
python
|
def add(self, widget, *args, **kwargs):
"""Insert new element.
Usage:
window.add(widget, **{
'prop1': val,
'prop2': val2
})
"""
ins_widget = widget(*args, **kwargs)
self.__iadd__(ins_widget)
return ins_widget
|
[
"def",
"add",
"(",
"self",
",",
"widget",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ins_widget",
"=",
"widget",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"__iadd__",
"(",
"ins_widget",
")",
"return",
"ins_widget"
] |
Insert new element.
Usage:
window.add(widget, **{
'prop1': val,
'prop2': val2
})
|
[
"Insert",
"new",
"element",
"."
] |
369ff76f06e7a0b6d04fabc287fa6c4095e158d4
|
https://github.com/Akhail/Tebless/blob/369ff76f06e7a0b6d04fabc287fa6c4095e158d4/tebless/widgets/window.py#L100-L112
|
243,467
|
emory-libraries/eulcommon
|
eulcommon/searchutil/__init__.py
|
search_terms
|
def search_terms(q):
'''Takes a search string and parses it into a list of keywords and
phrases.'''
tokens = parse_search_terms(q)
# iterate through all the tokens and make a list of token values
# (which are the actual words and phrases)
values = []
for t in tokens:
# word/phrase
if t[0] is None:
values.append(t[1])
# incomplete field
elif t[1] is None:
values.append('%s:' % t[0])
# anything else must be a field, value pair
# - if value includes whitespace, wrap in quotes
elif re.search('\s', t[1]):
values.append('%s:"%s"' % t)
# otherwise, leave unquoted
else:
values.append('%s:%s' % t)
return values
|
python
|
def search_terms(q):
'''Takes a search string and parses it into a list of keywords and
phrases.'''
tokens = parse_search_terms(q)
# iterate through all the tokens and make a list of token values
# (which are the actual words and phrases)
values = []
for t in tokens:
# word/phrase
if t[0] is None:
values.append(t[1])
# incomplete field
elif t[1] is None:
values.append('%s:' % t[0])
# anything else must be a field, value pair
# - if value includes whitespace, wrap in quotes
elif re.search('\s', t[1]):
values.append('%s:"%s"' % t)
# otherwise, leave unquoted
else:
values.append('%s:%s' % t)
return values
|
[
"def",
"search_terms",
"(",
"q",
")",
":",
"tokens",
"=",
"parse_search_terms",
"(",
"q",
")",
"# iterate through all the tokens and make a list of token values",
"# (which are the actual words and phrases)",
"values",
"=",
"[",
"]",
"for",
"t",
"in",
"tokens",
":",
"# word/phrase",
"if",
"t",
"[",
"0",
"]",
"is",
"None",
":",
"values",
".",
"append",
"(",
"t",
"[",
"1",
"]",
")",
"# incomplete field",
"elif",
"t",
"[",
"1",
"]",
"is",
"None",
":",
"values",
".",
"append",
"(",
"'%s:'",
"%",
"t",
"[",
"0",
"]",
")",
"# anything else must be a field, value pair",
"# - if value includes whitespace, wrap in quotes",
"elif",
"re",
".",
"search",
"(",
"'\\s'",
",",
"t",
"[",
"1",
"]",
")",
":",
"values",
".",
"append",
"(",
"'%s:\"%s\"'",
"%",
"t",
")",
"# otherwise, leave unquoted",
"else",
":",
"values",
".",
"append",
"(",
"'%s:%s'",
"%",
"t",
")",
"return",
"values"
] |
Takes a search string and parses it into a list of keywords and
phrases.
|
[
"Takes",
"a",
"search",
"string",
"and",
"parses",
"it",
"into",
"a",
"list",
"of",
"keywords",
"and",
"phrases",
"."
] |
dc63a9b3b5e38205178235e0d716d1b28158d3a9
|
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/searchutil/__init__.py#L129-L150
|
243,468
|
emory-libraries/eulcommon
|
eulcommon/searchutil/__init__.py
|
pages_to_show
|
def pages_to_show(paginator, page, page_labels=None):
"""Generate a dictionary of pages to show around the current page. Show
3 numbers on either side of the specified page, or more if close to end or
beginning of available pages.
:param paginator: django :class:`~django.core.paginator.Paginator`,
populated with objects
:param page: number of the current page
:param page_labels: optional dictionary of page labels, keyed on page number
:rtype: dictionary; keys are page numbers, values are page labels
"""
show_pages = {} # FIXME; do we need OrderedDict here ?
if page_labels is None:
page_labels = {}
def get_page_label(index):
if index in page_labels:
return page_labels[index]
else:
return unicode(index)
if page != 1:
before = 3 # default number of pages to show before the current page
if page >= (paginator.num_pages - 3): # current page is within 3 of end
# increase number to show before current page based on distance to end
before += (3 - (paginator.num_pages - page))
for i in range(before, 0, -1): # add pages from before away up to current page
if (page - i) >= 1:
# if there is a page label available, use that as dictionary value
show_pages[page - i] = get_page_label(page - i)
# show up to 3 to 7 numbers after the current number, depending on
# how many we already have
for i in range(7 - len(show_pages)):
if (page + i) <= paginator.num_pages:
# if there is a page label available, use that as dictionary value
show_pages[page + i] = get_page_label(page + i)
return show_pages
|
python
|
def pages_to_show(paginator, page, page_labels=None):
"""Generate a dictionary of pages to show around the current page. Show
3 numbers on either side of the specified page, or more if close to end or
beginning of available pages.
:param paginator: django :class:`~django.core.paginator.Paginator`,
populated with objects
:param page: number of the current page
:param page_labels: optional dictionary of page labels, keyed on page number
:rtype: dictionary; keys are page numbers, values are page labels
"""
show_pages = {} # FIXME; do we need OrderedDict here ?
if page_labels is None:
page_labels = {}
def get_page_label(index):
if index in page_labels:
return page_labels[index]
else:
return unicode(index)
if page != 1:
before = 3 # default number of pages to show before the current page
if page >= (paginator.num_pages - 3): # current page is within 3 of end
# increase number to show before current page based on distance to end
before += (3 - (paginator.num_pages - page))
for i in range(before, 0, -1): # add pages from before away up to current page
if (page - i) >= 1:
# if there is a page label available, use that as dictionary value
show_pages[page - i] = get_page_label(page - i)
# show up to 3 to 7 numbers after the current number, depending on
# how many we already have
for i in range(7 - len(show_pages)):
if (page + i) <= paginator.num_pages:
# if there is a page label available, use that as dictionary value
show_pages[page + i] = get_page_label(page + i)
return show_pages
|
[
"def",
"pages_to_show",
"(",
"paginator",
",",
"page",
",",
"page_labels",
"=",
"None",
")",
":",
"show_pages",
"=",
"{",
"}",
"# FIXME; do we need OrderedDict here ?",
"if",
"page_labels",
"is",
"None",
":",
"page_labels",
"=",
"{",
"}",
"def",
"get_page_label",
"(",
"index",
")",
":",
"if",
"index",
"in",
"page_labels",
":",
"return",
"page_labels",
"[",
"index",
"]",
"else",
":",
"return",
"unicode",
"(",
"index",
")",
"if",
"page",
"!=",
"1",
":",
"before",
"=",
"3",
"# default number of pages to show before the current page",
"if",
"page",
">=",
"(",
"paginator",
".",
"num_pages",
"-",
"3",
")",
":",
"# current page is within 3 of end",
"# increase number to show before current page based on distance to end",
"before",
"+=",
"(",
"3",
"-",
"(",
"paginator",
".",
"num_pages",
"-",
"page",
")",
")",
"for",
"i",
"in",
"range",
"(",
"before",
",",
"0",
",",
"-",
"1",
")",
":",
"# add pages from before away up to current page",
"if",
"(",
"page",
"-",
"i",
")",
">=",
"1",
":",
"# if there is a page label available, use that as dictionary value",
"show_pages",
"[",
"page",
"-",
"i",
"]",
"=",
"get_page_label",
"(",
"page",
"-",
"i",
")",
"# show up to 3 to 7 numbers after the current number, depending on",
"# how many we already have",
"for",
"i",
"in",
"range",
"(",
"7",
"-",
"len",
"(",
"show_pages",
")",
")",
":",
"if",
"(",
"page",
"+",
"i",
")",
"<=",
"paginator",
".",
"num_pages",
":",
"# if there is a page label available, use that as dictionary value",
"show_pages",
"[",
"page",
"+",
"i",
"]",
"=",
"get_page_label",
"(",
"page",
"+",
"i",
")",
"return",
"show_pages"
] |
Generate a dictionary of pages to show around the current page. Show
3 numbers on either side of the specified page, or more if close to end or
beginning of available pages.
:param paginator: django :class:`~django.core.paginator.Paginator`,
populated with objects
:param page: number of the current page
:param page_labels: optional dictionary of page labels, keyed on page number
:rtype: dictionary; keys are page numbers, values are page labels
|
[
"Generate",
"a",
"dictionary",
"of",
"pages",
"to",
"show",
"around",
"the",
"current",
"page",
".",
"Show",
"3",
"numbers",
"on",
"either",
"side",
"of",
"the",
"specified",
"page",
"or",
"more",
"if",
"close",
"to",
"end",
"or",
"beginning",
"of",
"available",
"pages",
"."
] |
dc63a9b3b5e38205178235e0d716d1b28158d3a9
|
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/searchutil/__init__.py#L153-L191
|
243,469
|
micbou/flake8-ycm
|
flake8_ycm.py
|
Indentation
|
def Indentation( logical_line,
previous_logical,
indent_level,
previous_indent_level ):
"""Use two spaces per indentation level."""
comment = '' if logical_line else ' (comment)'
if indent_level % 2:
code = 'YCM111' if logical_line else 'YCM114'
message = ' indentation is not a multiple of two spaces' + comment
yield 0, code + message
if ( previous_logical.endswith( ':' ) and
( indent_level - previous_indent_level != 2 ) ):
code = 'YCM112' if logical_line else 'YCM115'
message = ' expected an indented block of {} spaces{}'.format(
previous_indent_level + 2, comment )
yield 0, code + message
|
python
|
def Indentation( logical_line,
previous_logical,
indent_level,
previous_indent_level ):
"""Use two spaces per indentation level."""
comment = '' if logical_line else ' (comment)'
if indent_level % 2:
code = 'YCM111' if logical_line else 'YCM114'
message = ' indentation is not a multiple of two spaces' + comment
yield 0, code + message
if ( previous_logical.endswith( ':' ) and
( indent_level - previous_indent_level != 2 ) ):
code = 'YCM112' if logical_line else 'YCM115'
message = ' expected an indented block of {} spaces{}'.format(
previous_indent_level + 2, comment )
yield 0, code + message
|
[
"def",
"Indentation",
"(",
"logical_line",
",",
"previous_logical",
",",
"indent_level",
",",
"previous_indent_level",
")",
":",
"comment",
"=",
"''",
"if",
"logical_line",
"else",
"' (comment)'",
"if",
"indent_level",
"%",
"2",
":",
"code",
"=",
"'YCM111'",
"if",
"logical_line",
"else",
"'YCM114'",
"message",
"=",
"' indentation is not a multiple of two spaces'",
"+",
"comment",
"yield",
"0",
",",
"code",
"+",
"message",
"if",
"(",
"previous_logical",
".",
"endswith",
"(",
"':'",
")",
"and",
"(",
"indent_level",
"-",
"previous_indent_level",
"!=",
"2",
")",
")",
":",
"code",
"=",
"'YCM112'",
"if",
"logical_line",
"else",
"'YCM115'",
"message",
"=",
"' expected an indented block of {} spaces{}'",
".",
"format",
"(",
"previous_indent_level",
"+",
"2",
",",
"comment",
")",
"yield",
"0",
",",
"code",
"+",
"message"
] |
Use two spaces per indentation level.
|
[
"Use",
"two",
"spaces",
"per",
"indentation",
"level",
"."
] |
60eb837751260f28db44b51a1641ea8743c1c497
|
https://github.com/micbou/flake8-ycm/blob/60eb837751260f28db44b51a1641ea8743c1c497/flake8_ycm.py#L35-L50
|
243,470
|
micbou/flake8-ycm
|
flake8_ycm.py
|
SpacesInsideBrackets
|
def SpacesInsideBrackets( logical_line, tokens ):
"""Require spaces inside parentheses, square brackets, and braces for
non-empty content."""
for index in range( len( tokens ) ):
_, prev_text, _, prev_end, _ = ( tokens[ index - 1 ] if index - 1 >= 0 else
( None, None, None, None, None ) )
token_type, text, start, end, _ = tokens[ index ]
next_token_type, next_text, next_start, _, _ = (
tokens[ index + 1 ] if index + 1 < len( tokens ) else
( None, None, None, None, None ) )
if text in LEFT_BRACKETS:
if ( next_text == CORRESPONDING_BRACKET[ text ] and
next_start != end ):
code = 'YCM204'
message = ( ' no spaces between {} and {}'
' for empty content'.format( text, next_text ) )
yield end, code + message
if ( next_token_type not in [ tokenize.NL, tokenize.NEWLINE ] and
next_text != CORRESPONDING_BRACKET[ text ] and
next_start and
next_start[ 0 ] == start[ 0 ] and
next_start[ 1 ] - start[ 1 ] != 2 ):
code = 'YCM201'
message = ' exactly one space required after {}'.format( text )
yield end, code + message
if text in RIGHT_BRACKETS:
if ( prev_text != CORRESPONDING_BRACKET[ text ] and
prev_end and
prev_end[ 0 ] == end[ 0 ] and
end[ 1 ] - prev_end[ 1 ] != 2 ):
code = 'YCM202'
message = ' exactly one space required before {}'.format( text )
yield start, code + message
|
python
|
def SpacesInsideBrackets( logical_line, tokens ):
"""Require spaces inside parentheses, square brackets, and braces for
non-empty content."""
for index in range( len( tokens ) ):
_, prev_text, _, prev_end, _ = ( tokens[ index - 1 ] if index - 1 >= 0 else
( None, None, None, None, None ) )
token_type, text, start, end, _ = tokens[ index ]
next_token_type, next_text, next_start, _, _ = (
tokens[ index + 1 ] if index + 1 < len( tokens ) else
( None, None, None, None, None ) )
if text in LEFT_BRACKETS:
if ( next_text == CORRESPONDING_BRACKET[ text ] and
next_start != end ):
code = 'YCM204'
message = ( ' no spaces between {} and {}'
' for empty content'.format( text, next_text ) )
yield end, code + message
if ( next_token_type not in [ tokenize.NL, tokenize.NEWLINE ] and
next_text != CORRESPONDING_BRACKET[ text ] and
next_start and
next_start[ 0 ] == start[ 0 ] and
next_start[ 1 ] - start[ 1 ] != 2 ):
code = 'YCM201'
message = ' exactly one space required after {}'.format( text )
yield end, code + message
if text in RIGHT_BRACKETS:
if ( prev_text != CORRESPONDING_BRACKET[ text ] and
prev_end and
prev_end[ 0 ] == end[ 0 ] and
end[ 1 ] - prev_end[ 1 ] != 2 ):
code = 'YCM202'
message = ' exactly one space required before {}'.format( text )
yield start, code + message
|
[
"def",
"SpacesInsideBrackets",
"(",
"logical_line",
",",
"tokens",
")",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"tokens",
")",
")",
":",
"_",
",",
"prev_text",
",",
"_",
",",
"prev_end",
",",
"_",
"=",
"(",
"tokens",
"[",
"index",
"-",
"1",
"]",
"if",
"index",
"-",
"1",
">=",
"0",
"else",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
")",
")",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"_",
"=",
"tokens",
"[",
"index",
"]",
"next_token_type",
",",
"next_text",
",",
"next_start",
",",
"_",
",",
"_",
"=",
"(",
"tokens",
"[",
"index",
"+",
"1",
"]",
"if",
"index",
"+",
"1",
"<",
"len",
"(",
"tokens",
")",
"else",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
")",
")",
"if",
"text",
"in",
"LEFT_BRACKETS",
":",
"if",
"(",
"next_text",
"==",
"CORRESPONDING_BRACKET",
"[",
"text",
"]",
"and",
"next_start",
"!=",
"end",
")",
":",
"code",
"=",
"'YCM204'",
"message",
"=",
"(",
"' no spaces between {} and {}'",
"' for empty content'",
".",
"format",
"(",
"text",
",",
"next_text",
")",
")",
"yield",
"end",
",",
"code",
"+",
"message",
"if",
"(",
"next_token_type",
"not",
"in",
"[",
"tokenize",
".",
"NL",
",",
"tokenize",
".",
"NEWLINE",
"]",
"and",
"next_text",
"!=",
"CORRESPONDING_BRACKET",
"[",
"text",
"]",
"and",
"next_start",
"and",
"next_start",
"[",
"0",
"]",
"==",
"start",
"[",
"0",
"]",
"and",
"next_start",
"[",
"1",
"]",
"-",
"start",
"[",
"1",
"]",
"!=",
"2",
")",
":",
"code",
"=",
"'YCM201'",
"message",
"=",
"' exactly one space required after {}'",
".",
"format",
"(",
"text",
")",
"yield",
"end",
",",
"code",
"+",
"message",
"if",
"text",
"in",
"RIGHT_BRACKETS",
":",
"if",
"(",
"prev_text",
"!=",
"CORRESPONDING_BRACKET",
"[",
"text",
"]",
"and",
"prev_end",
"and",
"prev_end",
"[",
"0",
"]",
"==",
"end",
"[",
"0",
"]",
"and",
"end",
"[",
"1",
"]",
"-",
"prev_end",
"[",
"1",
"]",
"!=",
"2",
")",
":",
"code",
"=",
"'YCM202'",
"message",
"=",
"' exactly one space required before {}'",
".",
"format",
"(",
"text",
")",
"yield",
"start",
",",
"code",
"+",
"message"
] |
Require spaces inside parentheses, square brackets, and braces for
non-empty content.
|
[
"Require",
"spaces",
"inside",
"parentheses",
"square",
"brackets",
"and",
"braces",
"for",
"non",
"-",
"empty",
"content",
"."
] |
60eb837751260f28db44b51a1641ea8743c1c497
|
https://github.com/micbou/flake8-ycm/blob/60eb837751260f28db44b51a1641ea8743c1c497/flake8_ycm.py#L57-L89
|
243,471
|
chairbender/fantasy-football-auction
|
fantasy_football_auction/owner.py
|
Owner.buy
|
def buy(self, player, cost):
"""
indicate that the player was bought at the specified cost
:param Player player: player to buy
:param int cost: cost to pay
:raises InsufficientFundsError: if owner doesn't have the money
:raises NoValidRosterSlotError: if owner doesn't have a slot this player could fill
:raises AlreadyPurchasedError: if owner already bought this player
"""
if cost > self.max_bid():
raise InsufficientFundsError()
elif not any(roster_slot.accepts(player) and roster_slot.occupant is None for roster_slot in self.roster):
raise NoValidRosterSlotError()
elif self.owns(player):
raise AlreadyPurchasedError()
self.money -= cost
self._remaining_picks -= 1
self._owned_player_ids.add(player.player_id)
self._slot_in(player, cost)
|
python
|
def buy(self, player, cost):
"""
indicate that the player was bought at the specified cost
:param Player player: player to buy
:param int cost: cost to pay
:raises InsufficientFundsError: if owner doesn't have the money
:raises NoValidRosterSlotError: if owner doesn't have a slot this player could fill
:raises AlreadyPurchasedError: if owner already bought this player
"""
if cost > self.max_bid():
raise InsufficientFundsError()
elif not any(roster_slot.accepts(player) and roster_slot.occupant is None for roster_slot in self.roster):
raise NoValidRosterSlotError()
elif self.owns(player):
raise AlreadyPurchasedError()
self.money -= cost
self._remaining_picks -= 1
self._owned_player_ids.add(player.player_id)
self._slot_in(player, cost)
|
[
"def",
"buy",
"(",
"self",
",",
"player",
",",
"cost",
")",
":",
"if",
"cost",
">",
"self",
".",
"max_bid",
"(",
")",
":",
"raise",
"InsufficientFundsError",
"(",
")",
"elif",
"not",
"any",
"(",
"roster_slot",
".",
"accepts",
"(",
"player",
")",
"and",
"roster_slot",
".",
"occupant",
"is",
"None",
"for",
"roster_slot",
"in",
"self",
".",
"roster",
")",
":",
"raise",
"NoValidRosterSlotError",
"(",
")",
"elif",
"self",
".",
"owns",
"(",
"player",
")",
":",
"raise",
"AlreadyPurchasedError",
"(",
")",
"self",
".",
"money",
"-=",
"cost",
"self",
".",
"_remaining_picks",
"-=",
"1",
"self",
".",
"_owned_player_ids",
".",
"add",
"(",
"player",
".",
"player_id",
")",
"self",
".",
"_slot_in",
"(",
"player",
",",
"cost",
")"
] |
indicate that the player was bought at the specified cost
:param Player player: player to buy
:param int cost: cost to pay
:raises InsufficientFundsError: if owner doesn't have the money
:raises NoValidRosterSlotError: if owner doesn't have a slot this player could fill
:raises AlreadyPurchasedError: if owner already bought this player
|
[
"indicate",
"that",
"the",
"player",
"was",
"bought",
"at",
"the",
"specified",
"cost"
] |
f54868691ea37691c378b0a05b6b3280c2cbba11
|
https://github.com/chairbender/fantasy-football-auction/blob/f54868691ea37691c378b0a05b6b3280c2cbba11/fantasy_football_auction/owner.py#L132-L153
|
243,472
|
sarenji/pyrc
|
pyrc/threads.py
|
JobThread.run
|
def run(self):
"""Keep running this thread until it's stopped"""
while not self._finished.isSet():
self._func(self._reference)
self._finished.wait(self._func._interval / 1000.0)
|
python
|
def run(self):
"""Keep running this thread until it's stopped"""
while not self._finished.isSet():
self._func(self._reference)
self._finished.wait(self._func._interval / 1000.0)
|
[
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_finished",
".",
"isSet",
"(",
")",
":",
"self",
".",
"_func",
"(",
"self",
".",
"_reference",
")",
"self",
".",
"_finished",
".",
"wait",
"(",
"self",
".",
"_func",
".",
"_interval",
"/",
"1000.0",
")"
] |
Keep running this thread until it's stopped
|
[
"Keep",
"running",
"this",
"thread",
"until",
"it",
"s",
"stopped"
] |
5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68
|
https://github.com/sarenji/pyrc/blob/5e8377ddcda6e0ef4ba7d66cf400e243b1fb8f68/pyrc/threads.py#L16-L20
|
243,473
|
kankiri/pabiana
|
pabiana/zmqs/area.py
|
Area.subscribe
|
def subscribe(self, clock_name: str=None, clock_slots: Iterable[str]=None, subscriptions: Dict[str, Any]={}):
"""Subscribes this Area to the given Areas and optionally given Slots. Must be called before the Area is run.
Args:
clock_name: The name of the Area that is used as synchronizing Clock.
clock_slots: The slots of the Clock relevant to this Area.
subscriptions: A dictionary containing the relevant Areas names as keys and optionally the Slots as values.
"""
for area in subscriptions: # type: str
init_full(self, area, subscriptions[area])
subscriptions[area] = {'slots': subscriptions[area]}
if clock_name is not None:
self.clock_name = clock_name
self.clock_slots = clock_slots
subscriptions[clock_name] = {'slots': clock_slots, 'buffer-length': 1}
self.setup(puller=True, subscriptions=subscriptions)
|
python
|
def subscribe(self, clock_name: str=None, clock_slots: Iterable[str]=None, subscriptions: Dict[str, Any]={}):
"""Subscribes this Area to the given Areas and optionally given Slots. Must be called before the Area is run.
Args:
clock_name: The name of the Area that is used as synchronizing Clock.
clock_slots: The slots of the Clock relevant to this Area.
subscriptions: A dictionary containing the relevant Areas names as keys and optionally the Slots as values.
"""
for area in subscriptions: # type: str
init_full(self, area, subscriptions[area])
subscriptions[area] = {'slots': subscriptions[area]}
if clock_name is not None:
self.clock_name = clock_name
self.clock_slots = clock_slots
subscriptions[clock_name] = {'slots': clock_slots, 'buffer-length': 1}
self.setup(puller=True, subscriptions=subscriptions)
|
[
"def",
"subscribe",
"(",
"self",
",",
"clock_name",
":",
"str",
"=",
"None",
",",
"clock_slots",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"subscriptions",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
")",
":",
"for",
"area",
"in",
"subscriptions",
":",
"# type: str",
"init_full",
"(",
"self",
",",
"area",
",",
"subscriptions",
"[",
"area",
"]",
")",
"subscriptions",
"[",
"area",
"]",
"=",
"{",
"'slots'",
":",
"subscriptions",
"[",
"area",
"]",
"}",
"if",
"clock_name",
"is",
"not",
"None",
":",
"self",
".",
"clock_name",
"=",
"clock_name",
"self",
".",
"clock_slots",
"=",
"clock_slots",
"subscriptions",
"[",
"clock_name",
"]",
"=",
"{",
"'slots'",
":",
"clock_slots",
",",
"'buffer-length'",
":",
"1",
"}",
"self",
".",
"setup",
"(",
"puller",
"=",
"True",
",",
"subscriptions",
"=",
"subscriptions",
")"
] |
Subscribes this Area to the given Areas and optionally given Slots. Must be called before the Area is run.
Args:
clock_name: The name of the Area that is used as synchronizing Clock.
clock_slots: The slots of the Clock relevant to this Area.
subscriptions: A dictionary containing the relevant Areas names as keys and optionally the Slots as values.
|
[
"Subscribes",
"this",
"Area",
"to",
"the",
"given",
"Areas",
"and",
"optionally",
"given",
"Slots",
".",
"Must",
"be",
"called",
"before",
"the",
"Area",
"is",
"run",
"."
] |
74acfdd81e2a1cc411c37b9ee3d6905ce4b1a39b
|
https://github.com/kankiri/pabiana/blob/74acfdd81e2a1cc411c37b9ee3d6905ce4b1a39b/pabiana/zmqs/area.py#L52-L68
|
243,474
|
drcloud/magiclog
|
magiclog.py
|
logger
|
def logger(ref=0):
"""Finds a module logger.
If the argument passed is a module, find the logger for that module using
the modules' name; if it's a string, finds a logger of that name; if an
integer, walks the stack to the module at that height.
The logger is always extended with a ``.configure()`` method allowing
its log levels for syslog and stderr to be adjusted or automatically
initialized as per the documentation for `configure()` below.
"""
if inspect.ismodule(ref):
return extend(logging.getLogger(ref.__name__))
if isinstance(ref, basestring):
return extend(logging.getLogger(ref))
return extend(logging.getLogger(stackclimber(ref+1)))
|
python
|
def logger(ref=0):
"""Finds a module logger.
If the argument passed is a module, find the logger for that module using
the modules' name; if it's a string, finds a logger of that name; if an
integer, walks the stack to the module at that height.
The logger is always extended with a ``.configure()`` method allowing
its log levels for syslog and stderr to be adjusted or automatically
initialized as per the documentation for `configure()` below.
"""
if inspect.ismodule(ref):
return extend(logging.getLogger(ref.__name__))
if isinstance(ref, basestring):
return extend(logging.getLogger(ref))
return extend(logging.getLogger(stackclimber(ref+1)))
|
[
"def",
"logger",
"(",
"ref",
"=",
"0",
")",
":",
"if",
"inspect",
".",
"ismodule",
"(",
"ref",
")",
":",
"return",
"extend",
"(",
"logging",
".",
"getLogger",
"(",
"ref",
".",
"__name__",
")",
")",
"if",
"isinstance",
"(",
"ref",
",",
"basestring",
")",
":",
"return",
"extend",
"(",
"logging",
".",
"getLogger",
"(",
"ref",
")",
")",
"return",
"extend",
"(",
"logging",
".",
"getLogger",
"(",
"stackclimber",
"(",
"ref",
"+",
"1",
")",
")",
")"
] |
Finds a module logger.
If the argument passed is a module, find the logger for that module using
the modules' name; if it's a string, finds a logger of that name; if an
integer, walks the stack to the module at that height.
The logger is always extended with a ``.configure()`` method allowing
its log levels for syslog and stderr to be adjusted or automatically
initialized as per the documentation for `configure()` below.
|
[
"Finds",
"a",
"module",
"logger",
"."
] |
f045a68f9d3eff946c0a0d3147edff0ec0c0b344
|
https://github.com/drcloud/magiclog/blob/f045a68f9d3eff946c0a0d3147edff0ec0c0b344/magiclog.py#L21-L36
|
243,475
|
drcloud/magiclog
|
magiclog.py
|
Configuration.auto
|
def auto(cls, syslog=None, stderr=None, level=None, extended=None,
server=None):
"""Tries to guess a sound logging configuration.
"""
level = norm_level(level) or logging.INFO
if syslog is None and stderr is None:
if sys.stderr.isatty() or syslog_path() is None:
log.info('Defaulting to STDERR logging.')
syslog, stderr = None, level
if extended is None:
extended = (stderr or 0) <= logging.DEBUG
else:
log.info('Defaulting to logging with Syslog.')
syslog, stderr = level, None
return cls(syslog=syslog, stderr=stderr, extended=extended,
server=server)
|
python
|
def auto(cls, syslog=None, stderr=None, level=None, extended=None,
server=None):
"""Tries to guess a sound logging configuration.
"""
level = norm_level(level) or logging.INFO
if syslog is None and stderr is None:
if sys.stderr.isatty() or syslog_path() is None:
log.info('Defaulting to STDERR logging.')
syslog, stderr = None, level
if extended is None:
extended = (stderr or 0) <= logging.DEBUG
else:
log.info('Defaulting to logging with Syslog.')
syslog, stderr = level, None
return cls(syslog=syslog, stderr=stderr, extended=extended,
server=server)
|
[
"def",
"auto",
"(",
"cls",
",",
"syslog",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"level",
"=",
"None",
",",
"extended",
"=",
"None",
",",
"server",
"=",
"None",
")",
":",
"level",
"=",
"norm_level",
"(",
"level",
")",
"or",
"logging",
".",
"INFO",
"if",
"syslog",
"is",
"None",
"and",
"stderr",
"is",
"None",
":",
"if",
"sys",
".",
"stderr",
".",
"isatty",
"(",
")",
"or",
"syslog_path",
"(",
")",
"is",
"None",
":",
"log",
".",
"info",
"(",
"'Defaulting to STDERR logging.'",
")",
"syslog",
",",
"stderr",
"=",
"None",
",",
"level",
"if",
"extended",
"is",
"None",
":",
"extended",
"=",
"(",
"stderr",
"or",
"0",
")",
"<=",
"logging",
".",
"DEBUG",
"else",
":",
"log",
".",
"info",
"(",
"'Defaulting to logging with Syslog.'",
")",
"syslog",
",",
"stderr",
"=",
"level",
",",
"None",
"return",
"cls",
"(",
"syslog",
"=",
"syslog",
",",
"stderr",
"=",
"stderr",
",",
"extended",
"=",
"extended",
",",
"server",
"=",
"server",
")"
] |
Tries to guess a sound logging configuration.
|
[
"Tries",
"to",
"guess",
"a",
"sound",
"logging",
"configuration",
"."
] |
f045a68f9d3eff946c0a0d3147edff0ec0c0b344
|
https://github.com/drcloud/magiclog/blob/f045a68f9d3eff946c0a0d3147edff0ec0c0b344/magiclog.py#L68-L83
|
243,476
|
Othernet-Project/bottle-fdsend
|
fdsend/sendfile.py
|
send_file
|
def send_file(fd, filename=None, size=None, timestamp=None, ctype=None,
charset=CHARSET, attachment=False, wrapper=DEFAULT_WRAPPER):
""" Send a file represented by file object
This function constcuts a HTTPResponse object that uses a file descriptor
as response body. The file descriptor is suppled as ``fd`` argument and it
must have a ``read()`` method. ``ValueError`` is raised when this is not
the case. It supports `byte serving`_ using Range header, and makes the
best effort to set all appropriate headers. It also supports HEAD queries.
Because we are dealing with file descriptors and not physical files, the
user must also supply the file metadata such as filename, size, and
timestamp.
The ``filename`` argument is an arbitrary filename. It is used to guess the
content type, and also to set the content disposition in case of
attachments.
The ``size`` argument is the payload size in bytes. If it is omitted, the
content length header is not set, and byte serving does not work.
The ``timestamp`` argument is the number of seconds since Unix epoch when
the file was created or last modified. If this argument is omitted,
If-Modified-Since request headers cannot be honored.
To explicitly specify the content type, the ``ctype`` argument can be used.
This should be a valid MIME type of the payload.
Default encoding (used as charset parameter in Content-Type header) is
'UTF-8'. This can be overridden by using the ``charset`` argument.
The ``attachment`` argumnet can be set to ``True`` to add the
Content-Dispositon response header. Value of the header is then set to the
filename.
The ``wrapper`` argument is used to wrap the file descriptor when doing
byte serving. The default is to use ``fdsend.rangewrapper.RangeWrapper``
class, but there are alternatives as ``fdsend.rangewrapper.range_iter`` and
``bottle._file_iter_range``. The wrappers provided by this package are
written to specifically handle file handles that do not have a ``seek()``
method. If this is not your case, you may safely use the bottle's wrapper.
The primary difference between ``fdsend.rangewrapper.RangeWrapper`` and
``fdsend.rangewrapper.range_iter`` is that the former returns a file-like
object with ``read()`` method, which may or may not increase performance
when used on a WSGI server that supports ``wsgi.file_wrapper`` feature. The
latter returns an iterator and the response is returned as is without the
use of a ``file_wrapper``. This may have some benefits when it comes to
memory usage.
Benchmarking and profiling is the best way to determine which wrapper you
want to use, or you need to implement your own.
To implement your own wrapper, you need to create a callable or a class
that takes the following arguments:
- file descriptor
- offset (in bytes from start of the file)
- length (total number of bytes in the range)
The return value of the wrapper must be either an iterable or file-like
object that implements ``read()`` and ``close()`` methods with the usual
semantics.
The code is partly based on ``bottle.static_file``.
.. _byte serving: https://tools.ietf.org/html/rfc2616#page-138
"""
if not hasattr(fd, 'read'):
raise ValueError("Object '{}' has no read() method".format(fd))
headers = {}
status = 200
if not ctype and filename is not None:
ctype, enc = mimetypes.guess_type(filename)
if enc:
headers['Content-Encoding'] = enc
if ctype:
if ctype.startswith('text/'):
# We expect and assume all text files are encoded UTF-8. It's
# broadcaster's job to ensure this is true.
ctype += '; charset=%s' % charset
headers['Content-Type'] = ctype
if size:
headers['Content-Length'] = size
headers['Accept-Ranges'] = 'bytes'
if timestamp:
headers['Last-Modified'] = format_ts(timestamp)
# Check if If-Modified-Since header is in request and respond early
modsince = request.environ.get('HTTP_IF_MODIFIED_SINCE')
print(modsince)
modsince = modsince and parse_date(modsince.split(';')[0].strip())
if modsince is not None and modsince >= timestamp:
headers['Date'] = format_ts()
return HTTPResponse(status=304, **headers)
if attachment and filename:
headers['Content-Disposition'] = 'attachment; filename="%s"' % filename
if request.method == 'HEAD':
# Request is a HEAD, so remove any fd body
fd = ''
ranges = request.environ.get('HTTP_RANGE')
if size and ranges:
ranges = list(parse_range_header(ranges, size))
if not ranges:
return HTTPError(416, 'Request Range Not Satisfiable')
start, end = ranges[0]
headers['Content-Range'] = 'bytes %d-%d/%d' % (start, end - 1, size)
length = end - start
headers['Content-Length'] = str(length)
fd = wrapper(fd, start, length)
status = 206
return HTTPResponse(fd, status=status, **headers)
|
python
|
def send_file(fd, filename=None, size=None, timestamp=None, ctype=None,
charset=CHARSET, attachment=False, wrapper=DEFAULT_WRAPPER):
""" Send a file represented by file object
This function constcuts a HTTPResponse object that uses a file descriptor
as response body. The file descriptor is suppled as ``fd`` argument and it
must have a ``read()`` method. ``ValueError`` is raised when this is not
the case. It supports `byte serving`_ using Range header, and makes the
best effort to set all appropriate headers. It also supports HEAD queries.
Because we are dealing with file descriptors and not physical files, the
user must also supply the file metadata such as filename, size, and
timestamp.
The ``filename`` argument is an arbitrary filename. It is used to guess the
content type, and also to set the content disposition in case of
attachments.
The ``size`` argument is the payload size in bytes. If it is omitted, the
content length header is not set, and byte serving does not work.
The ``timestamp`` argument is the number of seconds since Unix epoch when
the file was created or last modified. If this argument is omitted,
If-Modified-Since request headers cannot be honored.
To explicitly specify the content type, the ``ctype`` argument can be used.
This should be a valid MIME type of the payload.
Default encoding (used as charset parameter in Content-Type header) is
'UTF-8'. This can be overridden by using the ``charset`` argument.
The ``attachment`` argumnet can be set to ``True`` to add the
Content-Dispositon response header. Value of the header is then set to the
filename.
The ``wrapper`` argument is used to wrap the file descriptor when doing
byte serving. The default is to use ``fdsend.rangewrapper.RangeWrapper``
class, but there are alternatives as ``fdsend.rangewrapper.range_iter`` and
``bottle._file_iter_range``. The wrappers provided by this package are
written to specifically handle file handles that do not have a ``seek()``
method. If this is not your case, you may safely use the bottle's wrapper.
The primary difference between ``fdsend.rangewrapper.RangeWrapper`` and
``fdsend.rangewrapper.range_iter`` is that the former returns a file-like
object with ``read()`` method, which may or may not increase performance
when used on a WSGI server that supports ``wsgi.file_wrapper`` feature. The
latter returns an iterator and the response is returned as is without the
use of a ``file_wrapper``. This may have some benefits when it comes to
memory usage.
Benchmarking and profiling is the best way to determine which wrapper you
want to use, or you need to implement your own.
To implement your own wrapper, you need to create a callable or a class
that takes the following arguments:
- file descriptor
- offset (in bytes from start of the file)
- length (total number of bytes in the range)
The return value of the wrapper must be either an iterable or file-like
object that implements ``read()`` and ``close()`` methods with the usual
semantics.
The code is partly based on ``bottle.static_file``.
.. _byte serving: https://tools.ietf.org/html/rfc2616#page-138
"""
if not hasattr(fd, 'read'):
raise ValueError("Object '{}' has no read() method".format(fd))
headers = {}
status = 200
if not ctype and filename is not None:
ctype, enc = mimetypes.guess_type(filename)
if enc:
headers['Content-Encoding'] = enc
if ctype:
if ctype.startswith('text/'):
# We expect and assume all text files are encoded UTF-8. It's
# broadcaster's job to ensure this is true.
ctype += '; charset=%s' % charset
headers['Content-Type'] = ctype
if size:
headers['Content-Length'] = size
headers['Accept-Ranges'] = 'bytes'
if timestamp:
headers['Last-Modified'] = format_ts(timestamp)
# Check if If-Modified-Since header is in request and respond early
modsince = request.environ.get('HTTP_IF_MODIFIED_SINCE')
print(modsince)
modsince = modsince and parse_date(modsince.split(';')[0].strip())
if modsince is not None and modsince >= timestamp:
headers['Date'] = format_ts()
return HTTPResponse(status=304, **headers)
if attachment and filename:
headers['Content-Disposition'] = 'attachment; filename="%s"' % filename
if request.method == 'HEAD':
# Request is a HEAD, so remove any fd body
fd = ''
ranges = request.environ.get('HTTP_RANGE')
if size and ranges:
ranges = list(parse_range_header(ranges, size))
if not ranges:
return HTTPError(416, 'Request Range Not Satisfiable')
start, end = ranges[0]
headers['Content-Range'] = 'bytes %d-%d/%d' % (start, end - 1, size)
length = end - start
headers['Content-Length'] = str(length)
fd = wrapper(fd, start, length)
status = 206
return HTTPResponse(fd, status=status, **headers)
|
[
"def",
"send_file",
"(",
"fd",
",",
"filename",
"=",
"None",
",",
"size",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"ctype",
"=",
"None",
",",
"charset",
"=",
"CHARSET",
",",
"attachment",
"=",
"False",
",",
"wrapper",
"=",
"DEFAULT_WRAPPER",
")",
":",
"if",
"not",
"hasattr",
"(",
"fd",
",",
"'read'",
")",
":",
"raise",
"ValueError",
"(",
"\"Object '{}' has no read() method\"",
".",
"format",
"(",
"fd",
")",
")",
"headers",
"=",
"{",
"}",
"status",
"=",
"200",
"if",
"not",
"ctype",
"and",
"filename",
"is",
"not",
"None",
":",
"ctype",
",",
"enc",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"if",
"enc",
":",
"headers",
"[",
"'Content-Encoding'",
"]",
"=",
"enc",
"if",
"ctype",
":",
"if",
"ctype",
".",
"startswith",
"(",
"'text/'",
")",
":",
"# We expect and assume all text files are encoded UTF-8. It's",
"# broadcaster's job to ensure this is true.",
"ctype",
"+=",
"'; charset=%s'",
"%",
"charset",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"ctype",
"if",
"size",
":",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"size",
"headers",
"[",
"'Accept-Ranges'",
"]",
"=",
"'bytes'",
"if",
"timestamp",
":",
"headers",
"[",
"'Last-Modified'",
"]",
"=",
"format_ts",
"(",
"timestamp",
")",
"# Check if If-Modified-Since header is in request and respond early",
"modsince",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'HTTP_IF_MODIFIED_SINCE'",
")",
"print",
"(",
"modsince",
")",
"modsince",
"=",
"modsince",
"and",
"parse_date",
"(",
"modsince",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
"if",
"modsince",
"is",
"not",
"None",
"and",
"modsince",
">=",
"timestamp",
":",
"headers",
"[",
"'Date'",
"]",
"=",
"format_ts",
"(",
")",
"return",
"HTTPResponse",
"(",
"status",
"=",
"304",
",",
"*",
"*",
"headers",
")",
"if",
"attachment",
"and",
"filename",
":",
"headers",
"[",
"'Content-Disposition'",
"]",
"=",
"'attachment; filename=\"%s\"'",
"%",
"filename",
"if",
"request",
".",
"method",
"==",
"'HEAD'",
":",
"# Request is a HEAD, so remove any fd body",
"fd",
"=",
"''",
"ranges",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'HTTP_RANGE'",
")",
"if",
"size",
"and",
"ranges",
":",
"ranges",
"=",
"list",
"(",
"parse_range_header",
"(",
"ranges",
",",
"size",
")",
")",
"if",
"not",
"ranges",
":",
"return",
"HTTPError",
"(",
"416",
",",
"'Request Range Not Satisfiable'",
")",
"start",
",",
"end",
"=",
"ranges",
"[",
"0",
"]",
"headers",
"[",
"'Content-Range'",
"]",
"=",
"'bytes %d-%d/%d'",
"%",
"(",
"start",
",",
"end",
"-",
"1",
",",
"size",
")",
"length",
"=",
"end",
"-",
"start",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"str",
"(",
"length",
")",
"fd",
"=",
"wrapper",
"(",
"fd",
",",
"start",
",",
"length",
")",
"status",
"=",
"206",
"return",
"HTTPResponse",
"(",
"fd",
",",
"status",
"=",
"status",
",",
"*",
"*",
"headers",
")"
] |
Send a file represented by file object
This function constcuts a HTTPResponse object that uses a file descriptor
as response body. The file descriptor is suppled as ``fd`` argument and it
must have a ``read()`` method. ``ValueError`` is raised when this is not
the case. It supports `byte serving`_ using Range header, and makes the
best effort to set all appropriate headers. It also supports HEAD queries.
Because we are dealing with file descriptors and not physical files, the
user must also supply the file metadata such as filename, size, and
timestamp.
The ``filename`` argument is an arbitrary filename. It is used to guess the
content type, and also to set the content disposition in case of
attachments.
The ``size`` argument is the payload size in bytes. If it is omitted, the
content length header is not set, and byte serving does not work.
The ``timestamp`` argument is the number of seconds since Unix epoch when
the file was created or last modified. If this argument is omitted,
If-Modified-Since request headers cannot be honored.
To explicitly specify the content type, the ``ctype`` argument can be used.
This should be a valid MIME type of the payload.
Default encoding (used as charset parameter in Content-Type header) is
'UTF-8'. This can be overridden by using the ``charset`` argument.
The ``attachment`` argumnet can be set to ``True`` to add the
Content-Dispositon response header. Value of the header is then set to the
filename.
The ``wrapper`` argument is used to wrap the file descriptor when doing
byte serving. The default is to use ``fdsend.rangewrapper.RangeWrapper``
class, but there are alternatives as ``fdsend.rangewrapper.range_iter`` and
``bottle._file_iter_range``. The wrappers provided by this package are
written to specifically handle file handles that do not have a ``seek()``
method. If this is not your case, you may safely use the bottle's wrapper.
The primary difference between ``fdsend.rangewrapper.RangeWrapper`` and
``fdsend.rangewrapper.range_iter`` is that the former returns a file-like
object with ``read()`` method, which may or may not increase performance
when used on a WSGI server that supports ``wsgi.file_wrapper`` feature. The
latter returns an iterator and the response is returned as is without the
use of a ``file_wrapper``. This may have some benefits when it comes to
memory usage.
Benchmarking and profiling is the best way to determine which wrapper you
want to use, or you need to implement your own.
To implement your own wrapper, you need to create a callable or a class
that takes the following arguments:
- file descriptor
- offset (in bytes from start of the file)
- length (total number of bytes in the range)
The return value of the wrapper must be either an iterable or file-like
object that implements ``read()`` and ``close()`` methods with the usual
semantics.
The code is partly based on ``bottle.static_file``.
.. _byte serving: https://tools.ietf.org/html/rfc2616#page-138
|
[
"Send",
"a",
"file",
"represented",
"by",
"file",
"object"
] |
5ff27e605e8cf878e24c71c1446dcf5c8caf4898
|
https://github.com/Othernet-Project/bottle-fdsend/blob/5ff27e605e8cf878e24c71c1446dcf5c8caf4898/fdsend/sendfile.py#L36-L156
|
243,477
|
maxfischer2781/chainlet
|
chainlet/primitives/linker.py
|
LinkPrimitives.convert
|
def convert(self, element):
"""Convert an element to a chainlink"""
if isinstance(element, self.base_link_type):
return element
for converter in self.converters:
link = converter(element)
if link is not NotImplemented:
return link
raise TypeError('%r cannot be converted to a chainlink' % element)
|
python
|
def convert(self, element):
"""Convert an element to a chainlink"""
if isinstance(element, self.base_link_type):
return element
for converter in self.converters:
link = converter(element)
if link is not NotImplemented:
return link
raise TypeError('%r cannot be converted to a chainlink' % element)
|
[
"def",
"convert",
"(",
"self",
",",
"element",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"self",
".",
"base_link_type",
")",
":",
"return",
"element",
"for",
"converter",
"in",
"self",
".",
"converters",
":",
"link",
"=",
"converter",
"(",
"element",
")",
"if",
"link",
"is",
"not",
"NotImplemented",
":",
"return",
"link",
"raise",
"TypeError",
"(",
"'%r cannot be converted to a chainlink'",
"%",
"element",
")"
] |
Convert an element to a chainlink
|
[
"Convert",
"an",
"element",
"to",
"a",
"chainlink"
] |
4e17f9992b4780bd0d9309202e2847df640bffe8
|
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/primitives/linker.py#L39-L47
|
243,478
|
ronaldguillen/wave
|
wave/views.py
|
get_view_name
|
def get_view_name(view_cls, suffix=None):
"""
Given a view class, return a textual name to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_NAME_FUNCTION` setting.
"""
name = view_cls.__name__
name = formatting.remove_trailing_string(name, 'View')
name = formatting.remove_trailing_string(name, 'ViewSet')
name = formatting.camelcase_to_spaces(name)
if suffix:
name += ' ' + suffix
return name
|
python
|
def get_view_name(view_cls, suffix=None):
"""
Given a view class, return a textual name to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_NAME_FUNCTION` setting.
"""
name = view_cls.__name__
name = formatting.remove_trailing_string(name, 'View')
name = formatting.remove_trailing_string(name, 'ViewSet')
name = formatting.camelcase_to_spaces(name)
if suffix:
name += ' ' + suffix
return name
|
[
"def",
"get_view_name",
"(",
"view_cls",
",",
"suffix",
"=",
"None",
")",
":",
"name",
"=",
"view_cls",
".",
"__name__",
"name",
"=",
"formatting",
".",
"remove_trailing_string",
"(",
"name",
",",
"'View'",
")",
"name",
"=",
"formatting",
".",
"remove_trailing_string",
"(",
"name",
",",
"'ViewSet'",
")",
"name",
"=",
"formatting",
".",
"camelcase_to_spaces",
"(",
"name",
")",
"if",
"suffix",
":",
"name",
"+=",
"' '",
"+",
"suffix",
"return",
"name"
] |
Given a view class, return a textual name to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_NAME_FUNCTION` setting.
|
[
"Given",
"a",
"view",
"class",
"return",
"a",
"textual",
"name",
"to",
"represent",
"the",
"view",
".",
"This",
"name",
"is",
"used",
"in",
"the",
"browsable",
"API",
"and",
"in",
"OPTIONS",
"responses",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L24-L38
|
243,479
|
ronaldguillen/wave
|
wave/views.py
|
get_view_description
|
def get_view_description(view_cls, html=False):
"""
Given a view class, return a textual description to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
"""
description = view_cls.__doc__ or ''
description = formatting.dedent(smart_text(description))
if html:
return formatting.markup_description(description)
return description
|
python
|
def get_view_description(view_cls, html=False):
"""
Given a view class, return a textual description to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
"""
description = view_cls.__doc__ or ''
description = formatting.dedent(smart_text(description))
if html:
return formatting.markup_description(description)
return description
|
[
"def",
"get_view_description",
"(",
"view_cls",
",",
"html",
"=",
"False",
")",
":",
"description",
"=",
"view_cls",
".",
"__doc__",
"or",
"''",
"description",
"=",
"formatting",
".",
"dedent",
"(",
"smart_text",
"(",
"description",
")",
")",
"if",
"html",
":",
"return",
"formatting",
".",
"markup_description",
"(",
"description",
")",
"return",
"description"
] |
Given a view class, return a textual description to represent the view.
This name is used in the browsable API, and in OPTIONS responses.
This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting.
|
[
"Given",
"a",
"view",
"class",
"return",
"a",
"textual",
"description",
"to",
"represent",
"the",
"view",
".",
"This",
"name",
"is",
"used",
"in",
"the",
"browsable",
"API",
"and",
"in",
"OPTIONS",
"responses",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L41-L52
|
243,480
|
ronaldguillen/wave
|
wave/views.py
|
exception_handler
|
def exception_handler(exc, context):
"""
Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's built-in `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a 500 error
to be raised.
"""
if isinstance(exc, exceptions.APIException):
headers = {}
if getattr(exc, 'auth_header', None):
headers['WWW-Authenticate'] = exc.auth_header
if getattr(exc, 'wait', None):
headers['Retry-After'] = '%d' % exc.wait
if isinstance(exc.detail, (list, dict)):
data = exc.detail
else:
data = {'message': exc.detail}
set_rollback()
return Response(data, status=exc.status_code, headers=headers)
elif isinstance(exc, Http404):
msg = _('Not found.')
data = {'message': six.text_type(msg)}
set_rollback()
return Response(data, status=status.HTTP_404_NOT_FOUND)
elif isinstance(exc, PermissionDenied):
msg = _('Permission denied.')
data = {'message': six.text_type(msg)}
set_rollback()
return Response(data, status=status.HTTP_403_FORBIDDEN)
# Note: Unhandled exceptions will raise a 500 error.
return None
|
python
|
def exception_handler(exc, context):
"""
Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's built-in `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a 500 error
to be raised.
"""
if isinstance(exc, exceptions.APIException):
headers = {}
if getattr(exc, 'auth_header', None):
headers['WWW-Authenticate'] = exc.auth_header
if getattr(exc, 'wait', None):
headers['Retry-After'] = '%d' % exc.wait
if isinstance(exc.detail, (list, dict)):
data = exc.detail
else:
data = {'message': exc.detail}
set_rollback()
return Response(data, status=exc.status_code, headers=headers)
elif isinstance(exc, Http404):
msg = _('Not found.')
data = {'message': six.text_type(msg)}
set_rollback()
return Response(data, status=status.HTTP_404_NOT_FOUND)
elif isinstance(exc, PermissionDenied):
msg = _('Permission denied.')
data = {'message': six.text_type(msg)}
set_rollback()
return Response(data, status=status.HTTP_403_FORBIDDEN)
# Note: Unhandled exceptions will raise a 500 error.
return None
|
[
"def",
"exception_handler",
"(",
"exc",
",",
"context",
")",
":",
"if",
"isinstance",
"(",
"exc",
",",
"exceptions",
".",
"APIException",
")",
":",
"headers",
"=",
"{",
"}",
"if",
"getattr",
"(",
"exc",
",",
"'auth_header'",
",",
"None",
")",
":",
"headers",
"[",
"'WWW-Authenticate'",
"]",
"=",
"exc",
".",
"auth_header",
"if",
"getattr",
"(",
"exc",
",",
"'wait'",
",",
"None",
")",
":",
"headers",
"[",
"'Retry-After'",
"]",
"=",
"'%d'",
"%",
"exc",
".",
"wait",
"if",
"isinstance",
"(",
"exc",
".",
"detail",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"data",
"=",
"exc",
".",
"detail",
"else",
":",
"data",
"=",
"{",
"'message'",
":",
"exc",
".",
"detail",
"}",
"set_rollback",
"(",
")",
"return",
"Response",
"(",
"data",
",",
"status",
"=",
"exc",
".",
"status_code",
",",
"headers",
"=",
"headers",
")",
"elif",
"isinstance",
"(",
"exc",
",",
"Http404",
")",
":",
"msg",
"=",
"_",
"(",
"'Not found.'",
")",
"data",
"=",
"{",
"'message'",
":",
"six",
".",
"text_type",
"(",
"msg",
")",
"}",
"set_rollback",
"(",
")",
"return",
"Response",
"(",
"data",
",",
"status",
"=",
"status",
".",
"HTTP_404_NOT_FOUND",
")",
"elif",
"isinstance",
"(",
"exc",
",",
"PermissionDenied",
")",
":",
"msg",
"=",
"_",
"(",
"'Permission denied.'",
")",
"data",
"=",
"{",
"'message'",
":",
"six",
".",
"text_type",
"(",
"msg",
")",
"}",
"set_rollback",
"(",
")",
"return",
"Response",
"(",
"data",
",",
"status",
"=",
"status",
".",
"HTTP_403_FORBIDDEN",
")",
"# Note: Unhandled exceptions will raise a 500 error.",
"return",
"None"
] |
Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's built-in `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a 500 error
to be raised.
|
[
"Returns",
"the",
"response",
"that",
"should",
"be",
"used",
"for",
"any",
"given",
"exception",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L55-L95
|
243,481
|
ronaldguillen/wave
|
wave/views.py
|
RestView.as_view
|
def as_view(cls, **initkwargs):
"""
Store the original class on the view function.
This allows us to discover information about the view when we do URL
reverse lookups. Used for breadcrumb generation.
"""
if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
def force_evaluation():
raise RuntimeError(
'Do not evaluate the `.queryset` attribute directly, '
'as the result will be cached and reused between requests. '
'Use `.all()` or call `.get_queryset()` instead.'
)
cls.queryset._fetch_all = force_evaluation
cls.queryset._result_iter = force_evaluation # Django <= 1.5
view = super(RestView, cls).as_view(**initkwargs)
view.cls = cls
# Note: session based authentication is explicitly CSRF validated,
# all other authentication is CSRF exempt.
return csrf_exempt(view)
|
python
|
def as_view(cls, **initkwargs):
"""
Store the original class on the view function.
This allows us to discover information about the view when we do URL
reverse lookups. Used for breadcrumb generation.
"""
if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
def force_evaluation():
raise RuntimeError(
'Do not evaluate the `.queryset` attribute directly, '
'as the result will be cached and reused between requests. '
'Use `.all()` or call `.get_queryset()` instead.'
)
cls.queryset._fetch_all = force_evaluation
cls.queryset._result_iter = force_evaluation # Django <= 1.5
view = super(RestView, cls).as_view(**initkwargs)
view.cls = cls
# Note: session based authentication is explicitly CSRF validated,
# all other authentication is CSRF exempt.
return csrf_exempt(view)
|
[
"def",
"as_view",
"(",
"cls",
",",
"*",
"*",
"initkwargs",
")",
":",
"if",
"isinstance",
"(",
"getattr",
"(",
"cls",
",",
"'queryset'",
",",
"None",
")",
",",
"models",
".",
"query",
".",
"QuerySet",
")",
":",
"def",
"force_evaluation",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Do not evaluate the `.queryset` attribute directly, '",
"'as the result will be cached and reused between requests. '",
"'Use `.all()` or call `.get_queryset()` instead.'",
")",
"cls",
".",
"queryset",
".",
"_fetch_all",
"=",
"force_evaluation",
"cls",
".",
"queryset",
".",
"_result_iter",
"=",
"force_evaluation",
"# Django <= 1.5",
"view",
"=",
"super",
"(",
"RestView",
",",
"cls",
")",
".",
"as_view",
"(",
"*",
"*",
"initkwargs",
")",
"view",
".",
"cls",
"=",
"cls",
"# Note: session based authentication is explicitly CSRF validated,",
"# all other authentication is CSRF exempt.",
"return",
"csrf_exempt",
"(",
"view",
")"
] |
Store the original class on the view function.
This allows us to discover information about the view when we do URL
reverse lookups. Used for breadcrumb generation.
|
[
"Store",
"the",
"original",
"class",
"on",
"the",
"view",
"function",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L114-L136
|
243,482
|
ronaldguillen/wave
|
wave/views.py
|
RestView.permission_denied
|
def permission_denied(self, request, message=None):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if not request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied(detail=message)
|
python
|
def permission_denied(self, request, message=None):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if not request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied(detail=message)
|
[
"def",
"permission_denied",
"(",
"self",
",",
"request",
",",
"message",
"=",
"None",
")",
":",
"if",
"not",
"request",
".",
"successful_authenticator",
":",
"raise",
"exceptions",
".",
"NotAuthenticated",
"(",
")",
"raise",
"exceptions",
".",
"PermissionDenied",
"(",
"detail",
"=",
"message",
")"
] |
If request is not permitted, determine what kind of exception to raise.
|
[
"If",
"request",
"is",
"not",
"permitted",
"determine",
"what",
"kind",
"of",
"exception",
"to",
"raise",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L161-L167
|
243,483
|
ronaldguillen/wave
|
wave/views.py
|
RestView.get_view_name
|
def get_view_name(self):
"""
Return the view name, as used in OPTIONS responses and in the
browsable API.
"""
func = self.settings.VIEW_NAME_FUNCTION
return func(self.__class__, getattr(self, 'suffix', None))
|
python
|
def get_view_name(self):
"""
Return the view name, as used in OPTIONS responses and in the
browsable API.
"""
func = self.settings.VIEW_NAME_FUNCTION
return func(self.__class__, getattr(self, 'suffix', None))
|
[
"def",
"get_view_name",
"(",
"self",
")",
":",
"func",
"=",
"self",
".",
"settings",
".",
"VIEW_NAME_FUNCTION",
"return",
"func",
"(",
"self",
".",
"__class__",
",",
"getattr",
"(",
"self",
",",
"'suffix'",
",",
"None",
")",
")"
] |
Return the view name, as used in OPTIONS responses and in the
browsable API.
|
[
"Return",
"the",
"view",
"name",
"as",
"used",
"in",
"OPTIONS",
"responses",
"and",
"in",
"the",
"browsable",
"API",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L223-L229
|
243,484
|
ronaldguillen/wave
|
wave/views.py
|
RestView.get_view_description
|
def get_view_description(self, html=False):
"""
Return some descriptive text for the view, as used in OPTIONS responses
and in the browsable API.
"""
func = self.settings.VIEW_DESCRIPTION_FUNCTION
return func(self.__class__, html)
|
python
|
def get_view_description(self, html=False):
"""
Return some descriptive text for the view, as used in OPTIONS responses
and in the browsable API.
"""
func = self.settings.VIEW_DESCRIPTION_FUNCTION
return func(self.__class__, html)
|
[
"def",
"get_view_description",
"(",
"self",
",",
"html",
"=",
"False",
")",
":",
"func",
"=",
"self",
".",
"settings",
".",
"VIEW_DESCRIPTION_FUNCTION",
"return",
"func",
"(",
"self",
".",
"__class__",
",",
"html",
")"
] |
Return some descriptive text for the view, as used in OPTIONS responses
and in the browsable API.
|
[
"Return",
"some",
"descriptive",
"text",
"for",
"the",
"view",
"as",
"used",
"in",
"OPTIONS",
"responses",
"and",
"in",
"the",
"browsable",
"API",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L231-L237
|
243,485
|
ronaldguillen/wave
|
wave/views.py
|
RestView.get_format_suffix
|
def get_format_suffix(self, **kwargs):
"""
Determine if the request includes a '.json' style format suffix
"""
if self.settings.FORMAT_SUFFIX_KWARG:
return kwargs.get(self.settings.FORMAT_SUFFIX_KWARG)
|
python
|
def get_format_suffix(self, **kwargs):
"""
Determine if the request includes a '.json' style format suffix
"""
if self.settings.FORMAT_SUFFIX_KWARG:
return kwargs.get(self.settings.FORMAT_SUFFIX_KWARG)
|
[
"def",
"get_format_suffix",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"settings",
".",
"FORMAT_SUFFIX_KWARG",
":",
"return",
"kwargs",
".",
"get",
"(",
"self",
".",
"settings",
".",
"FORMAT_SUFFIX_KWARG",
")"
] |
Determine if the request includes a '.json' style format suffix
|
[
"Determine",
"if",
"the",
"request",
"includes",
"a",
".",
"json",
"style",
"format",
"suffix"
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L241-L246
|
243,486
|
ronaldguillen/wave
|
wave/views.py
|
RestView.get_content_negotiator
|
def get_content_negotiator(self):
"""
Instantiate and return the content negotiation class to use.
"""
if not getattr(self, '_negotiator', None):
self._negotiator = self.content_negotiation_class()
return self._negotiator
|
python
|
def get_content_negotiator(self):
"""
Instantiate and return the content negotiation class to use.
"""
if not getattr(self, '_negotiator', None):
self._negotiator = self.content_negotiation_class()
return self._negotiator
|
[
"def",
"get_content_negotiator",
"(",
"self",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'_negotiator'",
",",
"None",
")",
":",
"self",
".",
"_negotiator",
"=",
"self",
".",
"content_negotiation_class",
"(",
")",
"return",
"self",
".",
"_negotiator"
] |
Instantiate and return the content negotiation class to use.
|
[
"Instantiate",
"and",
"return",
"the",
"content",
"negotiation",
"class",
"to",
"use",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L278-L284
|
243,487
|
ronaldguillen/wave
|
wave/views.py
|
RestView.perform_content_negotiation
|
def perform_content_negotiation(self, request, force=False):
"""
Determine which renderer and media type to use render the response.
"""
renderers = self.get_renderers()
conneg = self.get_content_negotiator()
try:
return conneg.select_renderer(request, renderers, self.format_kwarg)
except Exception:
if force:
return (renderers[0], renderers[0].media_type)
raise
|
python
|
def perform_content_negotiation(self, request, force=False):
"""
Determine which renderer and media type to use render the response.
"""
renderers = self.get_renderers()
conneg = self.get_content_negotiator()
try:
return conneg.select_renderer(request, renderers, self.format_kwarg)
except Exception:
if force:
return (renderers[0], renderers[0].media_type)
raise
|
[
"def",
"perform_content_negotiation",
"(",
"self",
",",
"request",
",",
"force",
"=",
"False",
")",
":",
"renderers",
"=",
"self",
".",
"get_renderers",
"(",
")",
"conneg",
"=",
"self",
".",
"get_content_negotiator",
"(",
")",
"try",
":",
"return",
"conneg",
".",
"select_renderer",
"(",
"request",
",",
"renderers",
",",
"self",
".",
"format_kwarg",
")",
"except",
"Exception",
":",
"if",
"force",
":",
"return",
"(",
"renderers",
"[",
"0",
"]",
",",
"renderers",
"[",
"0",
"]",
".",
"media_type",
")",
"raise"
] |
Determine which renderer and media type to use render the response.
|
[
"Determine",
"which",
"renderer",
"and",
"media",
"type",
"to",
"use",
"render",
"the",
"response",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L288-L300
|
243,488
|
ronaldguillen/wave
|
wave/views.py
|
RestView.check_throttles
|
def check_throttles(self, request):
"""
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
"""
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
self.throttled(request, throttle.wait())
|
python
|
def check_throttles(self, request):
"""
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
"""
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
self.throttled(request, throttle.wait())
|
[
"def",
"check_throttles",
"(",
"self",
",",
"request",
")",
":",
"for",
"throttle",
"in",
"self",
".",
"get_throttles",
"(",
")",
":",
"if",
"not",
"throttle",
".",
"allow_request",
"(",
"request",
",",
"self",
")",
":",
"self",
".",
"throttled",
"(",
"request",
",",
"throttle",
".",
"wait",
"(",
")",
")"
] |
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
|
[
"Check",
"if",
"request",
"should",
"be",
"throttled",
".",
"Raises",
"an",
"appropriate",
"exception",
"if",
"the",
"request",
"is",
"throttled",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L334-L341
|
243,489
|
ronaldguillen/wave
|
wave/views.py
|
RestView.initialize_request
|
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
|
python
|
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
|
[
"def",
"initialize_request",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"parser_context",
"=",
"self",
".",
"get_parser_context",
"(",
"request",
")",
"return",
"Request",
"(",
"request",
",",
"parsers",
"=",
"self",
".",
"get_parsers",
"(",
")",
",",
"authenticators",
"=",
"self",
".",
"get_authenticators",
"(",
")",
",",
"negotiator",
"=",
"self",
".",
"get_content_negotiator",
"(",
")",
",",
"parser_context",
"=",
"parser_context",
")"
] |
Returns the initial request object.
|
[
"Returns",
"the",
"initial",
"request",
"object",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L355-L367
|
243,490
|
ronaldguillen/wave
|
wave/views.py
|
RestView.initial
|
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)
# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
|
python
|
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)
# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
|
[
"def",
"initial",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"format_kwarg",
"=",
"self",
".",
"get_format_suffix",
"(",
"*",
"*",
"kwargs",
")",
"# Ensure that the incoming request is permitted",
"self",
".",
"perform_authentication",
"(",
"request",
")",
"self",
".",
"check_permissions",
"(",
"request",
")",
"self",
".",
"check_throttles",
"(",
"request",
")",
"# Perform content negotiation and store the accepted info on the request",
"neg",
"=",
"self",
".",
"perform_content_negotiation",
"(",
"request",
")",
"request",
".",
"accepted_renderer",
",",
"request",
".",
"accepted_media_type",
"=",
"neg",
"# Determine the API version, if versioning is in use.",
"version",
",",
"scheme",
"=",
"self",
".",
"determine_version",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"request",
".",
"version",
",",
"request",
".",
"versioning_scheme",
"=",
"version",
",",
"scheme"
] |
Runs anything that needs to occur prior to calling the method handler.
|
[
"Runs",
"anything",
"that",
"needs",
"to",
"occur",
"prior",
"to",
"calling",
"the",
"method",
"handler",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L369-L386
|
243,491
|
ronaldguillen/wave
|
wave/views.py
|
RestView.finalize_response
|
def finalize_response(self, request, response, *args, **kwargs):
"""
Returns the final response object.
"""
# Make the error obvious if a proper response is not returned
assert isinstance(response, HttpResponseBase), (
'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
'to be returned from the view, but received a `%s`'
% type(response)
)
if isinstance(response, Response):
if not getattr(request, 'accepted_renderer', None):
neg = self.perform_content_negotiation(request, force=True)
request.accepted_renderer, request.accepted_media_type = neg
response.accepted_renderer = request.accepted_renderer
response.accepted_media_type = request.accepted_media_type
response.renderer_context = self.get_renderer_context()
for key, value in self.headers.items():
response[key] = value
return response
|
python
|
def finalize_response(self, request, response, *args, **kwargs):
"""
Returns the final response object.
"""
# Make the error obvious if a proper response is not returned
assert isinstance(response, HttpResponseBase), (
'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
'to be returned from the view, but received a `%s`'
% type(response)
)
if isinstance(response, Response):
if not getattr(request, 'accepted_renderer', None):
neg = self.perform_content_negotiation(request, force=True)
request.accepted_renderer, request.accepted_media_type = neg
response.accepted_renderer = request.accepted_renderer
response.accepted_media_type = request.accepted_media_type
response.renderer_context = self.get_renderer_context()
for key, value in self.headers.items():
response[key] = value
return response
|
[
"def",
"finalize_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make the error obvious if a proper response is not returned",
"assert",
"isinstance",
"(",
"response",
",",
"HttpResponseBase",
")",
",",
"(",
"'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '",
"'to be returned from the view, but received a `%s`'",
"%",
"type",
"(",
"response",
")",
")",
"if",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"if",
"not",
"getattr",
"(",
"request",
",",
"'accepted_renderer'",
",",
"None",
")",
":",
"neg",
"=",
"self",
".",
"perform_content_negotiation",
"(",
"request",
",",
"force",
"=",
"True",
")",
"request",
".",
"accepted_renderer",
",",
"request",
".",
"accepted_media_type",
"=",
"neg",
"response",
".",
"accepted_renderer",
"=",
"request",
".",
"accepted_renderer",
"response",
".",
"accepted_media_type",
"=",
"request",
".",
"accepted_media_type",
"response",
".",
"renderer_context",
"=",
"self",
".",
"get_renderer_context",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"headers",
".",
"items",
"(",
")",
":",
"response",
"[",
"key",
"]",
"=",
"value",
"return",
"response"
] |
Returns the final response object.
|
[
"Returns",
"the",
"final",
"response",
"object",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L388-L411
|
243,492
|
ronaldguillen/wave
|
wave/views.py
|
RestView.handle_exception
|
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate response,
or re-raising the error.
"""
if isinstance(exc, (exceptions.NotAuthenticated,
exceptions.AuthenticationFailed)):
# WWW-Authenticate header for 401 responses, else coerce to 403
auth_header = self.get_authenticate_header(self.request)
if auth_header:
exc.auth_header = auth_header
else:
exc.status_code = status.HTTP_403_FORBIDDEN
exception_handler = self.settings.EXCEPTION_HANDLER
context = self.get_exception_handler_context()
response = exception_handler(exc, context)
if response is None:
raise
response.exception = True
return response
|
python
|
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate response,
or re-raising the error.
"""
if isinstance(exc, (exceptions.NotAuthenticated,
exceptions.AuthenticationFailed)):
# WWW-Authenticate header for 401 responses, else coerce to 403
auth_header = self.get_authenticate_header(self.request)
if auth_header:
exc.auth_header = auth_header
else:
exc.status_code = status.HTTP_403_FORBIDDEN
exception_handler = self.settings.EXCEPTION_HANDLER
context = self.get_exception_handler_context()
response = exception_handler(exc, context)
if response is None:
raise
response.exception = True
return response
|
[
"def",
"handle_exception",
"(",
"self",
",",
"exc",
")",
":",
"if",
"isinstance",
"(",
"exc",
",",
"(",
"exceptions",
".",
"NotAuthenticated",
",",
"exceptions",
".",
"AuthenticationFailed",
")",
")",
":",
"# WWW-Authenticate header for 401 responses, else coerce to 403",
"auth_header",
"=",
"self",
".",
"get_authenticate_header",
"(",
"self",
".",
"request",
")",
"if",
"auth_header",
":",
"exc",
".",
"auth_header",
"=",
"auth_header",
"else",
":",
"exc",
".",
"status_code",
"=",
"status",
".",
"HTTP_403_FORBIDDEN",
"exception_handler",
"=",
"self",
".",
"settings",
".",
"EXCEPTION_HANDLER",
"context",
"=",
"self",
".",
"get_exception_handler_context",
"(",
")",
"response",
"=",
"exception_handler",
"(",
"exc",
",",
"context",
")",
"if",
"response",
"is",
"None",
":",
"raise",
"response",
".",
"exception",
"=",
"True",
"return",
"response"
] |
Handle any exception that occurs, by returning an appropriate response,
or re-raising the error.
|
[
"Handle",
"any",
"exception",
"that",
"occurs",
"by",
"returning",
"an",
"appropriate",
"response",
"or",
"re",
"-",
"raising",
"the",
"error",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L413-L437
|
243,493
|
ronaldguillen/wave
|
wave/views.py
|
RestView.options
|
def options(self, request, *args, **kwargs):
"""
Handler method for HTTP 'OPTIONS' request.
"""
if self.metadata_class is None:
return self.http_method_not_allowed(request, *args, **kwargs)
data = self.metadata_class().determine_metadata(request, self)
return Response(data, status=status.HTTP_200_OK)
|
python
|
def options(self, request, *args, **kwargs):
"""
Handler method for HTTP 'OPTIONS' request.
"""
if self.metadata_class is None:
return self.http_method_not_allowed(request, *args, **kwargs)
data = self.metadata_class().determine_metadata(request, self)
return Response(data, status=status.HTTP_200_OK)
|
[
"def",
"options",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"metadata_class",
"is",
"None",
":",
"return",
"self",
".",
"http_method_not_allowed",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"self",
".",
"metadata_class",
"(",
")",
".",
"determine_metadata",
"(",
"request",
",",
"self",
")",
"return",
"Response",
"(",
"data",
",",
"status",
"=",
"status",
".",
"HTTP_200_OK",
")"
] |
Handler method for HTTP 'OPTIONS' request.
|
[
"Handler",
"method",
"for",
"HTTP",
"OPTIONS",
"request",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L471-L478
|
243,494
|
rfk/regobj
|
regobj.py
|
Key.get_subkey
|
def get_subkey(self,name):
"""Retreive the subkey with the specified name.
If the named subkey is not found, AttributeError is raised;
this is for consistency with the attribute-based access notation.
"""
subkey = Key(name,self)
try:
hkey = subkey.hkey
except WindowsError:
raise AttributeError("subkey '%s' does not exist" % (name,))
return subkey
|
python
|
def get_subkey(self,name):
"""Retreive the subkey with the specified name.
If the named subkey is not found, AttributeError is raised;
this is for consistency with the attribute-based access notation.
"""
subkey = Key(name,self)
try:
hkey = subkey.hkey
except WindowsError:
raise AttributeError("subkey '%s' does not exist" % (name,))
return subkey
|
[
"def",
"get_subkey",
"(",
"self",
",",
"name",
")",
":",
"subkey",
"=",
"Key",
"(",
"name",
",",
"self",
")",
"try",
":",
"hkey",
"=",
"subkey",
".",
"hkey",
"except",
"WindowsError",
":",
"raise",
"AttributeError",
"(",
"\"subkey '%s' does not exist\"",
"%",
"(",
"name",
",",
")",
")",
"return",
"subkey"
] |
Retreive the subkey with the specified name.
If the named subkey is not found, AttributeError is raised;
this is for consistency with the attribute-based access notation.
|
[
"Retreive",
"the",
"subkey",
"with",
"the",
"specified",
"name",
"."
] |
7edd46be28aa3e1427be263911e111c4ca2dfa4f
|
https://github.com/rfk/regobj/blob/7edd46be28aa3e1427be263911e111c4ca2dfa4f/regobj.py#L241-L252
|
243,495
|
rfk/regobj
|
regobj.py
|
Key.set_subkey
|
def set_subkey(self,name,value=None):
"""Create the named subkey and set its value.
There are several different ways to specify the new contents of
the named subkey:
* if 'value' is the Key class, a subclass thereof, or None, then
the subkey is created but not populated with any data.
* if 'value' is a key instance, the data from that key will be
copied into the new subkey.
* if 'value' is a dictionary, the dict's keys are interpreted as
key or value names and the corresponding entries are created
within the new subkey - nested dicts create further subkeys,
while scalar values create values on the subkey.
* any other value will be converted to a Value object and assigned
to the default value for the new subkey.
"""
self.sam |= KEY_CREATE_SUB_KEY
subkey = Key(name,self)
try:
subkey = self.get_subkey(name)
except AttributeError:
_winreg.CreateKey(self.hkey,name)
subkey = self.get_subkey(name)
if value is None:
pass
elif issubclass(type(value),type) and issubclass(value,Key):
pass
elif isinstance(value,Key):
for v in value.values():
subkey[v.name] = v
for k in value.subkeys():
subkey.set_subkey(k.name,k)
elif isinstance(value,dict):
for (nm,val) in value.items():
if isinstance(val,dict):
subkey.set_subkey(nm,val)
elif isinstance(val,Key):
subkey.set_subkey(nm,val)
elif issubclass(type(val),type) and issubclass(val,Key):
subkey.set_subkey(nm,val)
else:
subkey[nm] = val
else:
if not isinstance(value,Value):
value = Value(value)
subkey[value.name] = value
|
python
|
def set_subkey(self,name,value=None):
"""Create the named subkey and set its value.
There are several different ways to specify the new contents of
the named subkey:
* if 'value' is the Key class, a subclass thereof, or None, then
the subkey is created but not populated with any data.
* if 'value' is a key instance, the data from that key will be
copied into the new subkey.
* if 'value' is a dictionary, the dict's keys are interpreted as
key or value names and the corresponding entries are created
within the new subkey - nested dicts create further subkeys,
while scalar values create values on the subkey.
* any other value will be converted to a Value object and assigned
to the default value for the new subkey.
"""
self.sam |= KEY_CREATE_SUB_KEY
subkey = Key(name,self)
try:
subkey = self.get_subkey(name)
except AttributeError:
_winreg.CreateKey(self.hkey,name)
subkey = self.get_subkey(name)
if value is None:
pass
elif issubclass(type(value),type) and issubclass(value,Key):
pass
elif isinstance(value,Key):
for v in value.values():
subkey[v.name] = v
for k in value.subkeys():
subkey.set_subkey(k.name,k)
elif isinstance(value,dict):
for (nm,val) in value.items():
if isinstance(val,dict):
subkey.set_subkey(nm,val)
elif isinstance(val,Key):
subkey.set_subkey(nm,val)
elif issubclass(type(val),type) and issubclass(val,Key):
subkey.set_subkey(nm,val)
else:
subkey[nm] = val
else:
if not isinstance(value,Value):
value = Value(value)
subkey[value.name] = value
|
[
"def",
"set_subkey",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"self",
".",
"sam",
"|=",
"KEY_CREATE_SUB_KEY",
"subkey",
"=",
"Key",
"(",
"name",
",",
"self",
")",
"try",
":",
"subkey",
"=",
"self",
".",
"get_subkey",
"(",
"name",
")",
"except",
"AttributeError",
":",
"_winreg",
".",
"CreateKey",
"(",
"self",
".",
"hkey",
",",
"name",
")",
"subkey",
"=",
"self",
".",
"get_subkey",
"(",
"name",
")",
"if",
"value",
"is",
"None",
":",
"pass",
"elif",
"issubclass",
"(",
"type",
"(",
"value",
")",
",",
"type",
")",
"and",
"issubclass",
"(",
"value",
",",
"Key",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"value",
",",
"Key",
")",
":",
"for",
"v",
"in",
"value",
".",
"values",
"(",
")",
":",
"subkey",
"[",
"v",
".",
"name",
"]",
"=",
"v",
"for",
"k",
"in",
"value",
".",
"subkeys",
"(",
")",
":",
"subkey",
".",
"set_subkey",
"(",
"k",
".",
"name",
",",
"k",
")",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"for",
"(",
"nm",
",",
"val",
")",
"in",
"value",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"subkey",
".",
"set_subkey",
"(",
"nm",
",",
"val",
")",
"elif",
"isinstance",
"(",
"val",
",",
"Key",
")",
":",
"subkey",
".",
"set_subkey",
"(",
"nm",
",",
"val",
")",
"elif",
"issubclass",
"(",
"type",
"(",
"val",
")",
",",
"type",
")",
"and",
"issubclass",
"(",
"val",
",",
"Key",
")",
":",
"subkey",
".",
"set_subkey",
"(",
"nm",
",",
"val",
")",
"else",
":",
"subkey",
"[",
"nm",
"]",
"=",
"val",
"else",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Value",
")",
":",
"value",
"=",
"Value",
"(",
"value",
")",
"subkey",
"[",
"value",
".",
"name",
"]",
"=",
"value"
] |
Create the named subkey and set its value.
There are several different ways to specify the new contents of
the named subkey:
* if 'value' is the Key class, a subclass thereof, or None, then
the subkey is created but not populated with any data.
* if 'value' is a key instance, the data from that key will be
copied into the new subkey.
* if 'value' is a dictionary, the dict's keys are interpreted as
key or value names and the corresponding entries are created
within the new subkey - nested dicts create further subkeys,
while scalar values create values on the subkey.
* any other value will be converted to a Value object and assigned
to the default value for the new subkey.
|
[
"Create",
"the",
"named",
"subkey",
"and",
"set",
"its",
"value",
"."
] |
7edd46be28aa3e1427be263911e111c4ca2dfa4f
|
https://github.com/rfk/regobj/blob/7edd46be28aa3e1427be263911e111c4ca2dfa4f/regobj.py#L254-L301
|
243,496
|
rfk/regobj
|
regobj.py
|
Key.del_subkey
|
def del_subkey(self,name):
"""Delete the named subkey, and any values or keys it contains."""
self.sam |= KEY_WRITE
subkey = self.get_subkey(name)
subkey.clear()
_winreg.DeleteKey(subkey.parent.hkey,subkey.name)
|
python
|
def del_subkey(self,name):
"""Delete the named subkey, and any values or keys it contains."""
self.sam |= KEY_WRITE
subkey = self.get_subkey(name)
subkey.clear()
_winreg.DeleteKey(subkey.parent.hkey,subkey.name)
|
[
"def",
"del_subkey",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"sam",
"|=",
"KEY_WRITE",
"subkey",
"=",
"self",
".",
"get_subkey",
"(",
"name",
")",
"subkey",
".",
"clear",
"(",
")",
"_winreg",
".",
"DeleteKey",
"(",
"subkey",
".",
"parent",
".",
"hkey",
",",
"subkey",
".",
"name",
")"
] |
Delete the named subkey, and any values or keys it contains.
|
[
"Delete",
"the",
"named",
"subkey",
"and",
"any",
"values",
"or",
"keys",
"it",
"contains",
"."
] |
7edd46be28aa3e1427be263911e111c4ca2dfa4f
|
https://github.com/rfk/regobj/blob/7edd46be28aa3e1427be263911e111c4ca2dfa4f/regobj.py#L303-L308
|
243,497
|
rfk/regobj
|
regobj.py
|
Key.clear
|
def clear(self):
"""Remove all subkeys and values from this key."""
self.sam |= KEY_WRITE
for v in list(self.values()):
del self[v.name]
for k in list(self.subkeys()):
self.del_subkey(k.name)
|
python
|
def clear(self):
"""Remove all subkeys and values from this key."""
self.sam |= KEY_WRITE
for v in list(self.values()):
del self[v.name]
for k in list(self.subkeys()):
self.del_subkey(k.name)
|
[
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"sam",
"|=",
"KEY_WRITE",
"for",
"v",
"in",
"list",
"(",
"self",
".",
"values",
"(",
")",
")",
":",
"del",
"self",
"[",
"v",
".",
"name",
"]",
"for",
"k",
"in",
"list",
"(",
"self",
".",
"subkeys",
"(",
")",
")",
":",
"self",
".",
"del_subkey",
"(",
"k",
".",
"name",
")"
] |
Remove all subkeys and values from this key.
|
[
"Remove",
"all",
"subkeys",
"and",
"values",
"from",
"this",
"key",
"."
] |
7edd46be28aa3e1427be263911e111c4ca2dfa4f
|
https://github.com/rfk/regobj/blob/7edd46be28aa3e1427be263911e111c4ca2dfa4f/regobj.py#L426-L432
|
243,498
|
urbn/Caesium
|
caesium/document.py
|
AsyncRevisionStackManager.publish
|
def publish(self):
"""
Iterate over the scheduler collections and apply any actions found
"""
try:
for collection in self.settings.get("scheduler").get("collections"):
yield self.publish_for_collection(collection)
except Exception as ex:
self.logger.error(ex)
|
python
|
def publish(self):
"""
Iterate over the scheduler collections and apply any actions found
"""
try:
for collection in self.settings.get("scheduler").get("collections"):
yield self.publish_for_collection(collection)
except Exception as ex:
self.logger.error(ex)
|
[
"def",
"publish",
"(",
"self",
")",
":",
"try",
":",
"for",
"collection",
"in",
"self",
".",
"settings",
".",
"get",
"(",
"\"scheduler\"",
")",
".",
"get",
"(",
"\"collections\"",
")",
":",
"yield",
"self",
".",
"publish_for_collection",
"(",
"collection",
")",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"logger",
".",
"error",
"(",
"ex",
")"
] |
Iterate over the scheduler collections and apply any actions found
|
[
"Iterate",
"over",
"the",
"scheduler",
"collections",
"and",
"apply",
"any",
"actions",
"found"
] |
2a14fe79724c38fe9a1b20f7b8f518f8c6d50df1
|
https://github.com/urbn/Caesium/blob/2a14fe79724c38fe9a1b20f7b8f518f8c6d50df1/caesium/document.py#L36-L45
|
243,499
|
urbn/Caesium
|
caesium/document.py
|
AsyncRevisionStackManager.set_all_revisions_to_in_process
|
def set_all_revisions_to_in_process(self, ids):
"""
Set all revisions found to in process, so that other threads will not pick them up.
:param list ids:
"""
predicate = {
"_id" : {
"$in" : [ ObjectId(id) for id in ids ]
}
}
set = {"$set": { "inProcess": True }}
yield self.revisions.collection.update(predicate, set, multi=True)
|
python
|
def set_all_revisions_to_in_process(self, ids):
"""
Set all revisions found to in process, so that other threads will not pick them up.
:param list ids:
"""
predicate = {
"_id" : {
"$in" : [ ObjectId(id) for id in ids ]
}
}
set = {"$set": { "inProcess": True }}
yield self.revisions.collection.update(predicate, set, multi=True)
|
[
"def",
"set_all_revisions_to_in_process",
"(",
"self",
",",
"ids",
")",
":",
"predicate",
"=",
"{",
"\"_id\"",
":",
"{",
"\"$in\"",
":",
"[",
"ObjectId",
"(",
"id",
")",
"for",
"id",
"in",
"ids",
"]",
"}",
"}",
"set",
"=",
"{",
"\"$set\"",
":",
"{",
"\"inProcess\"",
":",
"True",
"}",
"}",
"yield",
"self",
".",
"revisions",
".",
"collection",
".",
"update",
"(",
"predicate",
",",
"set",
",",
"multi",
"=",
"True",
")"
] |
Set all revisions found to in process, so that other threads will not pick them up.
:param list ids:
|
[
"Set",
"all",
"revisions",
"found",
"to",
"in",
"process",
"so",
"that",
"other",
"threads",
"will",
"not",
"pick",
"them",
"up",
"."
] |
2a14fe79724c38fe9a1b20f7b8f518f8c6d50df1
|
https://github.com/urbn/Caesium/blob/2a14fe79724c38fe9a1b20f7b8f518f8c6d50df1/caesium/document.py#L48-L63
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.