partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
Rule.execute_actions
|
Iterates over the actions and executes them in order.
|
hook/model.py
|
def execute_actions(self, cwd):
"""Iterates over the actions and executes them in order."""
self._execute_globals(cwd)
for action in self.actions:
logger.info("executing {}".format(action))
p = subprocess.Popen(action, shell=True, cwd=cwd)
p.wait()
|
def execute_actions(self, cwd):
"""Iterates over the actions and executes them in order."""
self._execute_globals(cwd)
for action in self.actions:
logger.info("executing {}".format(action))
p = subprocess.Popen(action, shell=True, cwd=cwd)
p.wait()
|
[
"Iterates",
"over",
"the",
"actions",
"and",
"executes",
"them",
"in",
"order",
"."
] |
ssherar/hook
|
python
|
https://github.com/ssherar/hook/blob/54160df554d8b2ed65d762168e5808487e873ed9/hook/model.py#L57-L63
|
[
"def",
"execute_actions",
"(",
"self",
",",
"cwd",
")",
":",
"self",
".",
"_execute_globals",
"(",
"cwd",
")",
"for",
"action",
"in",
"self",
".",
"actions",
":",
"logger",
".",
"info",
"(",
"\"executing {}\"",
".",
"format",
"(",
"action",
")",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"action",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"cwd",
")",
"p",
".",
"wait",
"(",
")"
] |
54160df554d8b2ed65d762168e5808487e873ed9
|
test
|
CommandSet.from_yaml
|
Creates a new instance of a rule by merging two dictionaries.
This allows for independant configuration files to be merged
into the defaults.
|
hook/model.py
|
def from_yaml(cls, defaults, **kwargs):
"""Creates a new instance of a rule by merging two dictionaries.
This allows for independant configuration files to be merged
into the defaults."""
# TODO: I hate myself for this. Fix it later mmkay?
if "token" not in defaults:
kwargs["token"] = None
defaults = copy.deepcopy(defaults)
return cls(
defaults=defaults,
token=kwargs.pop("token"),
directory=kwargs.pop("directory"),
**kwargs
)
|
def from_yaml(cls, defaults, **kwargs):
"""Creates a new instance of a rule by merging two dictionaries.
This allows for independant configuration files to be merged
into the defaults."""
# TODO: I hate myself for this. Fix it later mmkay?
if "token" not in defaults:
kwargs["token"] = None
defaults = copy.deepcopy(defaults)
return cls(
defaults=defaults,
token=kwargs.pop("token"),
directory=kwargs.pop("directory"),
**kwargs
)
|
[
"Creates",
"a",
"new",
"instance",
"of",
"a",
"rule",
"by",
"merging",
"two",
"dictionaries",
"."
] |
ssherar/hook
|
python
|
https://github.com/ssherar/hook/blob/54160df554d8b2ed65d762168e5808487e873ed9/hook/model.py#L76-L91
|
[
"def",
"from_yaml",
"(",
"cls",
",",
"defaults",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: I hate myself for this. Fix it later mmkay?",
"if",
"\"token\"",
"not",
"in",
"defaults",
":",
"kwargs",
"[",
"\"token\"",
"]",
"=",
"None",
"defaults",
"=",
"copy",
".",
"deepcopy",
"(",
"defaults",
")",
"return",
"cls",
"(",
"defaults",
"=",
"defaults",
",",
"token",
"=",
"kwargs",
".",
"pop",
"(",
"\"token\"",
")",
",",
"directory",
"=",
"kwargs",
".",
"pop",
"(",
"\"directory\"",
")",
",",
"*",
"*",
"kwargs",
")"
] |
54160df554d8b2ed65d762168e5808487e873ed9
|
test
|
parse_address
|
:param formatted_address: A string like "email@address.com" or "My Email <email@address.com>"
:return: Tuple: (address, name)
|
littlefish/lfsmailer.py
|
def parse_address(formatted_address):
"""
:param formatted_address: A string like "email@address.com" or "My Email <email@address.com>"
:return: Tuple: (address, name)
"""
if email_regex.match(formatted_address):
# Just a raw address
return (formatted_address, None)
match = formatted_address_regex.match(formatted_address)
if match:
(name, email) = match.group(1, 2)
return email.strip(), name.strip()
raise ValueError('"{}" is not a valid formatted address'.format(formatted_address))
|
def parse_address(formatted_address):
"""
:param formatted_address: A string like "email@address.com" or "My Email <email@address.com>"
:return: Tuple: (address, name)
"""
if email_regex.match(formatted_address):
# Just a raw address
return (formatted_address, None)
match = formatted_address_regex.match(formatted_address)
if match:
(name, email) = match.group(1, 2)
return email.strip(), name.strip()
raise ValueError('"{}" is not a valid formatted address'.format(formatted_address))
|
[
":",
"param",
"formatted_address",
":",
"A",
"string",
"like",
"email"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/lfsmailer.py#L69-L85
|
[
"def",
"parse_address",
"(",
"formatted_address",
")",
":",
"if",
"email_regex",
".",
"match",
"(",
"formatted_address",
")",
":",
"# Just a raw address",
"return",
"(",
"formatted_address",
",",
"None",
")",
"match",
"=",
"formatted_address_regex",
".",
"match",
"(",
"formatted_address",
")",
"if",
"match",
":",
"(",
"name",
",",
"email",
")",
"=",
"match",
".",
"group",
"(",
"1",
",",
"2",
")",
"return",
"email",
".",
"strip",
"(",
")",
",",
"name",
".",
"strip",
"(",
")",
"raise",
"ValueError",
"(",
"'\"{}\" is not a valid formatted address'",
".",
"format",
"(",
"formatted_address",
")",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
send_mail
|
:param recipient_list: List of recipients i.e. ['testing@fig14.com', 'Stephen Brown <steve@fig14.com>']
:param subject: The subject
:param body: The email body
:param html: Is this a html email? Defaults to False
:param from_address: From email address or name and address i.e. 'Test System <errors@test.com>
:return:
|
littlefish/lfsmailer.py
|
def send_mail(recipient_list, subject, body, html=False, from_address=None):
"""
:param recipient_list: List of recipients i.e. ['testing@fig14.com', 'Stephen Brown <steve@fig14.com>']
:param subject: The subject
:param body: The email body
:param html: Is this a html email? Defaults to False
:param from_address: From email address or name and address i.e. 'Test System <errors@test.com>
:return:
"""
if not _configured:
raise Exception('LFS Mailer hasn\'t been configured')
if from_address is None:
from_address = default_email_from
mime_type = 'html' if html else 'plain'
log.debug('Sending {} mail to {}: {}'.format(mime_type, ', '.join(recipient_list), subject))
if dump_email_body:
log.info(body)
s = smtplib.SMTP(host, port)
if use_tls:
s.ehlo()
s.starttls()
s.ehlo()
if username:
s.login(username, password)
if email_to_override:
subject = '[to %s] %s' % (', '.join(recipient_list), subject)
recipient_list = [email_to_override]
log.info('Using email override: %s' % ', '.join(recipient_list))
msg = MIMEText(body, mime_type, 'utf-8')
msg['To'] = ', '.join(recipient_list)
msg['Subject'] = subject
msg['From'] = from_address
msg['Date'] = email.utils.formatdate()
s.sendmail(from_address, recipient_list, msg.as_string())
s.quit()
|
def send_mail(recipient_list, subject, body, html=False, from_address=None):
"""
:param recipient_list: List of recipients i.e. ['testing@fig14.com', 'Stephen Brown <steve@fig14.com>']
:param subject: The subject
:param body: The email body
:param html: Is this a html email? Defaults to False
:param from_address: From email address or name and address i.e. 'Test System <errors@test.com>
:return:
"""
if not _configured:
raise Exception('LFS Mailer hasn\'t been configured')
if from_address is None:
from_address = default_email_from
mime_type = 'html' if html else 'plain'
log.debug('Sending {} mail to {}: {}'.format(mime_type, ', '.join(recipient_list), subject))
if dump_email_body:
log.info(body)
s = smtplib.SMTP(host, port)
if use_tls:
s.ehlo()
s.starttls()
s.ehlo()
if username:
s.login(username, password)
if email_to_override:
subject = '[to %s] %s' % (', '.join(recipient_list), subject)
recipient_list = [email_to_override]
log.info('Using email override: %s' % ', '.join(recipient_list))
msg = MIMEText(body, mime_type, 'utf-8')
msg['To'] = ', '.join(recipient_list)
msg['Subject'] = subject
msg['From'] = from_address
msg['Date'] = email.utils.formatdate()
s.sendmail(from_address, recipient_list, msg.as_string())
s.quit()
|
[
":",
"param",
"recipient_list",
":",
"List",
"of",
"recipients",
"i",
".",
"e",
".",
"[",
"testing"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/lfsmailer.py#L108-L150
|
[
"def",
"send_mail",
"(",
"recipient_list",
",",
"subject",
",",
"body",
",",
"html",
"=",
"False",
",",
"from_address",
"=",
"None",
")",
":",
"if",
"not",
"_configured",
":",
"raise",
"Exception",
"(",
"'LFS Mailer hasn\\'t been configured'",
")",
"if",
"from_address",
"is",
"None",
":",
"from_address",
"=",
"default_email_from",
"mime_type",
"=",
"'html'",
"if",
"html",
"else",
"'plain'",
"log",
".",
"debug",
"(",
"'Sending {} mail to {}: {}'",
".",
"format",
"(",
"mime_type",
",",
"', '",
".",
"join",
"(",
"recipient_list",
")",
",",
"subject",
")",
")",
"if",
"dump_email_body",
":",
"log",
".",
"info",
"(",
"body",
")",
"s",
"=",
"smtplib",
".",
"SMTP",
"(",
"host",
",",
"port",
")",
"if",
"use_tls",
":",
"s",
".",
"ehlo",
"(",
")",
"s",
".",
"starttls",
"(",
")",
"s",
".",
"ehlo",
"(",
")",
"if",
"username",
":",
"s",
".",
"login",
"(",
"username",
",",
"password",
")",
"if",
"email_to_override",
":",
"subject",
"=",
"'[to %s] %s'",
"%",
"(",
"', '",
".",
"join",
"(",
"recipient_list",
")",
",",
"subject",
")",
"recipient_list",
"=",
"[",
"email_to_override",
"]",
"log",
".",
"info",
"(",
"'Using email override: %s'",
"%",
"', '",
".",
"join",
"(",
"recipient_list",
")",
")",
"msg",
"=",
"MIMEText",
"(",
"body",
",",
"mime_type",
",",
"'utf-8'",
")",
"msg",
"[",
"'To'",
"]",
"=",
"', '",
".",
"join",
"(",
"recipient_list",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"subject",
"msg",
"[",
"'From'",
"]",
"=",
"from_address",
"msg",
"[",
"'Date'",
"]",
"=",
"email",
".",
"utils",
".",
"formatdate",
"(",
")",
"s",
".",
"sendmail",
"(",
"from_address",
",",
"recipient_list",
",",
"msg",
".",
"as_string",
"(",
")",
")",
"s",
".",
"quit",
"(",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
LfsSmtpHandler.add_details
|
Add extra details to the message. Separate so that it can be overridden
|
littlefish/lfsmailer.py
|
def add_details(self, message):
"""
Add extra details to the message. Separate so that it can be overridden
"""
msg = message
# Try to append Flask request details
try:
from flask import request
url = request.url
method = request.method
endpoint = request.endpoint
# Obscure password field and prettify a little bit
form_dict = dict(request.form)
for key in form_dict:
if key.lower() in _error_reporting_obscured_fields:
form_dict[key] = '******'
elif len(form_dict[key]) == 1:
form_dict[key] = form_dict[key][0]
form = pprint.pformat(form_dict).replace('\n', '\n ')
msg = '%s\nRequest:\n\nurl: %s\nmethod: %s\nendpoint: %s\nform: %s\n' % \
(msg, url, method, endpoint, form)
except Exception:
traceback.print_exc()
# Try to append the session
try:
from flask import session
from flask.json import JSONEncoder
session_str = json.dumps(
dict(**session),
indent=2,
cls=JSONEncoder
)
msg = '%s\nSession:\n\n%s\n' % (msg, session_str)
except Exception:
traceback.print_exc()
return msg
|
def add_details(self, message):
"""
Add extra details to the message. Separate so that it can be overridden
"""
msg = message
# Try to append Flask request details
try:
from flask import request
url = request.url
method = request.method
endpoint = request.endpoint
# Obscure password field and prettify a little bit
form_dict = dict(request.form)
for key in form_dict:
if key.lower() in _error_reporting_obscured_fields:
form_dict[key] = '******'
elif len(form_dict[key]) == 1:
form_dict[key] = form_dict[key][0]
form = pprint.pformat(form_dict).replace('\n', '\n ')
msg = '%s\nRequest:\n\nurl: %s\nmethod: %s\nendpoint: %s\nform: %s\n' % \
(msg, url, method, endpoint, form)
except Exception:
traceback.print_exc()
# Try to append the session
try:
from flask import session
from flask.json import JSONEncoder
session_str = json.dumps(
dict(**session),
indent=2,
cls=JSONEncoder
)
msg = '%s\nSession:\n\n%s\n' % (msg, session_str)
except Exception:
traceback.print_exc()
return msg
|
[
"Add",
"extra",
"details",
"to",
"the",
"message",
".",
"Separate",
"so",
"that",
"it",
"can",
"be",
"overridden"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/lfsmailer.py#L196-L236
|
[
"def",
"add_details",
"(",
"self",
",",
"message",
")",
":",
"msg",
"=",
"message",
"# Try to append Flask request details",
"try",
":",
"from",
"flask",
"import",
"request",
"url",
"=",
"request",
".",
"url",
"method",
"=",
"request",
".",
"method",
"endpoint",
"=",
"request",
".",
"endpoint",
"# Obscure password field and prettify a little bit",
"form_dict",
"=",
"dict",
"(",
"request",
".",
"form",
")",
"for",
"key",
"in",
"form_dict",
":",
"if",
"key",
".",
"lower",
"(",
")",
"in",
"_error_reporting_obscured_fields",
":",
"form_dict",
"[",
"key",
"]",
"=",
"'******'",
"elif",
"len",
"(",
"form_dict",
"[",
"key",
"]",
")",
"==",
"1",
":",
"form_dict",
"[",
"key",
"]",
"=",
"form_dict",
"[",
"key",
"]",
"[",
"0",
"]",
"form",
"=",
"pprint",
".",
"pformat",
"(",
"form_dict",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n '",
")",
"msg",
"=",
"'%s\\nRequest:\\n\\nurl: %s\\nmethod: %s\\nendpoint: %s\\nform: %s\\n'",
"%",
"(",
"msg",
",",
"url",
",",
"method",
",",
"endpoint",
",",
"form",
")",
"except",
"Exception",
":",
"traceback",
".",
"print_exc",
"(",
")",
"# Try to append the session",
"try",
":",
"from",
"flask",
"import",
"session",
"from",
"flask",
".",
"json",
"import",
"JSONEncoder",
"session_str",
"=",
"json",
".",
"dumps",
"(",
"dict",
"(",
"*",
"*",
"session",
")",
",",
"indent",
"=",
"2",
",",
"cls",
"=",
"JSONEncoder",
")",
"msg",
"=",
"'%s\\nSession:\\n\\n%s\\n'",
"%",
"(",
"msg",
",",
"session_str",
")",
"except",
"Exception",
":",
"traceback",
".",
"print_exc",
"(",
")",
"return",
"msg"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
LfsSmtpHandler.emit
|
Emit a record.
Format the record and send it to the specified addressees.
|
littlefish/lfsmailer.py
|
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
# First, remove all records from the rate limiter list that are over a minute old
now = timetool.unix_time()
one_minute_ago = now - 60
new_rate_limiter = [x for x in self.rate_limiter if x > one_minute_ago]
log.debug('Rate limiter %s -> %s' % (len(self.rate_limiter), len(new_rate_limiter)))
self.rate_limiter = new_rate_limiter
# Now, get the number of emails sent in the last minute. If it's less than the threshold, add another
# entry to the rate limiter list
recent_sends = len(self.rate_limiter)
send_email = recent_sends < self.max_sends_per_minute
if send_email:
self.rate_limiter.append(now)
msg = self.format(record)
msg = self.add_details(msg)
# Finally send the message!
if send_email:
if DEBUG_ERROR_EMAIL_SENDING:
log.info('@@@> ! Sending error email to {} !'.format(self.toaddrs))
send_text_mail(self.toaddrs, self.subject, msg, self.fromaddr)
else:
log.info('!! WARNING: Not sending email as too many emails have been sent in the past minute !!')
log.info(msg)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
self.handleError(record)
|
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
# First, remove all records from the rate limiter list that are over a minute old
now = timetool.unix_time()
one_minute_ago = now - 60
new_rate_limiter = [x for x in self.rate_limiter if x > one_minute_ago]
log.debug('Rate limiter %s -> %s' % (len(self.rate_limiter), len(new_rate_limiter)))
self.rate_limiter = new_rate_limiter
# Now, get the number of emails sent in the last minute. If it's less than the threshold, add another
# entry to the rate limiter list
recent_sends = len(self.rate_limiter)
send_email = recent_sends < self.max_sends_per_minute
if send_email:
self.rate_limiter.append(now)
msg = self.format(record)
msg = self.add_details(msg)
# Finally send the message!
if send_email:
if DEBUG_ERROR_EMAIL_SENDING:
log.info('@@@> ! Sending error email to {} !'.format(self.toaddrs))
send_text_mail(self.toaddrs, self.subject, msg, self.fromaddr)
else:
log.info('!! WARNING: Not sending email as too many emails have been sent in the past minute !!')
log.info(msg)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
self.handleError(record)
|
[
"Emit",
"a",
"record",
"."
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/lfsmailer.py#L238-L274
|
[
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"# First, remove all records from the rate limiter list that are over a minute old",
"now",
"=",
"timetool",
".",
"unix_time",
"(",
")",
"one_minute_ago",
"=",
"now",
"-",
"60",
"new_rate_limiter",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"rate_limiter",
"if",
"x",
">",
"one_minute_ago",
"]",
"log",
".",
"debug",
"(",
"'Rate limiter %s -> %s'",
"%",
"(",
"len",
"(",
"self",
".",
"rate_limiter",
")",
",",
"len",
"(",
"new_rate_limiter",
")",
")",
")",
"self",
".",
"rate_limiter",
"=",
"new_rate_limiter",
"# Now, get the number of emails sent in the last minute. If it's less than the threshold, add another",
"# entry to the rate limiter list",
"recent_sends",
"=",
"len",
"(",
"self",
".",
"rate_limiter",
")",
"send_email",
"=",
"recent_sends",
"<",
"self",
".",
"max_sends_per_minute",
"if",
"send_email",
":",
"self",
".",
"rate_limiter",
".",
"append",
"(",
"now",
")",
"msg",
"=",
"self",
".",
"format",
"(",
"record",
")",
"msg",
"=",
"self",
".",
"add_details",
"(",
"msg",
")",
"# Finally send the message!",
"if",
"send_email",
":",
"if",
"DEBUG_ERROR_EMAIL_SENDING",
":",
"log",
".",
"info",
"(",
"'@@@> ! Sending error email to {} !'",
".",
"format",
"(",
"self",
".",
"toaddrs",
")",
")",
"send_text_mail",
"(",
"self",
".",
"toaddrs",
",",
"self",
".",
"subject",
",",
"msg",
",",
"self",
".",
"fromaddr",
")",
"else",
":",
"log",
".",
"info",
"(",
"'!! WARNING: Not sending email as too many emails have been sent in the past minute !!'",
")",
"log",
".",
"info",
"(",
"msg",
")",
"except",
"(",
"KeyboardInterrupt",
",",
"SystemExit",
")",
":",
"raise",
"except",
"Exception",
":",
"self",
".",
"handleError",
"(",
"record",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
RenditionAwareStructBlock.get_context
|
Ensure `image_rendition` is added to the global context.
|
streamfield_tools/blocks/struct_block.py
|
def get_context(self, value):
"""Ensure `image_rendition` is added to the global context."""
context = super(RenditionAwareStructBlock, self).get_context(value)
context['image_rendition'] = self.rendition.\
image_rendition or 'original'
return context
|
def get_context(self, value):
"""Ensure `image_rendition` is added to the global context."""
context = super(RenditionAwareStructBlock, self).get_context(value)
context['image_rendition'] = self.rendition.\
image_rendition or 'original'
return context
|
[
"Ensure",
"image_rendition",
"is",
"added",
"to",
"the",
"global",
"context",
"."
] |
WGBH/wagtail-streamfieldtools
|
python
|
https://github.com/WGBH/wagtail-streamfieldtools/blob/192f86845532742b0b7d432bef3987357833b8ed/streamfield_tools/blocks/struct_block.py#L118-L123
|
[
"def",
"get_context",
"(",
"self",
",",
"value",
")",
":",
"context",
"=",
"super",
"(",
"RenditionAwareStructBlock",
",",
"self",
")",
".",
"get_context",
"(",
"value",
")",
"context",
"[",
"'image_rendition'",
"]",
"=",
"self",
".",
"rendition",
".",
"image_rendition",
"or",
"'original'",
"return",
"context"
] |
192f86845532742b0b7d432bef3987357833b8ed
|
test
|
AttackProtect.log_attempt
|
Log an attempt against key, incrementing the number of attempts for that key and potentially adding a lock to
the lock table
|
littlefish/attackprotect.py
|
def log_attempt(self, key):
"""
Log an attempt against key, incrementing the number of attempts for that key and potentially adding a lock to
the lock table
"""
with self.lock:
if key not in self.attempts:
self.attempts[key] = 1
else:
self.attempts[key] += 1
if self.attempts[key] >= self.max_attempts:
log.info('Account %s locked due to too many login attempts' % key)
# lock account
self.locks[key] = datetime.datetime.utcnow() + datetime.timedelta(seconds=self.lock_duration)
|
def log_attempt(self, key):
"""
Log an attempt against key, incrementing the number of attempts for that key and potentially adding a lock to
the lock table
"""
with self.lock:
if key not in self.attempts:
self.attempts[key] = 1
else:
self.attempts[key] += 1
if self.attempts[key] >= self.max_attempts:
log.info('Account %s locked due to too many login attempts' % key)
# lock account
self.locks[key] = datetime.datetime.utcnow() + datetime.timedelta(seconds=self.lock_duration)
|
[
"Log",
"an",
"attempt",
"against",
"key",
"incrementing",
"the",
"number",
"of",
"attempts",
"for",
"that",
"key",
"and",
"potentially",
"adding",
"a",
"lock",
"to",
"the",
"lock",
"table"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/attackprotect.py#L38-L52
|
[
"def",
"log_attempt",
"(",
"self",
",",
"key",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"key",
"not",
"in",
"self",
".",
"attempts",
":",
"self",
".",
"attempts",
"[",
"key",
"]",
"=",
"1",
"else",
":",
"self",
".",
"attempts",
"[",
"key",
"]",
"+=",
"1",
"if",
"self",
".",
"attempts",
"[",
"key",
"]",
">=",
"self",
".",
"max_attempts",
":",
"log",
".",
"info",
"(",
"'Account %s locked due to too many login attempts'",
"%",
"key",
")",
"# lock account",
"self",
".",
"locks",
"[",
"key",
"]",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"lock_duration",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
AttackProtect.service
|
Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds.
|
littlefish/attackprotect.py
|
def service(self):
"""
Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds.
"""
with self.lock:
# Decrement / remove all attempts
for key in list(self.attempts.keys()):
log.debug('Decrementing count for %s' % key)
if key in self.attempts:
if self.attempts[key] <= 1:
del self.attempts[key]
else:
self.attempts[key] -= 1
# Remove expired locks
now = datetime.datetime.utcnow()
for key in list(self.locks.keys()):
if key in self.locks and self.locks[key] < now:
log.info('Expiring login lock for %s' % key)
del self.locks[key]
|
def service(self):
"""
Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds.
"""
with self.lock:
# Decrement / remove all attempts
for key in list(self.attempts.keys()):
log.debug('Decrementing count for %s' % key)
if key in self.attempts:
if self.attempts[key] <= 1:
del self.attempts[key]
else:
self.attempts[key] -= 1
# Remove expired locks
now = datetime.datetime.utcnow()
for key in list(self.locks.keys()):
if key in self.locks and self.locks[key] < now:
log.info('Expiring login lock for %s' % key)
del self.locks[key]
|
[
"Decrease",
"the",
"countdowns",
"and",
"remove",
"any",
"expired",
"locks",
".",
"Should",
"be",
"called",
"once",
"every",
"<decrease_every",
">",
"seconds",
"."
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/attackprotect.py#L61-L80
|
[
"def",
"service",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"# Decrement / remove all attempts",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"attempts",
".",
"keys",
"(",
")",
")",
":",
"log",
".",
"debug",
"(",
"'Decrementing count for %s'",
"%",
"key",
")",
"if",
"key",
"in",
"self",
".",
"attempts",
":",
"if",
"self",
".",
"attempts",
"[",
"key",
"]",
"<=",
"1",
":",
"del",
"self",
".",
"attempts",
"[",
"key",
"]",
"else",
":",
"self",
".",
"attempts",
"[",
"key",
"]",
"-=",
"1",
"# Remove expired locks",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"locks",
".",
"keys",
"(",
")",
")",
":",
"if",
"key",
"in",
"self",
".",
"locks",
"and",
"self",
".",
"locks",
"[",
"key",
"]",
"<",
"now",
":",
"log",
".",
"info",
"(",
"'Expiring login lock for %s'",
"%",
"key",
")",
"del",
"self",
".",
"locks",
"[",
"key",
"]"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
Music2Storage.add_to_queue
|
Adds an URL to the download queue.
:param str url: URL to the music service track
|
music2storage/__init__.py
|
def add_to_queue(self, url):
"""
Adds an URL to the download queue.
:param str url: URL to the music service track
"""
if self.connection_handler.current_music is None:
log.error('Music service is not initialized. URL was not added to queue.')
elif self.connection_handler.current_storage is None:
log.error('Drive service is not initialized. URL was not added to queue.')
else:
self.queues['download'].put(url)
|
def add_to_queue(self, url):
"""
Adds an URL to the download queue.
:param str url: URL to the music service track
"""
if self.connection_handler.current_music is None:
log.error('Music service is not initialized. URL was not added to queue.')
elif self.connection_handler.current_storage is None:
log.error('Drive service is not initialized. URL was not added to queue.')
else:
self.queues['download'].put(url)
|
[
"Adds",
"an",
"URL",
"to",
"the",
"download",
"queue",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/__init__.py#L36-L48
|
[
"def",
"add_to_queue",
"(",
"self",
",",
"url",
")",
":",
"if",
"self",
".",
"connection_handler",
".",
"current_music",
"is",
"None",
":",
"log",
".",
"error",
"(",
"'Music service is not initialized. URL was not added to queue.'",
")",
"elif",
"self",
".",
"connection_handler",
".",
"current_storage",
"is",
"None",
":",
"log",
".",
"error",
"(",
"'Drive service is not initialized. URL was not added to queue.'",
")",
"else",
":",
"self",
".",
"queues",
"[",
"'download'",
"]",
".",
"put",
"(",
"url",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
Music2Storage.use_music_service
|
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
|
music2storage/__init__.py
|
def use_music_service(self, service_name, api_key=None):
"""
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
"""
self.connection_handler.use_music_service(service_name, api_key=api_key)
|
def use_music_service(self, service_name, api_key=None):
"""
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
"""
self.connection_handler.use_music_service(service_name, api_key=api_key)
|
[
"Sets",
"the",
"current",
"music",
"service",
"to",
"service_name",
".",
":",
"param",
"str",
"service_name",
":",
"Name",
"of",
"the",
"music",
"service",
":",
"param",
"str",
"api_key",
":",
"Optional",
"API",
"key",
"if",
"necessary"
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/__init__.py#L50-L58
|
[
"def",
"use_music_service",
"(",
"self",
",",
"service_name",
",",
"api_key",
"=",
"None",
")",
":",
"self",
".",
"connection_handler",
".",
"use_music_service",
"(",
"service_name",
",",
"api_key",
"=",
"api_key",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
Music2Storage.use_storage_service
|
Sets the current storage service to service_name and attempts to connect to it.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only)
|
music2storage/__init__.py
|
def use_storage_service(self, service_name, custom_path=None):
"""
Sets the current storage service to service_name and attempts to connect to it.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only)
"""
self.connection_handler.use_storage_service(service_name, custom_path=custom_path)
|
def use_storage_service(self, service_name, custom_path=None):
"""
Sets the current storage service to service_name and attempts to connect to it.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only)
"""
self.connection_handler.use_storage_service(service_name, custom_path=custom_path)
|
[
"Sets",
"the",
"current",
"storage",
"service",
"to",
"service_name",
"and",
"attempts",
"to",
"connect",
"to",
"it",
".",
":",
"param",
"str",
"service_name",
":",
"Name",
"of",
"the",
"storage",
"service",
":",
"param",
"str",
"custom_path",
":",
"Custom",
"path",
"where",
"to",
"download",
"tracks",
"for",
"local",
"storage",
"(",
"optional",
"and",
"must",
"already",
"exist",
"use",
"absolute",
"paths",
"only",
")"
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/__init__.py#L60-L68
|
[
"def",
"use_storage_service",
"(",
"self",
",",
"service_name",
",",
"custom_path",
"=",
"None",
")",
":",
"self",
".",
"connection_handler",
".",
"use_storage_service",
"(",
"service_name",
",",
"custom_path",
"=",
"custom_path",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
Music2Storage.start_workers
|
Creates and starts the workers, as well as attaching a handler to terminate them gracefully when a SIGINT signal is received.
:param int workers_per_task: Number of workers to create for each task in the pipeline
|
music2storage/__init__.py
|
def start_workers(self, workers_per_task=1):
"""
Creates and starts the workers, as well as attaching a handler to terminate them gracefully when a SIGINT signal is received.
:param int workers_per_task: Number of workers to create for each task in the pipeline
"""
if not self.workers:
for _ in range(workers_per_task):
self.workers.append(Worker(self._download, self.queues['download'], self.queues['convert'], self.stopper))
self.workers.append(Worker(self._convert, self.queues['convert'], self.queues['upload'], self.stopper))
self.workers.append(Worker(self._upload, self.queues['upload'], self.queues['delete'], self.stopper))
self.workers.append(Worker(self._delete, self.queues['delete'], self.queues['done'], self.stopper))
self.signal_handler = SignalHandler(self.workers, self.stopper)
signal.signal(signal.SIGINT, self.signal_handler)
for worker in self.workers:
worker.start()
|
def start_workers(self, workers_per_task=1):
"""
Creates and starts the workers, as well as attaching a handler to terminate them gracefully when a SIGINT signal is received.
:param int workers_per_task: Number of workers to create for each task in the pipeline
"""
if not self.workers:
for _ in range(workers_per_task):
self.workers.append(Worker(self._download, self.queues['download'], self.queues['convert'], self.stopper))
self.workers.append(Worker(self._convert, self.queues['convert'], self.queues['upload'], self.stopper))
self.workers.append(Worker(self._upload, self.queues['upload'], self.queues['delete'], self.stopper))
self.workers.append(Worker(self._delete, self.queues['delete'], self.queues['done'], self.stopper))
self.signal_handler = SignalHandler(self.workers, self.stopper)
signal.signal(signal.SIGINT, self.signal_handler)
for worker in self.workers:
worker.start()
|
[
"Creates",
"and",
"starts",
"the",
"workers",
"as",
"well",
"as",
"attaching",
"a",
"handler",
"to",
"terminate",
"them",
"gracefully",
"when",
"a",
"SIGINT",
"signal",
"is",
"received",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/__init__.py#L70-L88
|
[
"def",
"start_workers",
"(",
"self",
",",
"workers_per_task",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"workers",
":",
"for",
"_",
"in",
"range",
"(",
"workers_per_task",
")",
":",
"self",
".",
"workers",
".",
"append",
"(",
"Worker",
"(",
"self",
".",
"_download",
",",
"self",
".",
"queues",
"[",
"'download'",
"]",
",",
"self",
".",
"queues",
"[",
"'convert'",
"]",
",",
"self",
".",
"stopper",
")",
")",
"self",
".",
"workers",
".",
"append",
"(",
"Worker",
"(",
"self",
".",
"_convert",
",",
"self",
".",
"queues",
"[",
"'convert'",
"]",
",",
"self",
".",
"queues",
"[",
"'upload'",
"]",
",",
"self",
".",
"stopper",
")",
")",
"self",
".",
"workers",
".",
"append",
"(",
"Worker",
"(",
"self",
".",
"_upload",
",",
"self",
".",
"queues",
"[",
"'upload'",
"]",
",",
"self",
".",
"queues",
"[",
"'delete'",
"]",
",",
"self",
".",
"stopper",
")",
")",
"self",
".",
"workers",
".",
"append",
"(",
"Worker",
"(",
"self",
".",
"_delete",
",",
"self",
".",
"queues",
"[",
"'delete'",
"]",
",",
"self",
".",
"queues",
"[",
"'done'",
"]",
",",
"self",
".",
"stopper",
")",
")",
"self",
".",
"signal_handler",
"=",
"SignalHandler",
"(",
"self",
".",
"workers",
",",
"self",
".",
"stopper",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"signal_handler",
")",
"for",
"worker",
"in",
"self",
".",
"workers",
":",
"worker",
".",
"start",
"(",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
Client.set
|
Add or update a key, value pair to the database
|
kvstore.py
|
def set(self, k, v):
"""Add or update a key, value pair to the database"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
r = requests.put(url, data=str(v))
if r.status_code != 200 or r.json() is not True:
raise KVStoreError('PUT returned {}'.format(r.status_code))
|
def set(self, k, v):
"""Add or update a key, value pair to the database"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
r = requests.put(url, data=str(v))
if r.status_code != 200 or r.json() is not True:
raise KVStoreError('PUT returned {}'.format(r.status_code))
|
[
"Add",
"or",
"update",
"a",
"key",
"value",
"pair",
"to",
"the",
"database"
] |
bigdatacesga/kvstore
|
python
|
https://github.com/bigdatacesga/kvstore/blob/8ad2222b39d47defc8ad30deda3da06798e2a9a4/kvstore.py#L31-L37
|
[
"def",
"set",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"k",
"=",
"k",
".",
"lstrip",
"(",
"'/'",
")",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"endpoint",
",",
"k",
")",
"r",
"=",
"requests",
".",
"put",
"(",
"url",
",",
"data",
"=",
"str",
"(",
"v",
")",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
"or",
"r",
".",
"json",
"(",
")",
"is",
"not",
"True",
":",
"raise",
"KVStoreError",
"(",
"'PUT returned {}'",
".",
"format",
"(",
"r",
".",
"status_code",
")",
")"
] |
8ad2222b39d47defc8ad30deda3da06798e2a9a4
|
test
|
Client.get
|
Get the value of a given key
|
kvstore.py
|
def get(self, k, wait=False, wait_index=False, timeout='5m'):
"""Get the value of a given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if wait:
params['index'] = wait_index
params['wait'] = timeout
r = requests.get(url, params=params)
if r.status_code == 404:
raise KeyDoesNotExist("Key " + k + " does not exist")
if r.status_code != 200:
raise KVStoreError('GET returned {}'.format(r.status_code))
try:
return base64.b64decode(r.json()[0]['Value'])
except TypeError as e:
# Value was empty and wild None appeared
return ""
|
def get(self, k, wait=False, wait_index=False, timeout='5m'):
"""Get the value of a given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if wait:
params['index'] = wait_index
params['wait'] = timeout
r = requests.get(url, params=params)
if r.status_code == 404:
raise KeyDoesNotExist("Key " + k + " does not exist")
if r.status_code != 200:
raise KVStoreError('GET returned {}'.format(r.status_code))
try:
return base64.b64decode(r.json()[0]['Value'])
except TypeError as e:
# Value was empty and wild None appeared
return ""
|
[
"Get",
"the",
"value",
"of",
"a",
"given",
"key"
] |
bigdatacesga/kvstore
|
python
|
https://github.com/bigdatacesga/kvstore/blob/8ad2222b39d47defc8ad30deda3da06798e2a9a4/kvstore.py#L39-L57
|
[
"def",
"get",
"(",
"self",
",",
"k",
",",
"wait",
"=",
"False",
",",
"wait_index",
"=",
"False",
",",
"timeout",
"=",
"'5m'",
")",
":",
"k",
"=",
"k",
".",
"lstrip",
"(",
"'/'",
")",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"endpoint",
",",
"k",
")",
"params",
"=",
"{",
"}",
"if",
"wait",
":",
"params",
"[",
"'index'",
"]",
"=",
"wait_index",
"params",
"[",
"'wait'",
"]",
"=",
"timeout",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"if",
"r",
".",
"status_code",
"==",
"404",
":",
"raise",
"KeyDoesNotExist",
"(",
"\"Key \"",
"+",
"k",
"+",
"\" does not exist\"",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"raise",
"KVStoreError",
"(",
"'GET returned {}'",
".",
"format",
"(",
"r",
".",
"status_code",
")",
")",
"try",
":",
"return",
"base64",
".",
"b64decode",
"(",
"r",
".",
"json",
"(",
")",
"[",
"0",
"]",
"[",
"'Value'",
"]",
")",
"except",
"TypeError",
"as",
"e",
":",
"# Value was empty and wild None appeared",
"return",
"\"\""
] |
8ad2222b39d47defc8ad30deda3da06798e2a9a4
|
test
|
Client.recurse
|
Recursively get the tree below the given key
|
kvstore.py
|
def recurse(self, k, wait=False, wait_index=None, timeout='5m'):
"""Recursively get the tree below the given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
params['recurse'] = 'true'
if wait:
params['wait'] = timeout
if not wait_index:
params['index'] = self.index(k, recursive=True)
else:
params['index'] = wait_index
r = requests.get(url, params=params)
if r.status_code == 404:
raise KeyDoesNotExist("Key " + k + " does not exist")
if r.status_code != 200:
raise KVStoreError('GET returned {}'.format(r.status_code))
entries = {}
for e in r.json():
if e['Value']:
entries[e['Key']] = base64.b64decode(e['Value'])
else:
entries[e['Key']] = ''
return entries
|
def recurse(self, k, wait=False, wait_index=None, timeout='5m'):
"""Recursively get the tree below the given key"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
params['recurse'] = 'true'
if wait:
params['wait'] = timeout
if not wait_index:
params['index'] = self.index(k, recursive=True)
else:
params['index'] = wait_index
r = requests.get(url, params=params)
if r.status_code == 404:
raise KeyDoesNotExist("Key " + k + " does not exist")
if r.status_code != 200:
raise KVStoreError('GET returned {}'.format(r.status_code))
entries = {}
for e in r.json():
if e['Value']:
entries[e['Key']] = base64.b64decode(e['Value'])
else:
entries[e['Key']] = ''
return entries
|
[
"Recursively",
"get",
"the",
"tree",
"below",
"the",
"given",
"key"
] |
bigdatacesga/kvstore
|
python
|
https://github.com/bigdatacesga/kvstore/blob/8ad2222b39d47defc8ad30deda3da06798e2a9a4/kvstore.py#L60-L83
|
[
"def",
"recurse",
"(",
"self",
",",
"k",
",",
"wait",
"=",
"False",
",",
"wait_index",
"=",
"None",
",",
"timeout",
"=",
"'5m'",
")",
":",
"k",
"=",
"k",
".",
"lstrip",
"(",
"'/'",
")",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"endpoint",
",",
"k",
")",
"params",
"=",
"{",
"}",
"params",
"[",
"'recurse'",
"]",
"=",
"'true'",
"if",
"wait",
":",
"params",
"[",
"'wait'",
"]",
"=",
"timeout",
"if",
"not",
"wait_index",
":",
"params",
"[",
"'index'",
"]",
"=",
"self",
".",
"index",
"(",
"k",
",",
"recursive",
"=",
"True",
")",
"else",
":",
"params",
"[",
"'index'",
"]",
"=",
"wait_index",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"if",
"r",
".",
"status_code",
"==",
"404",
":",
"raise",
"KeyDoesNotExist",
"(",
"\"Key \"",
"+",
"k",
"+",
"\" does not exist\"",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"raise",
"KVStoreError",
"(",
"'GET returned {}'",
".",
"format",
"(",
"r",
".",
"status_code",
")",
")",
"entries",
"=",
"{",
"}",
"for",
"e",
"in",
"r",
".",
"json",
"(",
")",
":",
"if",
"e",
"[",
"'Value'",
"]",
":",
"entries",
"[",
"e",
"[",
"'Key'",
"]",
"]",
"=",
"base64",
".",
"b64decode",
"(",
"e",
"[",
"'Value'",
"]",
")",
"else",
":",
"entries",
"[",
"e",
"[",
"'Key'",
"]",
"]",
"=",
"''",
"return",
"entries"
] |
8ad2222b39d47defc8ad30deda3da06798e2a9a4
|
test
|
Client.index
|
Get the current index of the key or the subtree.
This is needed for later creating long polling requests
|
kvstore.py
|
def index(self, k, recursive=False):
"""Get the current index of the key or the subtree.
This is needed for later creating long polling requests
"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ''
r = requests.get(url, params=params)
return r.headers['X-Consul-Index']
|
def index(self, k, recursive=False):
"""Get the current index of the key or the subtree.
This is needed for later creating long polling requests
"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ''
r = requests.get(url, params=params)
return r.headers['X-Consul-Index']
|
[
"Get",
"the",
"current",
"index",
"of",
"the",
"key",
"or",
"the",
"subtree",
".",
"This",
"is",
"needed",
"for",
"later",
"creating",
"long",
"polling",
"requests"
] |
bigdatacesga/kvstore
|
python
|
https://github.com/bigdatacesga/kvstore/blob/8ad2222b39d47defc8ad30deda3da06798e2a9a4/kvstore.py#L85-L95
|
[
"def",
"index",
"(",
"self",
",",
"k",
",",
"recursive",
"=",
"False",
")",
":",
"k",
"=",
"k",
".",
"lstrip",
"(",
"'/'",
")",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"endpoint",
",",
"k",
")",
"params",
"=",
"{",
"}",
"if",
"recursive",
":",
"params",
"[",
"'recurse'",
"]",
"=",
"''",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"return",
"r",
".",
"headers",
"[",
"'X-Consul-Index'",
"]"
] |
8ad2222b39d47defc8ad30deda3da06798e2a9a4
|
test
|
Client.delete
|
Delete a given key or recursively delete the tree below it
|
kvstore.py
|
def delete(self, k, recursive=False):
"""Delete a given key or recursively delete the tree below it"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ''
r = requests.delete(url, params=params)
if r.status_code != 200:
raise KVStoreError('DELETE returned {}'.format(r.status_code))
|
def delete(self, k, recursive=False):
"""Delete a given key or recursively delete the tree below it"""
k = k.lstrip('/')
url = '{}/{}'.format(self.endpoint, k)
params = {}
if recursive:
params['recurse'] = ''
r = requests.delete(url, params=params)
if r.status_code != 200:
raise KVStoreError('DELETE returned {}'.format(r.status_code))
|
[
"Delete",
"a",
"given",
"key",
"or",
"recursively",
"delete",
"the",
"tree",
"below",
"it"
] |
bigdatacesga/kvstore
|
python
|
https://github.com/bigdatacesga/kvstore/blob/8ad2222b39d47defc8ad30deda3da06798e2a9a4/kvstore.py#L97-L106
|
[
"def",
"delete",
"(",
"self",
",",
"k",
",",
"recursive",
"=",
"False",
")",
":",
"k",
"=",
"k",
".",
"lstrip",
"(",
"'/'",
")",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"endpoint",
",",
"k",
")",
"params",
"=",
"{",
"}",
"if",
"recursive",
":",
"params",
"[",
"'recurse'",
"]",
"=",
"''",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"params",
"=",
"params",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"raise",
"KVStoreError",
"(",
"'DELETE returned {}'",
".",
"format",
"(",
"r",
".",
"status_code",
")",
")"
] |
8ad2222b39d47defc8ad30deda3da06798e2a9a4
|
test
|
internal_error
|
Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whether to wrap the error message in a pre
As well as rendering the error message to the user, this will also log the exception
:param exception: The exception that was caught
:param template_path: The template to render (i.e. "main/error.html")
:param is_admin: Can the logged in user always view detailed error reports?
:param db: The Flask-SQLAlchemy instance
:return: Flask Response
|
littlefish/viewutil.py
|
def internal_error(exception, template_path, is_admin, db=None):
"""
Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whether to wrap the error message in a pre
As well as rendering the error message to the user, this will also log the exception
:param exception: The exception that was caught
:param template_path: The template to render (i.e. "main/error.html")
:param is_admin: Can the logged in user always view detailed error reports?
:param db: The Flask-SQLAlchemy instance
:return: Flask Response
"""
if db:
try:
db.session.rollback()
except: # noqa: E722
pass
title = str(exception)
message = traceback.format_exc()
preformat = True
log.error('Exception caught: {}\n{}'.format(title, message))
if current_app.config.get('TEST_MODE'):
show_detailed_error = True
message = 'Note: You are seeing this error message because the server is in test mode.\n\n{}'.format(message)
elif is_admin:
show_detailed_error = True
message = 'Note: You are seeing this error message because you are a member of staff.\n\n{}'.format(message)
else:
title = '500 Internal Server Error'
message = 'Something went wrong while processing your request.'
preformat = False
show_detailed_error = False
try:
return render_template(template_path, title=title, message=message, preformat=preformat,
exception=exception, is_admin=is_admin,
show_detailed_error=show_detailed_error), 500
except: # noqa: E722
log.exception('Error rendering error page!')
return '500 Internal Server Error', 500
|
def internal_error(exception, template_path, is_admin, db=None):
"""
Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whether to wrap the error message in a pre
As well as rendering the error message to the user, this will also log the exception
:param exception: The exception that was caught
:param template_path: The template to render (i.e. "main/error.html")
:param is_admin: Can the logged in user always view detailed error reports?
:param db: The Flask-SQLAlchemy instance
:return: Flask Response
"""
if db:
try:
db.session.rollback()
except: # noqa: E722
pass
title = str(exception)
message = traceback.format_exc()
preformat = True
log.error('Exception caught: {}\n{}'.format(title, message))
if current_app.config.get('TEST_MODE'):
show_detailed_error = True
message = 'Note: You are seeing this error message because the server is in test mode.\n\n{}'.format(message)
elif is_admin:
show_detailed_error = True
message = 'Note: You are seeing this error message because you are a member of staff.\n\n{}'.format(message)
else:
title = '500 Internal Server Error'
message = 'Something went wrong while processing your request.'
preformat = False
show_detailed_error = False
try:
return render_template(template_path, title=title, message=message, preformat=preformat,
exception=exception, is_admin=is_admin,
show_detailed_error=show_detailed_error), 500
except: # noqa: E722
log.exception('Error rendering error page!')
return '500 Internal Server Error', 500
|
[
"Render",
"an",
"internal",
"error",
"page",
".",
"The",
"following",
"variables",
"will",
"be",
"populated",
"when",
"rendering",
"the",
"template",
":",
"title",
":",
"The",
"page",
"title",
"message",
":",
"The",
"body",
"of",
"the",
"error",
"message",
"to",
"display",
"to",
"the",
"user",
"preformat",
":",
"Boolean",
"stating",
"whether",
"to",
"wrap",
"the",
"error",
"message",
"in",
"a",
"pre"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/viewutil.py#L15-L63
|
[
"def",
"internal_error",
"(",
"exception",
",",
"template_path",
",",
"is_admin",
",",
"db",
"=",
"None",
")",
":",
"if",
"db",
":",
"try",
":",
"db",
".",
"session",
".",
"rollback",
"(",
")",
"except",
":",
"# noqa: E722",
"pass",
"title",
"=",
"str",
"(",
"exception",
")",
"message",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"preformat",
"=",
"True",
"log",
".",
"error",
"(",
"'Exception caught: {}\\n{}'",
".",
"format",
"(",
"title",
",",
"message",
")",
")",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TEST_MODE'",
")",
":",
"show_detailed_error",
"=",
"True",
"message",
"=",
"'Note: You are seeing this error message because the server is in test mode.\\n\\n{}'",
".",
"format",
"(",
"message",
")",
"elif",
"is_admin",
":",
"show_detailed_error",
"=",
"True",
"message",
"=",
"'Note: You are seeing this error message because you are a member of staff.\\n\\n{}'",
".",
"format",
"(",
"message",
")",
"else",
":",
"title",
"=",
"'500 Internal Server Error'",
"message",
"=",
"'Something went wrong while processing your request.'",
"preformat",
"=",
"False",
"show_detailed_error",
"=",
"False",
"try",
":",
"return",
"render_template",
"(",
"template_path",
",",
"title",
"=",
"title",
",",
"message",
"=",
"message",
",",
"preformat",
"=",
"preformat",
",",
"exception",
"=",
"exception",
",",
"is_admin",
"=",
"is_admin",
",",
"show_detailed_error",
"=",
"show_detailed_error",
")",
",",
"500",
"except",
":",
"# noqa: E722",
"log",
".",
"exception",
"(",
"'Error rendering error page!'",
")",
"return",
"'500 Internal Server Error'",
",",
"500"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
plot_heatmap
|
Plot heatmap which shows features with classes.
:param X: list of dict
:param y: labels
:param top_n: most important n feature
:param metric: metric which will be used for clustering
:param method: method which will be used for clustering
|
sklearn_utils/visualization/heatmap.py
|
def plot_heatmap(X, y, top_n=10, metric='correlation', method='complete'):
'''
Plot heatmap which shows features with classes.
:param X: list of dict
:param y: labels
:param top_n: most important n feature
:param metric: metric which will be used for clustering
:param method: method which will be used for clustering
'''
sns.set(color_codes=True)
df = feature_importance_report(X, y)
df_sns = pd.DataFrame().from_records(X)[df[:top_n].index].T
df_sns.columns = y
color_mapping = dict(zip(set(y), sns.mpl_palette("Set2", len(set(y)))))
return sns.clustermap(df_sns, figsize=(22, 22), z_score=0,
metric=metric, method=method,
col_colors=[color_mapping[i] for i in y])
|
def plot_heatmap(X, y, top_n=10, metric='correlation', method='complete'):
'''
Plot heatmap which shows features with classes.
:param X: list of dict
:param y: labels
:param top_n: most important n feature
:param metric: metric which will be used for clustering
:param method: method which will be used for clustering
'''
sns.set(color_codes=True)
df = feature_importance_report(X, y)
df_sns = pd.DataFrame().from_records(X)[df[:top_n].index].T
df_sns.columns = y
color_mapping = dict(zip(set(y), sns.mpl_palette("Set2", len(set(y)))))
return sns.clustermap(df_sns, figsize=(22, 22), z_score=0,
metric=metric, method=method,
col_colors=[color_mapping[i] for i in y])
|
[
"Plot",
"heatmap",
"which",
"shows",
"features",
"with",
"classes",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/visualization/heatmap.py#L7-L28
|
[
"def",
"plot_heatmap",
"(",
"X",
",",
"y",
",",
"top_n",
"=",
"10",
",",
"metric",
"=",
"'correlation'",
",",
"method",
"=",
"'complete'",
")",
":",
"sns",
".",
"set",
"(",
"color_codes",
"=",
"True",
")",
"df",
"=",
"feature_importance_report",
"(",
"X",
",",
"y",
")",
"df_sns",
"=",
"pd",
".",
"DataFrame",
"(",
")",
".",
"from_records",
"(",
"X",
")",
"[",
"df",
"[",
":",
"top_n",
"]",
".",
"index",
"]",
".",
"T",
"df_sns",
".",
"columns",
"=",
"y",
"color_mapping",
"=",
"dict",
"(",
"zip",
"(",
"set",
"(",
"y",
")",
",",
"sns",
".",
"mpl_palette",
"(",
"\"Set2\"",
",",
"len",
"(",
"set",
"(",
"y",
")",
")",
")",
")",
")",
"return",
"sns",
".",
"clustermap",
"(",
"df_sns",
",",
"figsize",
"=",
"(",
"22",
",",
"22",
")",
",",
"z_score",
"=",
"0",
",",
"metric",
"=",
"metric",
",",
"method",
"=",
"method",
",",
"col_colors",
"=",
"[",
"color_mapping",
"[",
"i",
"]",
"for",
"i",
"in",
"y",
"]",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
get_setup_version
|
获取打包使用的版本号,符合 PYPI 官方推荐的版本号方案
:return: PYPI 打包版本号
:rtype: str
|
source/mohand/version.py
|
def get_setup_version():
"""
获取打包使用的版本号,符合 PYPI 官方推荐的版本号方案
:return: PYPI 打包版本号
:rtype: str
"""
ver = '.'.join(map(str, VERSION[:3]))
# 若后缀描述字串为 None ,则直接返回主版本号
if not VERSION[3]:
return ver
# 否则,追加版本号后缀
hyphen = ''
suffix = hyphen.join(map(str, VERSION[-2:]))
if VERSION[3] in [VERSION_SUFFIX_DEV, VERSION_SUFFIX_POST]:
hyphen = '.'
ver = hyphen.join([ver, suffix])
return ver
|
def get_setup_version():
"""
获取打包使用的版本号,符合 PYPI 官方推荐的版本号方案
:return: PYPI 打包版本号
:rtype: str
"""
ver = '.'.join(map(str, VERSION[:3]))
# 若后缀描述字串为 None ,则直接返回主版本号
if not VERSION[3]:
return ver
# 否则,追加版本号后缀
hyphen = ''
suffix = hyphen.join(map(str, VERSION[-2:]))
if VERSION[3] in [VERSION_SUFFIX_DEV, VERSION_SUFFIX_POST]:
hyphen = '.'
ver = hyphen.join([ver, suffix])
return ver
|
[
"获取打包使用的版本号,符合",
"PYPI",
"官方推荐的版本号方案"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/version.py#L22-L42
|
[
"def",
"get_setup_version",
"(",
")",
":",
"ver",
"=",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"VERSION",
"[",
":",
"3",
"]",
")",
")",
"# 若后缀描述字串为 None ,则直接返回主版本号",
"if",
"not",
"VERSION",
"[",
"3",
"]",
":",
"return",
"ver",
"# 否则,追加版本号后缀",
"hyphen",
"=",
"''",
"suffix",
"=",
"hyphen",
".",
"join",
"(",
"map",
"(",
"str",
",",
"VERSION",
"[",
"-",
"2",
":",
"]",
")",
")",
"if",
"VERSION",
"[",
"3",
"]",
"in",
"[",
"VERSION_SUFFIX_DEV",
",",
"VERSION_SUFFIX_POST",
"]",
":",
"hyphen",
"=",
"'.'",
"ver",
"=",
"hyphen",
".",
"join",
"(",
"[",
"ver",
",",
"suffix",
"]",
")",
"return",
"ver"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
get_cli_version
|
获取终端命令版本号,若存在VERSION文件则使用其中的版本号,
否则使用 :meth:`.get_setup_version`
:return: 终端命令版本号
:rtype: str
|
source/mohand/version.py
|
def get_cli_version():
"""
获取终端命令版本号,若存在VERSION文件则使用其中的版本号,
否则使用 :meth:`.get_setup_version`
:return: 终端命令版本号
:rtype: str
"""
directory = os.path.dirname(os.path.abspath(__file__))
version_path = os.path.join(directory, 'VERSION')
if os.path.exists(version_path):
with open(version_path) as f:
ver = f.read()
return ver
return get_setup_version()
|
def get_cli_version():
"""
获取终端命令版本号,若存在VERSION文件则使用其中的版本号,
否则使用 :meth:`.get_setup_version`
:return: 终端命令版本号
:rtype: str
"""
directory = os.path.dirname(os.path.abspath(__file__))
version_path = os.path.join(directory, 'VERSION')
if os.path.exists(version_path):
with open(version_path) as f:
ver = f.read()
return ver
return get_setup_version()
|
[
"获取终端命令版本号,若存在VERSION文件则使用其中的版本号,",
"否则使用",
":",
"meth",
":",
".",
"get_setup_version"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/version.py#L45-L60
|
[
"def",
"get_cli_version",
"(",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"version_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'VERSION'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"version_path",
")",
":",
"with",
"open",
"(",
"version_path",
")",
"as",
"f",
":",
"ver",
"=",
"f",
".",
"read",
"(",
")",
"return",
"ver",
"return",
"get_setup_version",
"(",
")"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
add_months
|
Add a number of months to a timestamp
|
littlefish/timetool.py
|
def add_months(months, timestamp=datetime.datetime.utcnow()):
"""Add a number of months to a timestamp"""
month = timestamp.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
year = timestamp.year + years
try:
return datetime.datetime(year, new_month, timestamp.day, timestamp.hour, timestamp.minute, timestamp.second)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
# We are adding, so use the first day of the next month
new_month += 1
if new_month > 12:
new_month -= 12
year += 1
return datetime.datetime(year, new_month, 1, timestamp.hour, timestamp.minute, timestamp.second)
else:
# We are subtracting - use the last day of the same month
new_day = calendar.monthrange(year, new_month)[1]
return datetime.datetime(year, new_month, new_day, timestamp.hour, timestamp.minute, timestamp.second)
|
def add_months(months, timestamp=datetime.datetime.utcnow()):
"""Add a number of months to a timestamp"""
month = timestamp.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
year = timestamp.year + years
try:
return datetime.datetime(year, new_month, timestamp.day, timestamp.hour, timestamp.minute, timestamp.second)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
# We are adding, so use the first day of the next month
new_month += 1
if new_month > 12:
new_month -= 12
year += 1
return datetime.datetime(year, new_month, 1, timestamp.hour, timestamp.minute, timestamp.second)
else:
# We are subtracting - use the last day of the same month
new_day = calendar.monthrange(year, new_month)[1]
return datetime.datetime(year, new_month, new_day, timestamp.hour, timestamp.minute, timestamp.second)
|
[
"Add",
"a",
"number",
"of",
"months",
"to",
"a",
"timestamp"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/timetool.py#L218-L251
|
[
"def",
"add_months",
"(",
"months",
",",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
")",
":",
"month",
"=",
"timestamp",
".",
"month",
"new_month",
"=",
"month",
"+",
"months",
"years",
"=",
"0",
"while",
"new_month",
"<",
"1",
":",
"new_month",
"+=",
"12",
"years",
"-=",
"1",
"while",
"new_month",
">",
"12",
":",
"new_month",
"-=",
"12",
"years",
"+=",
"1",
"# month = timestamp.month",
"year",
"=",
"timestamp",
".",
"year",
"+",
"years",
"try",
":",
"return",
"datetime",
".",
"datetime",
"(",
"year",
",",
"new_month",
",",
"timestamp",
".",
"day",
",",
"timestamp",
".",
"hour",
",",
"timestamp",
".",
"minute",
",",
"timestamp",
".",
"second",
")",
"except",
"ValueError",
":",
"# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day",
"# 1 month ago, and it is trying to return 30th February",
"if",
"months",
">",
"0",
":",
"# We are adding, so use the first day of the next month",
"new_month",
"+=",
"1",
"if",
"new_month",
">",
"12",
":",
"new_month",
"-=",
"12",
"year",
"+=",
"1",
"return",
"datetime",
".",
"datetime",
"(",
"year",
",",
"new_month",
",",
"1",
",",
"timestamp",
".",
"hour",
",",
"timestamp",
".",
"minute",
",",
"timestamp",
".",
"second",
")",
"else",
":",
"# We are subtracting - use the last day of the same month",
"new_day",
"=",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"new_month",
")",
"[",
"1",
"]",
"return",
"datetime",
".",
"datetime",
"(",
"year",
",",
"new_month",
",",
"new_day",
",",
"timestamp",
".",
"hour",
",",
"timestamp",
".",
"minute",
",",
"timestamp",
".",
"second",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
add_months_to_date
|
Add a number of months to a date
|
littlefish/timetool.py
|
def add_months_to_date(months, date):
"""Add a number of months to a date"""
month = date.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
year = date.year + years
try:
return datetime.date(year, new_month, date.day)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
# We are adding, so use the first day of the next month
new_month += 1
if new_month > 12:
new_month -= 12
year += 1
return datetime.datetime(year, new_month, 1)
else:
# We are subtracting - use the last day of the same month
new_day = calendar.monthrange(year, new_month)[1]
return datetime.datetime(year, new_month, new_day)
|
def add_months_to_date(months, date):
"""Add a number of months to a date"""
month = date.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
year = date.year + years
try:
return datetime.date(year, new_month, date.day)
except ValueError:
# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day
# 1 month ago, and it is trying to return 30th February
if months > 0:
# We are adding, so use the first day of the next month
new_month += 1
if new_month > 12:
new_month -= 12
year += 1
return datetime.datetime(year, new_month, 1)
else:
# We are subtracting - use the last day of the same month
new_day = calendar.monthrange(year, new_month)[1]
return datetime.datetime(year, new_month, new_day)
|
[
"Add",
"a",
"number",
"of",
"months",
"to",
"a",
"date"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/timetool.py#L254-L287
|
[
"def",
"add_months_to_date",
"(",
"months",
",",
"date",
")",
":",
"month",
"=",
"date",
".",
"month",
"new_month",
"=",
"month",
"+",
"months",
"years",
"=",
"0",
"while",
"new_month",
"<",
"1",
":",
"new_month",
"+=",
"12",
"years",
"-=",
"1",
"while",
"new_month",
">",
"12",
":",
"new_month",
"-=",
"12",
"years",
"+=",
"1",
"# month = timestamp.month",
"year",
"=",
"date",
".",
"year",
"+",
"years",
"try",
":",
"return",
"datetime",
".",
"date",
"(",
"year",
",",
"new_month",
",",
"date",
".",
"day",
")",
"except",
"ValueError",
":",
"# This means that the day exceeds the last day of the month, i.e. it is 30th March, and we are finding the day",
"# 1 month ago, and it is trying to return 30th February",
"if",
"months",
">",
"0",
":",
"# We are adding, so use the first day of the next month",
"new_month",
"+=",
"1",
"if",
"new_month",
">",
"12",
":",
"new_month",
"-=",
"12",
"year",
"+=",
"1",
"return",
"datetime",
".",
"datetime",
"(",
"year",
",",
"new_month",
",",
"1",
")",
"else",
":",
"# We are subtracting - use the last day of the same month",
"new_day",
"=",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"new_month",
")",
"[",
"1",
"]",
"return",
"datetime",
".",
"datetime",
"(",
"year",
",",
"new_month",
",",
"new_day",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
unix_time
|
Generate a unix style timestamp (in seconds)
|
littlefish/timetool.py
|
def unix_time(dt=None, as_int=False):
"""Generate a unix style timestamp (in seconds)"""
if dt is None:
dt = datetime.datetime.utcnow()
if type(dt) is datetime.date:
dt = date_to_datetime(dt)
epoch = datetime.datetime.utcfromtimestamp(0)
delta = dt - epoch
if as_int:
return int(delta.total_seconds())
return delta.total_seconds()
|
def unix_time(dt=None, as_int=False):
"""Generate a unix style timestamp (in seconds)"""
if dt is None:
dt = datetime.datetime.utcnow()
if type(dt) is datetime.date:
dt = date_to_datetime(dt)
epoch = datetime.datetime.utcfromtimestamp(0)
delta = dt - epoch
if as_int:
return int(delta.total_seconds())
return delta.total_seconds()
|
[
"Generate",
"a",
"unix",
"style",
"timestamp",
"(",
"in",
"seconds",
")"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/timetool.py#L290-L304
|
[
"def",
"unix_time",
"(",
"dt",
"=",
"None",
",",
"as_int",
"=",
"False",
")",
":",
"if",
"dt",
"is",
"None",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"type",
"(",
"dt",
")",
"is",
"datetime",
".",
"date",
":",
"dt",
"=",
"date_to_datetime",
"(",
"dt",
")",
"epoch",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"0",
")",
"delta",
"=",
"dt",
"-",
"epoch",
"if",
"as_int",
":",
"return",
"int",
"(",
"delta",
".",
"total_seconds",
"(",
")",
")",
"return",
"delta",
".",
"total_seconds",
"(",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
is_christmas_period
|
Is this the christmas period?
|
littlefish/timetool.py
|
def is_christmas_period():
"""Is this the christmas period?"""
now = datetime.date.today()
if now.month != 12:
return False
if now.day < 15:
return False
if now.day > 27:
return False
return True
|
def is_christmas_period():
"""Is this the christmas period?"""
now = datetime.date.today()
if now.month != 12:
return False
if now.day < 15:
return False
if now.day > 27:
return False
return True
|
[
"Is",
"this",
"the",
"christmas",
"period?"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/timetool.py#L320-L329
|
[
"def",
"is_christmas_period",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"if",
"now",
".",
"month",
"!=",
"12",
":",
"return",
"False",
"if",
"now",
".",
"day",
"<",
"15",
":",
"return",
"False",
"if",
"now",
".",
"day",
">",
"27",
":",
"return",
"False",
"return",
"True"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
get_end_of_day
|
Given a date or a datetime, return a datetime at 23:59:59 on that day
|
littlefish/timetool.py
|
def get_end_of_day(timestamp):
"""
Given a date or a datetime, return a datetime at 23:59:59 on that day
"""
return datetime.datetime(timestamp.year, timestamp.month, timestamp.day, 23, 59, 59)
|
def get_end_of_day(timestamp):
"""
Given a date or a datetime, return a datetime at 23:59:59 on that day
"""
return datetime.datetime(timestamp.year, timestamp.month, timestamp.day, 23, 59, 59)
|
[
"Given",
"a",
"date",
"or",
"a",
"datetime",
"return",
"a",
"datetime",
"at",
"23",
":",
"59",
":",
"59",
"on",
"that",
"day"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/timetool.py#L332-L336
|
[
"def",
"get_end_of_day",
"(",
"timestamp",
")",
":",
"return",
"datetime",
".",
"datetime",
"(",
"timestamp",
".",
"year",
",",
"timestamp",
".",
"month",
",",
"timestamp",
".",
"day",
",",
"23",
",",
"59",
",",
"59",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
DictInput.transform
|
:param X: features.
|
sklearn_utils/preprocessing/dict_input.py
|
def transform(self, X):
'''
:param X: features.
'''
inverser_tranformer = self.dict_vectorizer_
if self.feature_selection:
inverser_tranformer = self.clone_dict_vectorizer_
return inverser_tranformer.inverse_transform(
self.transformer.transform(
self.dict_vectorizer_.transform(X)))
|
def transform(self, X):
'''
:param X: features.
'''
inverser_tranformer = self.dict_vectorizer_
if self.feature_selection:
inverser_tranformer = self.clone_dict_vectorizer_
return inverser_tranformer.inverse_transform(
self.transformer.transform(
self.dict_vectorizer_.transform(X)))
|
[
":",
"param",
"X",
":",
"features",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/dict_input.py#L29-L39
|
[
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"inverser_tranformer",
"=",
"self",
".",
"dict_vectorizer_",
"if",
"self",
".",
"feature_selection",
":",
"inverser_tranformer",
"=",
"self",
".",
"clone_dict_vectorizer_",
"return",
"inverser_tranformer",
".",
"inverse_transform",
"(",
"self",
".",
"transformer",
".",
"transform",
"(",
"self",
".",
"dict_vectorizer_",
".",
"transform",
"(",
"X",
")",
")",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
ConnectionHandler.use_music_service
|
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
|
music2storage/connection.py
|
def use_music_service(self, service_name, api_key):
"""
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
"""
try:
self.current_music = self.music_services[service_name]
except KeyError:
if service_name == 'youtube':
self.music_services['youtube'] = Youtube()
self.current_music = self.music_services['youtube']
elif service_name == 'soundcloud':
self.music_services['soundcloud'] = Soundcloud(api_key=api_key)
self.current_music = self.music_services['soundcloud']
else:
log.error('Music service name is not recognized.')
|
def use_music_service(self, service_name, api_key):
"""
Sets the current music service to service_name.
:param str service_name: Name of the music service
:param str api_key: Optional API key if necessary
"""
try:
self.current_music = self.music_services[service_name]
except KeyError:
if service_name == 'youtube':
self.music_services['youtube'] = Youtube()
self.current_music = self.music_services['youtube']
elif service_name == 'soundcloud':
self.music_services['soundcloud'] = Soundcloud(api_key=api_key)
self.current_music = self.music_services['soundcloud']
else:
log.error('Music service name is not recognized.')
|
[
"Sets",
"the",
"current",
"music",
"service",
"to",
"service_name",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/connection.py#L16-L34
|
[
"def",
"use_music_service",
"(",
"self",
",",
"service_name",
",",
"api_key",
")",
":",
"try",
":",
"self",
".",
"current_music",
"=",
"self",
".",
"music_services",
"[",
"service_name",
"]",
"except",
"KeyError",
":",
"if",
"service_name",
"==",
"'youtube'",
":",
"self",
".",
"music_services",
"[",
"'youtube'",
"]",
"=",
"Youtube",
"(",
")",
"self",
".",
"current_music",
"=",
"self",
".",
"music_services",
"[",
"'youtube'",
"]",
"elif",
"service_name",
"==",
"'soundcloud'",
":",
"self",
".",
"music_services",
"[",
"'soundcloud'",
"]",
"=",
"Soundcloud",
"(",
"api_key",
"=",
"api_key",
")",
"self",
".",
"current_music",
"=",
"self",
".",
"music_services",
"[",
"'soundcloud'",
"]",
"else",
":",
"log",
".",
"error",
"(",
"'Music service name is not recognized.'",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
ConnectionHandler.use_storage_service
|
Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only)
|
music2storage/connection.py
|
def use_storage_service(self, service_name, custom_path):
"""
Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only)
"""
try:
self.current_storage = self.storage_services[service_name]
except KeyError:
if service_name == 'google drive':
self.storage_services['google drive'] = GoogleDrive()
self.current_storage = self.storage_services['google drive']
self.current_storage.connect()
elif service_name == 'dropbox':
log.error('Dropbox is not supported yet.')
elif service_name == 'local':
self.storage_services['local'] = LocalStorage(custom_path=custom_path)
self.current_storage = self.storage_services['local']
self.current_storage.connect()
else:
log.error('Storage service name is not recognized.')
|
def use_storage_service(self, service_name, custom_path):
"""
Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only)
"""
try:
self.current_storage = self.storage_services[service_name]
except KeyError:
if service_name == 'google drive':
self.storage_services['google drive'] = GoogleDrive()
self.current_storage = self.storage_services['google drive']
self.current_storage.connect()
elif service_name == 'dropbox':
log.error('Dropbox is not supported yet.')
elif service_name == 'local':
self.storage_services['local'] = LocalStorage(custom_path=custom_path)
self.current_storage = self.storage_services['local']
self.current_storage.connect()
else:
log.error('Storage service name is not recognized.')
|
[
"Sets",
"the",
"current",
"storage",
"service",
"to",
"service_name",
"and",
"runs",
"the",
"connect",
"method",
"on",
"the",
"service",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/connection.py#L36-L58
|
[
"def",
"use_storage_service",
"(",
"self",
",",
"service_name",
",",
"custom_path",
")",
":",
"try",
":",
"self",
".",
"current_storage",
"=",
"self",
".",
"storage_services",
"[",
"service_name",
"]",
"except",
"KeyError",
":",
"if",
"service_name",
"==",
"'google drive'",
":",
"self",
".",
"storage_services",
"[",
"'google drive'",
"]",
"=",
"GoogleDrive",
"(",
")",
"self",
".",
"current_storage",
"=",
"self",
".",
"storage_services",
"[",
"'google drive'",
"]",
"self",
".",
"current_storage",
".",
"connect",
"(",
")",
"elif",
"service_name",
"==",
"'dropbox'",
":",
"log",
".",
"error",
"(",
"'Dropbox is not supported yet.'",
")",
"elif",
"service_name",
"==",
"'local'",
":",
"self",
".",
"storage_services",
"[",
"'local'",
"]",
"=",
"LocalStorage",
"(",
"custom_path",
"=",
"custom_path",
")",
"self",
".",
"current_storage",
"=",
"self",
".",
"storage_services",
"[",
"'local'",
"]",
"self",
".",
"current_storage",
".",
"connect",
"(",
")",
"else",
":",
"log",
".",
"error",
"(",
"'Storage service name is not recognized.'",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
SkUtilsIO.from_csv
|
Read dataset from csv.
|
sklearn_utils/utils/skutils_io.py
|
def from_csv(self, label_column='labels'):
'''
Read dataset from csv.
'''
df = pd.read_csv(self.path, header=0)
X = df.loc[:, df.columns != label_column].to_dict('records')
X = map_dict_list(X, if_func=lambda k, v: v and math.isfinite(v))
y = list(df[label_column].values)
return X, y
|
def from_csv(self, label_column='labels'):
'''
Read dataset from csv.
'''
df = pd.read_csv(self.path, header=0)
X = df.loc[:, df.columns != label_column].to_dict('records')
X = map_dict_list(X, if_func=lambda k, v: v and math.isfinite(v))
y = list(df[label_column].values)
return X, y
|
[
"Read",
"dataset",
"from",
"csv",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/skutils_io.py#L23-L31
|
[
"def",
"from_csv",
"(",
"self",
",",
"label_column",
"=",
"'labels'",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"self",
".",
"path",
",",
"header",
"=",
"0",
")",
"X",
"=",
"df",
".",
"loc",
"[",
":",
",",
"df",
".",
"columns",
"!=",
"label_column",
"]",
".",
"to_dict",
"(",
"'records'",
")",
"X",
"=",
"map_dict_list",
"(",
"X",
",",
"if_func",
"=",
"lambda",
"k",
",",
"v",
":",
"v",
"and",
"math",
".",
"isfinite",
"(",
"v",
")",
")",
"y",
"=",
"list",
"(",
"df",
"[",
"label_column",
"]",
".",
"values",
")",
"return",
"X",
",",
"y"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
SkUtilsIO.from_json
|
Reads dataset from json.
|
sklearn_utils/utils/skutils_io.py
|
def from_json(self):
'''
Reads dataset from json.
'''
with gzip.open('%s.gz' % self.path,
'rt') if self.gz else open(self.path) as file:
return list(map(list, zip(*json.load(file))))[::-1]
|
def from_json(self):
'''
Reads dataset from json.
'''
with gzip.open('%s.gz' % self.path,
'rt') if self.gz else open(self.path) as file:
return list(map(list, zip(*json.load(file))))[::-1]
|
[
"Reads",
"dataset",
"from",
"json",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/skutils_io.py#L40-L46
|
[
"def",
"from_json",
"(",
"self",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"'%s.gz'",
"%",
"self",
".",
"path",
",",
"'rt'",
")",
"if",
"self",
".",
"gz",
"else",
"open",
"(",
"self",
".",
"path",
")",
"as",
"file",
":",
"return",
"list",
"(",
"map",
"(",
"list",
",",
"zip",
"(",
"*",
"json",
".",
"load",
"(",
"file",
")",
")",
")",
")",
"[",
":",
":",
"-",
"1",
"]"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
SkUtilsIO.to_json
|
Reads dataset to csv.
:param X: dataset as list of dict.
:param y: labels.
|
sklearn_utils/utils/skutils_io.py
|
def to_json(self, X, y):
'''
Reads dataset to csv.
:param X: dataset as list of dict.
:param y: labels.
'''
with gzip.open('%s.gz' % self.path, 'wt') if self.gz else open(
self.path, 'w') as file:
json.dump(list(zip(y, X)), file)
|
def to_json(self, X, y):
'''
Reads dataset to csv.
:param X: dataset as list of dict.
:param y: labels.
'''
with gzip.open('%s.gz' % self.path, 'wt') if self.gz else open(
self.path, 'w') as file:
json.dump(list(zip(y, X)), file)
|
[
"Reads",
"dataset",
"to",
"csv",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/skutils_io.py#L48-L57
|
[
"def",
"to_json",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"'%s.gz'",
"%",
"self",
".",
"path",
",",
"'wt'",
")",
"if",
"self",
".",
"gz",
"else",
"open",
"(",
"self",
".",
"path",
",",
"'w'",
")",
"as",
"file",
":",
"json",
".",
"dump",
"(",
"list",
"(",
"zip",
"(",
"y",
",",
"X",
")",
")",
",",
"file",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
filter_by_label
|
Select items with label from dataset.
:param X: dataset
:param y: labels
:param ref_label: reference label
:param bool reverse: if false selects ref_labels else eliminates
|
sklearn_utils/utils/data_utils.py
|
def filter_by_label(X, y, ref_label, reverse=False):
'''
Select items with label from dataset.
:param X: dataset
:param y: labels
:param ref_label: reference label
:param bool reverse: if false selects ref_labels else eliminates
'''
check_reference_label(y, ref_label)
return list(zip(*filter(lambda t: (not reverse) == (t[1] == ref_label),
zip(X, y))))
|
def filter_by_label(X, y, ref_label, reverse=False):
'''
Select items with label from dataset.
:param X: dataset
:param y: labels
:param ref_label: reference label
:param bool reverse: if false selects ref_labels else eliminates
'''
check_reference_label(y, ref_label)
return list(zip(*filter(lambda t: (not reverse) == (t[1] == ref_label),
zip(X, y))))
|
[
"Select",
"items",
"with",
"label",
"from",
"dataset",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/data_utils.py#L8-L20
|
[
"def",
"filter_by_label",
"(",
"X",
",",
"y",
",",
"ref_label",
",",
"reverse",
"=",
"False",
")",
":",
"check_reference_label",
"(",
"y",
",",
"ref_label",
")",
"return",
"list",
"(",
"zip",
"(",
"*",
"filter",
"(",
"lambda",
"t",
":",
"(",
"not",
"reverse",
")",
"==",
"(",
"t",
"[",
"1",
"]",
"==",
"ref_label",
")",
",",
"zip",
"(",
"X",
",",
"y",
")",
")",
")",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
average_by_label
|
Calculates average dictinary from list of dictionary for give label
:param List[Dict] X: dataset
:param list y: labels
:param ref_label: reference label
|
sklearn_utils/utils/data_utils.py
|
def average_by_label(X, y, ref_label):
'''
Calculates average dictinary from list of dictionary for give label
:param List[Dict] X: dataset
:param list y: labels
:param ref_label: reference label
'''
# TODO: consider to delete defaultdict
return defaultdict(float,
pd.DataFrame.from_records(
filter_by_label(X, y, ref_label)[0]
).mean().to_dict())
|
def average_by_label(X, y, ref_label):
'''
Calculates average dictinary from list of dictionary for give label
:param List[Dict] X: dataset
:param list y: labels
:param ref_label: reference label
'''
# TODO: consider to delete defaultdict
return defaultdict(float,
pd.DataFrame.from_records(
filter_by_label(X, y, ref_label)[0]
).mean().to_dict())
|
[
"Calculates",
"average",
"dictinary",
"from",
"list",
"of",
"dictionary",
"for",
"give",
"label"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/data_utils.py#L23-L35
|
[
"def",
"average_by_label",
"(",
"X",
",",
"y",
",",
"ref_label",
")",
":",
"# TODO: consider to delete defaultdict",
"return",
"defaultdict",
"(",
"float",
",",
"pd",
".",
"DataFrame",
".",
"from_records",
"(",
"filter_by_label",
"(",
"X",
",",
"y",
",",
"ref_label",
")",
"[",
"0",
"]",
")",
".",
"mean",
"(",
")",
".",
"to_dict",
"(",
")",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
map_dict
|
:param dict d: dictionary
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
|
sklearn_utils/utils/data_utils.py
|
def map_dict(d, key_func=None, value_func=None, if_func=None):
'''
:param dict d: dictionary
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
'''
key_func = key_func or (lambda k, v: k)
value_func = value_func or (lambda k, v: v)
if_func = if_func or (lambda k, v: True)
return {
key_func(*k_v): value_func(*k_v)
for k_v in d.items() if if_func(*k_v)
}
|
def map_dict(d, key_func=None, value_func=None, if_func=None):
'''
:param dict d: dictionary
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
'''
key_func = key_func or (lambda k, v: k)
value_func = value_func or (lambda k, v: v)
if_func = if_func or (lambda k, v: True)
return {
key_func(*k_v): value_func(*k_v)
for k_v in d.items() if if_func(*k_v)
}
|
[
":",
"param",
"dict",
"d",
":",
"dictionary",
":",
"param",
"func",
"key_func",
":",
"func",
"which",
"will",
"run",
"on",
"key",
".",
":",
"param",
"func",
"value_func",
":",
"func",
"which",
"will",
"run",
"on",
"values",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/data_utils.py#L38-L50
|
[
"def",
"map_dict",
"(",
"d",
",",
"key_func",
"=",
"None",
",",
"value_func",
"=",
"None",
",",
"if_func",
"=",
"None",
")",
":",
"key_func",
"=",
"key_func",
"or",
"(",
"lambda",
"k",
",",
"v",
":",
"k",
")",
"value_func",
"=",
"value_func",
"or",
"(",
"lambda",
"k",
",",
"v",
":",
"v",
")",
"if_func",
"=",
"if_func",
"or",
"(",
"lambda",
"k",
",",
"v",
":",
"True",
")",
"return",
"{",
"key_func",
"(",
"*",
"k_v",
")",
":",
"value_func",
"(",
"*",
"k_v",
")",
"for",
"k_v",
"in",
"d",
".",
"items",
"(",
")",
"if",
"if_func",
"(",
"*",
"k_v",
")",
"}"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
map_dict_list
|
:param List[Dict] ds: list of dict
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
|
sklearn_utils/utils/data_utils.py
|
def map_dict_list(ds, key_func=None, value_func=None, if_func=None):
'''
:param List[Dict] ds: list of dict
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
'''
return [map_dict(d, key_func, value_func, if_func) for d in ds]
|
def map_dict_list(ds, key_func=None, value_func=None, if_func=None):
'''
:param List[Dict] ds: list of dict
:param func key_func: func which will run on key.
:param func value_func: func which will run on values.
'''
return [map_dict(d, key_func, value_func, if_func) for d in ds]
|
[
":",
"param",
"List",
"[",
"Dict",
"]",
"ds",
":",
"list",
"of",
"dict",
":",
"param",
"func",
"key_func",
":",
"func",
"which",
"will",
"run",
"on",
"key",
".",
":",
"param",
"func",
"value_func",
":",
"func",
"which",
"will",
"run",
"on",
"values",
"."
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/data_utils.py#L53-L59
|
[
"def",
"map_dict_list",
"(",
"ds",
",",
"key_func",
"=",
"None",
",",
"value_func",
"=",
"None",
",",
"if_func",
"=",
"None",
")",
":",
"return",
"[",
"map_dict",
"(",
"d",
",",
"key_func",
",",
"value_func",
",",
"if_func",
")",
"for",
"d",
"in",
"ds",
"]"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
check_reference_label
|
:param list y: label
:param ref_label: reference label
|
sklearn_utils/utils/data_utils.py
|
def check_reference_label(y, ref_label):
'''
:param list y: label
:param ref_label: reference label
'''
set_y = set(y)
if ref_label not in set_y:
raise ValueError('There is not reference label in dataset. '
"Reference label: '%s' "
'Labels in dataset: %s' % (ref_label, set_y))
|
def check_reference_label(y, ref_label):
'''
:param list y: label
:param ref_label: reference label
'''
set_y = set(y)
if ref_label not in set_y:
raise ValueError('There is not reference label in dataset. '
"Reference label: '%s' "
'Labels in dataset: %s' % (ref_label, set_y))
|
[
":",
"param",
"list",
"y",
":",
"label",
":",
"param",
"ref_label",
":",
"reference",
"label"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/data_utils.py#L62-L71
|
[
"def",
"check_reference_label",
"(",
"y",
",",
"ref_label",
")",
":",
"set_y",
"=",
"set",
"(",
"y",
")",
"if",
"ref_label",
"not",
"in",
"set_y",
":",
"raise",
"ValueError",
"(",
"'There is not reference label in dataset. '",
"\"Reference label: '%s' \"",
"'Labels in dataset: %s'",
"%",
"(",
"ref_label",
",",
"set_y",
")",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
feature_importance_report
|
Provide signifance for features in dataset with anova using multiple hypostesis testing
:param X: List of dict with key as feature names and values as features
:param y: Labels
:param threshold: Low-variens threshold to eliminate low varience features
:param correcting_multiple_hypotesis: corrects p-val with multiple hypotesis testing
:param method: method of multiple hypotesis testing
:param alpha: alpha of multiple hypotesis testing
:param sort_by: sorts output dataframe by pval or F
:return: DataFrame with F and pval for each feature with their average values
|
sklearn_utils/utils/data_utils.py
|
def feature_importance_report(X,
y,
threshold=0.001,
correcting_multiple_hypotesis=True,
method='fdr_bh',
alpha=0.1,
sort_by='pval'):
'''
Provide signifance for features in dataset with anova using multiple hypostesis testing
:param X: List of dict with key as feature names and values as features
:param y: Labels
:param threshold: Low-variens threshold to eliminate low varience features
:param correcting_multiple_hypotesis: corrects p-val with multiple hypotesis testing
:param method: method of multiple hypotesis testing
:param alpha: alpha of multiple hypotesis testing
:param sort_by: sorts output dataframe by pval or F
:return: DataFrame with F and pval for each feature with their average values
'''
df = variance_threshold_on_df(
pd.DataFrame.from_records(X), threshold=threshold)
F, pvals = f_classif(df.values, y)
if correcting_multiple_hypotesis:
_, pvals, _, _ = multipletests(pvals, alpha=alpha, method=method)
df['labels'] = y
df_mean = df.groupby('labels').mean().T
df_mean['F'] = F
df_mean['pval'] = pvals
return df_mean.sort_values(sort_by, ascending=True)
|
def feature_importance_report(X,
y,
threshold=0.001,
correcting_multiple_hypotesis=True,
method='fdr_bh',
alpha=0.1,
sort_by='pval'):
'''
Provide signifance for features in dataset with anova using multiple hypostesis testing
:param X: List of dict with key as feature names and values as features
:param y: Labels
:param threshold: Low-variens threshold to eliminate low varience features
:param correcting_multiple_hypotesis: corrects p-val with multiple hypotesis testing
:param method: method of multiple hypotesis testing
:param alpha: alpha of multiple hypotesis testing
:param sort_by: sorts output dataframe by pval or F
:return: DataFrame with F and pval for each feature with their average values
'''
df = variance_threshold_on_df(
pd.DataFrame.from_records(X), threshold=threshold)
F, pvals = f_classif(df.values, y)
if correcting_multiple_hypotesis:
_, pvals, _, _ = multipletests(pvals, alpha=alpha, method=method)
df['labels'] = y
df_mean = df.groupby('labels').mean().T
df_mean['F'] = F
df_mean['pval'] = pvals
return df_mean.sort_values(sort_by, ascending=True)
|
[
"Provide",
"signifance",
"for",
"features",
"in",
"dataset",
"with",
"anova",
"using",
"multiple",
"hypostesis",
"testing"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/data_utils.py#L80-L113
|
[
"def",
"feature_importance_report",
"(",
"X",
",",
"y",
",",
"threshold",
"=",
"0.001",
",",
"correcting_multiple_hypotesis",
"=",
"True",
",",
"method",
"=",
"'fdr_bh'",
",",
"alpha",
"=",
"0.1",
",",
"sort_by",
"=",
"'pval'",
")",
":",
"df",
"=",
"variance_threshold_on_df",
"(",
"pd",
".",
"DataFrame",
".",
"from_records",
"(",
"X",
")",
",",
"threshold",
"=",
"threshold",
")",
"F",
",",
"pvals",
"=",
"f_classif",
"(",
"df",
".",
"values",
",",
"y",
")",
"if",
"correcting_multiple_hypotesis",
":",
"_",
",",
"pvals",
",",
"_",
",",
"_",
"=",
"multipletests",
"(",
"pvals",
",",
"alpha",
"=",
"alpha",
",",
"method",
"=",
"method",
")",
"df",
"[",
"'labels'",
"]",
"=",
"y",
"df_mean",
"=",
"df",
".",
"groupby",
"(",
"'labels'",
")",
".",
"mean",
"(",
")",
".",
"T",
"df_mean",
"[",
"'F'",
"]",
"=",
"F",
"df_mean",
"[",
"'pval'",
"]",
"=",
"pvals",
"return",
"df_mean",
".",
"sort_values",
"(",
"sort_by",
",",
"ascending",
"=",
"True",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
SessionData.restore_data
|
Restore the data dict - update the flask session and this object
|
littlefish/sessiondata/framework.py
|
def restore_data(self, data_dict):
"""
Restore the data dict - update the flask session and this object
"""
session[self._base_key] = data_dict
self._data_dict = session[self._base_key]
|
def restore_data(self, data_dict):
"""
Restore the data dict - update the flask session and this object
"""
session[self._base_key] = data_dict
self._data_dict = session[self._base_key]
|
[
"Restore",
"the",
"data",
"dict",
"-",
"update",
"the",
"flask",
"session",
"and",
"this",
"object"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/sessiondata/framework.py#L119-L124
|
[
"def",
"restore_data",
"(",
"self",
",",
"data_dict",
")",
":",
"session",
"[",
"self",
".",
"_base_key",
"]",
"=",
"data_dict",
"self",
".",
"_data_dict",
"=",
"session",
"[",
"self",
".",
"_base_key",
"]"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
_mergedict
|
Recusively merge the 2 dicts.
Destructive on argument 'a'.
|
src/pyproxyfs/__init__.py
|
def _mergedict(a, b):
"""Recusively merge the 2 dicts.
Destructive on argument 'a'.
"""
for p, d1 in b.items():
if p in a:
if not isinstance(d1, dict):
continue
_mergedict(a[p], d1)
else:
a[p] = d1
return a
|
def _mergedict(a, b):
"""Recusively merge the 2 dicts.
Destructive on argument 'a'.
"""
for p, d1 in b.items():
if p in a:
if not isinstance(d1, dict):
continue
_mergedict(a[p], d1)
else:
a[p] = d1
return a
|
[
"Recusively",
"merge",
"the",
"2",
"dicts",
"."
] |
nicferrier/pyproxyfs
|
python
|
https://github.com/nicferrier/pyproxyfs/blob/7db09bb07bdeece56b7b1c4bf78c9f0b0a03c14b/src/pyproxyfs/__init__.py#L51-L63
|
[
"def",
"_mergedict",
"(",
"a",
",",
"b",
")",
":",
"for",
"p",
",",
"d1",
"in",
"b",
".",
"items",
"(",
")",
":",
"if",
"p",
"in",
"a",
":",
"if",
"not",
"isinstance",
"(",
"d1",
",",
"dict",
")",
":",
"continue",
"_mergedict",
"(",
"a",
"[",
"p",
"]",
",",
"d1",
")",
"else",
":",
"a",
"[",
"p",
"]",
"=",
"d1",
"return",
"a"
] |
7db09bb07bdeece56b7b1c4bf78c9f0b0a03c14b
|
test
|
multi
|
A decorator for a function to dispatch on.
The value returned by the dispatch function is used to look up the
implementation function based on its dispatch key.
The dispatch function is available using the `dispatch_fn` function.
|
dialogue/multi_method/__init__.py
|
def multi(dispatch_fn, default=None):
"""A decorator for a function to dispatch on.
The value returned by the dispatch function is used to look up the
implementation function based on its dispatch key.
The dispatch function is available using the `dispatch_fn` function.
"""
def _inner(*args, **kwargs):
dispatch_value = dispatch_fn(*args, **kwargs)
f = _inner.__multi__.get(dispatch_value, _inner.__multi_default__)
if f is None:
raise Exception(
f"No implementation of {dispatch_fn.__name__} "
f"for dispatch value {dispatch_value}"
)
return f(*args, **kwargs)
_inner.__multi__ = {}
_inner.__multi_default__ = default
_inner.__dispatch_fn__ = dispatch_fn
return _inner
|
def multi(dispatch_fn, default=None):
"""A decorator for a function to dispatch on.
The value returned by the dispatch function is used to look up the
implementation function based on its dispatch key.
The dispatch function is available using the `dispatch_fn` function.
"""
def _inner(*args, **kwargs):
dispatch_value = dispatch_fn(*args, **kwargs)
f = _inner.__multi__.get(dispatch_value, _inner.__multi_default__)
if f is None:
raise Exception(
f"No implementation of {dispatch_fn.__name__} "
f"for dispatch value {dispatch_value}"
)
return f(*args, **kwargs)
_inner.__multi__ = {}
_inner.__multi_default__ = default
_inner.__dispatch_fn__ = dispatch_fn
return _inner
|
[
"A",
"decorator",
"for",
"a",
"function",
"to",
"dispatch",
"on",
"."
] |
dialoguemd/multi-method
|
python
|
https://github.com/dialoguemd/multi-method/blob/8b405d4c5ad74a2a36a4ecf88283262defa2e737/dialogue/multi_method/__init__.py#L5-L27
|
[
"def",
"multi",
"(",
"dispatch_fn",
",",
"default",
"=",
"None",
")",
":",
"def",
"_inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dispatch_value",
"=",
"dispatch_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"f",
"=",
"_inner",
".",
"__multi__",
".",
"get",
"(",
"dispatch_value",
",",
"_inner",
".",
"__multi_default__",
")",
"if",
"f",
"is",
"None",
":",
"raise",
"Exception",
"(",
"f\"No implementation of {dispatch_fn.__name__} \"",
"f\"for dispatch value {dispatch_value}\"",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_inner",
".",
"__multi__",
"=",
"{",
"}",
"_inner",
".",
"__multi_default__",
"=",
"default",
"_inner",
".",
"__dispatch_fn__",
"=",
"dispatch_fn",
"return",
"_inner"
] |
8b405d4c5ad74a2a36a4ecf88283262defa2e737
|
test
|
method
|
A decorator for a function implementing dispatch_fn for dispatch_key.
If no dispatch_key is specified, the function is used as the
default dispacth function.
|
dialogue/multi_method/__init__.py
|
def method(dispatch_fn, dispatch_key=None):
"""A decorator for a function implementing dispatch_fn for dispatch_key.
If no dispatch_key is specified, the function is used as the
default dispacth function.
"""
def apply_decorator(fn):
if dispatch_key is None:
# Default case
dispatch_fn.__multi_default__ = fn
else:
dispatch_fn.__multi__[dispatch_key] = fn
return fn
return apply_decorator
|
def method(dispatch_fn, dispatch_key=None):
"""A decorator for a function implementing dispatch_fn for dispatch_key.
If no dispatch_key is specified, the function is used as the
default dispacth function.
"""
def apply_decorator(fn):
if dispatch_key is None:
# Default case
dispatch_fn.__multi_default__ = fn
else:
dispatch_fn.__multi__[dispatch_key] = fn
return fn
return apply_decorator
|
[
"A",
"decorator",
"for",
"a",
"function",
"implementing",
"dispatch_fn",
"for",
"dispatch_key",
"."
] |
dialoguemd/multi-method
|
python
|
https://github.com/dialoguemd/multi-method/blob/8b405d4c5ad74a2a36a4ecf88283262defa2e737/dialogue/multi_method/__init__.py#L30-L45
|
[
"def",
"method",
"(",
"dispatch_fn",
",",
"dispatch_key",
"=",
"None",
")",
":",
"def",
"apply_decorator",
"(",
"fn",
")",
":",
"if",
"dispatch_key",
"is",
"None",
":",
"# Default case",
"dispatch_fn",
".",
"__multi_default__",
"=",
"fn",
"else",
":",
"dispatch_fn",
".",
"__multi__",
"[",
"dispatch_key",
"]",
"=",
"fn",
"return",
"fn",
"return",
"apply_decorator"
] |
8b405d4c5ad74a2a36a4ecf88283262defa2e737
|
test
|
find_blocks
|
Auto-discover INSTALLED_APPS registered_blocks.py modules and fail
silently when not present. This forces an import on them thereby
registering their blocks.
This is a near 1-to-1 copy of how django's admin application registers
models.
|
streamfield_tools/registry.py
|
def find_blocks():
"""
Auto-discover INSTALLED_APPS registered_blocks.py modules and fail
silently when not present. This forces an import on them thereby
registering their blocks.
This is a near 1-to-1 copy of how django's admin application registers
models.
"""
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's sizedimage module.
try:
before_import_block_registry = copy.copy(
block_registry._registry
)
import_module('{}.registered_blocks'.format(app))
except:
# Reset the block_registry to the state before the last
# import as this import will have to reoccur on the next request
# and this could raise NotRegistered and AlreadyRegistered
# exceptions (see django ticket #8245).
block_registry._registry = before_import_block_registry
# Decide whether to bubble up this error. If the app just
# doesn't have a stuff module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'registered_blocks'):
raise
|
def find_blocks():
"""
Auto-discover INSTALLED_APPS registered_blocks.py modules and fail
silently when not present. This forces an import on them thereby
registering their blocks.
This is a near 1-to-1 copy of how django's admin application registers
models.
"""
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's sizedimage module.
try:
before_import_block_registry = copy.copy(
block_registry._registry
)
import_module('{}.registered_blocks'.format(app))
except:
# Reset the block_registry to the state before the last
# import as this import will have to reoccur on the next request
# and this could raise NotRegistered and AlreadyRegistered
# exceptions (see django ticket #8245).
block_registry._registry = before_import_block_registry
# Decide whether to bubble up this error. If the app just
# doesn't have a stuff module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'registered_blocks'):
raise
|
[
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"registered_blocks",
".",
"py",
"modules",
"and",
"fail",
"silently",
"when",
"not",
"present",
".",
"This",
"forces",
"an",
"import",
"on",
"them",
"thereby",
"registering",
"their",
"blocks",
"."
] |
WGBH/wagtail-streamfieldtools
|
python
|
https://github.com/WGBH/wagtail-streamfieldtools/blob/192f86845532742b0b7d432bef3987357833b8ed/streamfield_tools/registry.py#L78-L107
|
[
"def",
"find_blocks",
"(",
")",
":",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"mod",
"=",
"import_module",
"(",
"app",
")",
"# Attempt to import the app's sizedimage module.",
"try",
":",
"before_import_block_registry",
"=",
"copy",
".",
"copy",
"(",
"block_registry",
".",
"_registry",
")",
"import_module",
"(",
"'{}.registered_blocks'",
".",
"format",
"(",
"app",
")",
")",
"except",
":",
"# Reset the block_registry to the state before the last",
"# import as this import will have to reoccur on the next request",
"# and this could raise NotRegistered and AlreadyRegistered",
"# exceptions (see django ticket #8245).",
"block_registry",
".",
"_registry",
"=",
"before_import_block_registry",
"# Decide whether to bubble up this error. If the app just",
"# doesn't have a stuff module, we can ignore the error",
"# attempting to import it, otherwise we want it to bubble up.",
"if",
"module_has_submodule",
"(",
"mod",
",",
"'registered_blocks'",
")",
":",
"raise"
] |
192f86845532742b0b7d432bef3987357833b8ed
|
test
|
RegisteredBlockStreamFieldRegistry._verify_block
|
Verifies a block prior to registration.
|
streamfield_tools/registry.py
|
def _verify_block(self, block_type, block):
"""
Verifies a block prior to registration.
"""
if block_type in self._registry:
raise AlreadyRegistered(
"A block has already been registered to the {} `block_type` "
"in the registry. Either unregister that block before trying "
"to register this block under a different `block_type`".format(
block_type
)
)
if not isinstance(block, Block):
raise InvalidBlock(
"The block you tried register to {} is invalid. Only "
"instances of `wagtail.wagtailcore.blocks.Block` may be "
"registered with the the block_registry.".format(block_type)
)
|
def _verify_block(self, block_type, block):
"""
Verifies a block prior to registration.
"""
if block_type in self._registry:
raise AlreadyRegistered(
"A block has already been registered to the {} `block_type` "
"in the registry. Either unregister that block before trying "
"to register this block under a different `block_type`".format(
block_type
)
)
if not isinstance(block, Block):
raise InvalidBlock(
"The block you tried register to {} is invalid. Only "
"instances of `wagtail.wagtailcore.blocks.Block` may be "
"registered with the the block_registry.".format(block_type)
)
|
[
"Verifies",
"a",
"block",
"prior",
"to",
"registration",
"."
] |
WGBH/wagtail-streamfieldtools
|
python
|
https://github.com/WGBH/wagtail-streamfieldtools/blob/192f86845532742b0b7d432bef3987357833b8ed/streamfield_tools/registry.py#L32-L49
|
[
"def",
"_verify_block",
"(",
"self",
",",
"block_type",
",",
"block",
")",
":",
"if",
"block_type",
"in",
"self",
".",
"_registry",
":",
"raise",
"AlreadyRegistered",
"(",
"\"A block has already been registered to the {} `block_type` \"",
"\"in the registry. Either unregister that block before trying \"",
"\"to register this block under a different `block_type`\"",
".",
"format",
"(",
"block_type",
")",
")",
"if",
"not",
"isinstance",
"(",
"block",
",",
"Block",
")",
":",
"raise",
"InvalidBlock",
"(",
"\"The block you tried register to {} is invalid. Only \"",
"\"instances of `wagtail.wagtailcore.blocks.Block` may be \"",
"\"registered with the the block_registry.\"",
".",
"format",
"(",
"block_type",
")",
")"
] |
192f86845532742b0b7d432bef3987357833b8ed
|
test
|
RegisteredBlockStreamFieldRegistry.register_block
|
Registers `block` to `block_type` in the registry.
|
streamfield_tools/registry.py
|
def register_block(self, block_type, block):
"""
Registers `block` to `block_type` in the registry.
"""
self._verify_block(block_type, block)
self._registry[block_type] = block
|
def register_block(self, block_type, block):
"""
Registers `block` to `block_type` in the registry.
"""
self._verify_block(block_type, block)
self._registry[block_type] = block
|
[
"Registers",
"block",
"to",
"block_type",
"in",
"the",
"registry",
"."
] |
WGBH/wagtail-streamfieldtools
|
python
|
https://github.com/WGBH/wagtail-streamfieldtools/blob/192f86845532742b0b7d432bef3987357833b8ed/streamfield_tools/registry.py#L51-L57
|
[
"def",
"register_block",
"(",
"self",
",",
"block_type",
",",
"block",
")",
":",
"self",
".",
"_verify_block",
"(",
"block_type",
",",
"block",
")",
"self",
".",
"_registry",
"[",
"block_type",
"]",
"=",
"block"
] |
192f86845532742b0b7d432bef3987357833b8ed
|
test
|
RegisteredBlockStreamFieldRegistry.unregister_block
|
Unregisters the block associated with `block_type` from the registry.
If no block is registered to `block_type`, NotRegistered will raise.
|
streamfield_tools/registry.py
|
def unregister_block(self, block_type):
"""
Unregisters the block associated with `block_type` from the registry.
If no block is registered to `block_type`, NotRegistered will raise.
"""
if block_type not in self._registry:
raise NotRegistered(
'There is no block registered as "{}" with the '
'RegisteredBlockStreamFieldRegistry registry.'.format(
block_type
)
)
else:
del self._registry[block_type]
|
def unregister_block(self, block_type):
"""
Unregisters the block associated with `block_type` from the registry.
If no block is registered to `block_type`, NotRegistered will raise.
"""
if block_type not in self._registry:
raise NotRegistered(
'There is no block registered as "{}" with the '
'RegisteredBlockStreamFieldRegistry registry.'.format(
block_type
)
)
else:
del self._registry[block_type]
|
[
"Unregisters",
"the",
"block",
"associated",
"with",
"block_type",
"from",
"the",
"registry",
"."
] |
WGBH/wagtail-streamfieldtools
|
python
|
https://github.com/WGBH/wagtail-streamfieldtools/blob/192f86845532742b0b7d432bef3987357833b8ed/streamfield_tools/registry.py#L59-L73
|
[
"def",
"unregister_block",
"(",
"self",
",",
"block_type",
")",
":",
"if",
"block_type",
"not",
"in",
"self",
".",
"_registry",
":",
"raise",
"NotRegistered",
"(",
"'There is no block registered as \"{}\" with the '",
"'RegisteredBlockStreamFieldRegistry registry.'",
".",
"format",
"(",
"block_type",
")",
")",
"else",
":",
"del",
"self",
".",
"_registry",
"[",
"block_type",
"]"
] |
192f86845532742b0b7d432bef3987357833b8ed
|
test
|
convert_to_mp3
|
Converts the file associated with the file_name passed into a MP3 file.
:param str file_name: Filename of the original file in local storage
:param Queue delete_queue: Delete queue to add the original file to after conversion is done
:return str: Filename of the new file in local storage
|
music2storage/helpers.py
|
def convert_to_mp3(file_name, delete_queue):
"""
Converts the file associated with the file_name passed into a MP3 file.
:param str file_name: Filename of the original file in local storage
:param Queue delete_queue: Delete queue to add the original file to after conversion is done
:return str: Filename of the new file in local storage
"""
file = os.path.splitext(file_name)
if file[1] == '.mp3':
log.info(f"{file_name} is already a MP3 file, no conversion needed.")
return file_name
new_file_name = file[0] + '.mp3'
ff = FFmpeg(
inputs={file_name: None},
outputs={new_file_name: None}
)
log.info(f"Conversion for {file_name} has started")
start_time = time()
try:
ff.run(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FFRuntimeError:
os.remove(new_file_name)
ff.run(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
end_time = time()
log.info(f"Conversion for {file_name} has finished in {end_time - start_time} seconds")
delete_queue.put(file_name)
return new_file_name
|
def convert_to_mp3(file_name, delete_queue):
"""
Converts the file associated with the file_name passed into a MP3 file.
:param str file_name: Filename of the original file in local storage
:param Queue delete_queue: Delete queue to add the original file to after conversion is done
:return str: Filename of the new file in local storage
"""
file = os.path.splitext(file_name)
if file[1] == '.mp3':
log.info(f"{file_name} is already a MP3 file, no conversion needed.")
return file_name
new_file_name = file[0] + '.mp3'
ff = FFmpeg(
inputs={file_name: None},
outputs={new_file_name: None}
)
log.info(f"Conversion for {file_name} has started")
start_time = time()
try:
ff.run(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FFRuntimeError:
os.remove(new_file_name)
ff.run(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
end_time = time()
log.info(f"Conversion for {file_name} has finished in {end_time - start_time} seconds")
delete_queue.put(file_name)
return new_file_name
|
[
"Converts",
"the",
"file",
"associated",
"with",
"the",
"file_name",
"passed",
"into",
"a",
"MP3",
"file",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/helpers.py#L12-L46
|
[
"def",
"convert_to_mp3",
"(",
"file_name",
",",
"delete_queue",
")",
":",
"file",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"if",
"file",
"[",
"1",
"]",
"==",
"'.mp3'",
":",
"log",
".",
"info",
"(",
"f\"{file_name} is already a MP3 file, no conversion needed.\"",
")",
"return",
"file_name",
"new_file_name",
"=",
"file",
"[",
"0",
"]",
"+",
"'.mp3'",
"ff",
"=",
"FFmpeg",
"(",
"inputs",
"=",
"{",
"file_name",
":",
"None",
"}",
",",
"outputs",
"=",
"{",
"new_file_name",
":",
"None",
"}",
")",
"log",
".",
"info",
"(",
"f\"Conversion for {file_name} has started\"",
")",
"start_time",
"=",
"time",
"(",
")",
"try",
":",
"ff",
".",
"run",
"(",
"stdout",
"=",
"subprocess",
".",
"DEVNULL",
",",
"stderr",
"=",
"subprocess",
".",
"DEVNULL",
")",
"except",
"FFRuntimeError",
":",
"os",
".",
"remove",
"(",
"new_file_name",
")",
"ff",
".",
"run",
"(",
"stdout",
"=",
"subprocess",
".",
"DEVNULL",
",",
"stderr",
"=",
"subprocess",
".",
"DEVNULL",
")",
"end_time",
"=",
"time",
"(",
")",
"log",
".",
"info",
"(",
"f\"Conversion for {file_name} has finished in {end_time - start_time} seconds\"",
")",
"delete_queue",
".",
"put",
"(",
"file_name",
")",
"return",
"new_file_name"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
delete_local_file
|
Deletes the file associated with the file_name passed from local storage.
:param str file_name: Filename of the file to be deleted
:return str: Filename of the file that was just deleted
|
music2storage/helpers.py
|
def delete_local_file(file_name):
"""
Deletes the file associated with the file_name passed from local storage.
:param str file_name: Filename of the file to be deleted
:return str: Filename of the file that was just deleted
"""
try:
os.remove(file_name)
log.info(f"Deletion for {file_name} has finished")
return file_name
except OSError:
pass
|
def delete_local_file(file_name):
"""
Deletes the file associated with the file_name passed from local storage.
:param str file_name: Filename of the file to be deleted
:return str: Filename of the file that was just deleted
"""
try:
os.remove(file_name)
log.info(f"Deletion for {file_name} has finished")
return file_name
except OSError:
pass
|
[
"Deletes",
"the",
"file",
"associated",
"with",
"the",
"file_name",
"passed",
"from",
"local",
"storage",
".",
":",
"param",
"str",
"file_name",
":",
"Filename",
"of",
"the",
"file",
"to",
"be",
"deleted",
":",
"return",
"str",
":",
"Filename",
"of",
"the",
"file",
"that",
"was",
"just",
"deleted"
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/helpers.py#L49-L62
|
[
"def",
"delete_local_file",
"(",
"file_name",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"file_name",
")",
"log",
".",
"info",
"(",
"f\"Deletion for {file_name} has finished\"",
")",
"return",
"file_name",
"except",
"OSError",
":",
"pass"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
cli
|
通用自动化处理工具
详情参考 `GitHub <https://github.com/littlemo/mohand>`_
|
source/mohand/main.py
|
def cli(*args, **kwargs):
"""
通用自动化处理工具
详情参考 `GitHub <https://github.com/littlemo/mohand>`_
"""
log.debug('cli: {} {}'.format(args, kwargs))
# 使用终端传入的 option 更新 env 中的配置值
env.update(kwargs)
|
def cli(*args, **kwargs):
"""
通用自动化处理工具
详情参考 `GitHub <https://github.com/littlemo/mohand>`_
"""
log.debug('cli: {} {}'.format(args, kwargs))
# 使用终端传入的 option 更新 env 中的配置值
env.update(kwargs)
|
[
"通用自动化处理工具"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/main.py#L86-L95
|
[
"def",
"cli",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"'cli: {} {}'",
".",
"format",
"(",
"args",
",",
"kwargs",
")",
")",
"# 使用终端传入的 option 更新 env 中的配置值",
"env",
".",
"update",
"(",
"kwargs",
")"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
_is_package
|
判断传入的路径是否为一个 Python 模块包
:param str path: 待判断的路径
:return: 返回是,则传入 path 为一个 Python 包,否则不是
:rtype: bool
|
source/mohand/load_file.py
|
def _is_package(path):
"""
判断传入的路径是否为一个 Python 模块包
:param str path: 待判断的路径
:return: 返回是,则传入 path 为一个 Python 包,否则不是
:rtype: bool
"""
def _exists(s):
return os.path.exists(os.path.join(path, s))
return (
os.path.isdir(path) and
(_exists('__init__.py') or _exists('__init__.pyc'))
)
|
def _is_package(path):
"""
判断传入的路径是否为一个 Python 模块包
:param str path: 待判断的路径
:return: 返回是,则传入 path 为一个 Python 包,否则不是
:rtype: bool
"""
def _exists(s):
return os.path.exists(os.path.join(path, s))
return (
os.path.isdir(path) and
(_exists('__init__.py') or _exists('__init__.pyc'))
)
|
[
"判断传入的路径是否为一个",
"Python",
"模块包"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/load_file.py#L11-L25
|
[
"def",
"_is_package",
"(",
"path",
")",
":",
"def",
"_exists",
"(",
"s",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"s",
")",
")",
"return",
"(",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"and",
"(",
"_exists",
"(",
"'__init__.py'",
")",
"or",
"_exists",
"(",
"'__init__.pyc'",
")",
")",
")"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
find_handfile
|
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
|
source/mohand/load_file.py
|
def find_handfile(names=None):
"""
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
"""
# 如果没有明确指定,则包含 env 中的值
names = names or [env.handfile]
# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾
if not names[0].endswith('.py'):
names += [names[0] + '.py']
# name 中是否包含路径元素
if os.path.dirname(names[0]):
# 若存在,则扩展 Home 路径标志,并测试是否存在
for name in names:
expanded = os.path.expanduser(name)
if os.path.exists(expanded):
if name.endswith('.py') or _is_package(expanded):
return os.path.abspath(expanded)
else:
# 否则,逐级向上搜索,直到根路径
path = '.'
# 在到系统根路径之前停止
while os.path.split(os.path.abspath(path))[1]:
for name in names:
joined = os.path.join(path, name)
if os.path.exists(joined):
if name.endswith('.py') or _is_package(joined):
return os.path.abspath(joined)
path = os.path.join('..', path)
return None
|
def find_handfile(names=None):
"""
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
"""
# 如果没有明确指定,则包含 env 中的值
names = names or [env.handfile]
# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾
if not names[0].endswith('.py'):
names += [names[0] + '.py']
# name 中是否包含路径元素
if os.path.dirname(names[0]):
# 若存在,则扩展 Home 路径标志,并测试是否存在
for name in names:
expanded = os.path.expanduser(name)
if os.path.exists(expanded):
if name.endswith('.py') or _is_package(expanded):
return os.path.abspath(expanded)
else:
# 否则,逐级向上搜索,直到根路径
path = '.'
# 在到系统根路径之前停止
while os.path.split(os.path.abspath(path))[1]:
for name in names:
joined = os.path.join(path, name)
if os.path.exists(joined):
if name.endswith('.py') or _is_package(joined):
return os.path.abspath(joined)
path = os.path.join('..', path)
return None
|
[
"尝试定位",
"handfile",
"文件,明确指定或逐级搜索父路径"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/load_file.py#L28-L64
|
[
"def",
"find_handfile",
"(",
"names",
"=",
"None",
")",
":",
"# 如果没有明确指定,则包含 env 中的值",
"names",
"=",
"names",
"or",
"[",
"env",
".",
"handfile",
"]",
"# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾",
"if",
"not",
"names",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.py'",
")",
":",
"names",
"+=",
"[",
"names",
"[",
"0",
"]",
"+",
"'.py'",
"]",
"# name 中是否包含路径元素",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"names",
"[",
"0",
"]",
")",
":",
"# 若存在,则扩展 Home 路径标志,并测试是否存在",
"for",
"name",
"in",
"names",
":",
"expanded",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"expanded",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'.py'",
")",
"or",
"_is_package",
"(",
"expanded",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"expanded",
")",
"else",
":",
"# 否则,逐级向上搜索,直到根路径",
"path",
"=",
"'.'",
"# 在到系统根路径之前停止",
"while",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"[",
"1",
"]",
":",
"for",
"name",
"in",
"names",
":",
"joined",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"joined",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'.py'",
")",
"or",
"_is_package",
"(",
"joined",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"joined",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'..'",
",",
"path",
")",
"return",
"None"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
get_commands_from_module
|
从传入的 ``imported`` 中获取所有 ``click.core.Command``
:param module imported: 导入的Python包
:return: 包描述文档,仅含终端命令函数的对象字典
:rtype: (str, dict(str, object))
|
source/mohand/load_file.py
|
def get_commands_from_module(imported):
"""
从传入的 ``imported`` 中获取所有 ``click.core.Command``
:param module imported: 导入的Python包
:return: 包描述文档,仅含终端命令函数的对象字典
:rtype: (str, dict(str, object))
"""
# 如果存在 <module>.__all__ ,则遵守
imported_vars = vars(imported)
if "__all__" in imported_vars:
imported_vars = [
(name, imported_vars[name]) for name in
imported_vars if name in imported_vars["__all__"]]
else:
imported_vars = imported_vars.items()
cmd_dict = extract_commands(imported_vars)
return imported.__doc__, cmd_dict
|
def get_commands_from_module(imported):
"""
从传入的 ``imported`` 中获取所有 ``click.core.Command``
:param module imported: 导入的Python包
:return: 包描述文档,仅含终端命令函数的对象字典
:rtype: (str, dict(str, object))
"""
# 如果存在 <module>.__all__ ,则遵守
imported_vars = vars(imported)
if "__all__" in imported_vars:
imported_vars = [
(name, imported_vars[name]) for name in
imported_vars if name in imported_vars["__all__"]]
else:
imported_vars = imported_vars.items()
cmd_dict = extract_commands(imported_vars)
return imported.__doc__, cmd_dict
|
[
"从传入的",
"imported",
"中获取所有",
"click",
".",
"core",
".",
"Command"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/load_file.py#L67-L85
|
[
"def",
"get_commands_from_module",
"(",
"imported",
")",
":",
"# 如果存在 <module>.__all__ ,则遵守",
"imported_vars",
"=",
"vars",
"(",
"imported",
")",
"if",
"\"__all__\"",
"in",
"imported_vars",
":",
"imported_vars",
"=",
"[",
"(",
"name",
",",
"imported_vars",
"[",
"name",
"]",
")",
"for",
"name",
"in",
"imported_vars",
"if",
"name",
"in",
"imported_vars",
"[",
"\"__all__\"",
"]",
"]",
"else",
":",
"imported_vars",
"=",
"imported_vars",
".",
"items",
"(",
")",
"cmd_dict",
"=",
"extract_commands",
"(",
"imported_vars",
")",
"return",
"imported",
".",
"__doc__",
",",
"cmd_dict"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
extract_commands
|
从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object)
|
source/mohand/load_file.py
|
def extract_commands(imported_vars):
"""
从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object)
"""
commands = dict()
for tup in imported_vars:
name, obj = tup
if is_command_object(obj):
commands.setdefault(name, obj)
return commands
|
def extract_commands(imported_vars):
"""
从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object)
"""
commands = dict()
for tup in imported_vars:
name, obj = tup
if is_command_object(obj):
commands.setdefault(name, obj)
return commands
|
[
"从传入的变量列表中提取命令",
"(",
"click",
".",
"core",
".",
"Command",
")",
"对象"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/load_file.py#L99-L112
|
[
"def",
"extract_commands",
"(",
"imported_vars",
")",
":",
"commands",
"=",
"dict",
"(",
")",
"for",
"tup",
"in",
"imported_vars",
":",
"name",
",",
"obj",
"=",
"tup",
"if",
"is_command_object",
"(",
"obj",
")",
":",
"commands",
".",
"setdefault",
"(",
"name",
",",
"obj",
")",
"return",
"commands"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
load_handfile
|
导入传入的 ``handfile`` 文件路径,并返回(docstring, callables)
也就是 handfile 包的 ``__doc__`` 属性 (字符串) 和一个 ``{'name': callable}``
的字典,包含所有通过 mohand 的 command 测试的 callables
:param str path: 待导入的 handfile 文件路径
:param function importer: 可选,包导入函数,默认为 ``__import__``
:return: 包描述文档,仅含终端命令函数的对象字典
:rtype: (str, dict(str, object))
|
source/mohand/load_file.py
|
def load_handfile(path, importer=None):
"""
导入传入的 ``handfile`` 文件路径,并返回(docstring, callables)
也就是 handfile 包的 ``__doc__`` 属性 (字符串) 和一个 ``{'name': callable}``
的字典,包含所有通过 mohand 的 command 测试的 callables
:param str path: 待导入的 handfile 文件路径
:param function importer: 可选,包导入函数,默认为 ``__import__``
:return: 包描述文档,仅含终端命令函数的对象字典
:rtype: (str, dict(str, object))
"""
if importer is None:
importer = __import__
# 获取路径&文件名
directory, handfile = os.path.split(path)
# 如果路径不在 ``PYTHONPATH`` 中,则添加,以便于我们的导入正常工作
added_to_path = False
index = None
if directory not in sys.path:
sys.path.insert(0, directory)
added_to_path = True
# 如果路径在 ``PYTHONPATH`` 中,则临时将其移到最前,否则其他的 ``handfile``
# 文件将会被优先导入,而不是我们想要导入的那个
else:
i = sys.path.index(directory)
if i != 0:
# 为之后的恢复保存索引号
index = i
# 添加到最前,然后删除原始位置
sys.path.insert(0, directory)
del sys.path[i + 1]
# 执行导入(去除 .py 扩展名)
sys_byte_code_bak = sys.dont_write_bytecode
sys.dont_write_bytecode = True
imported = importer(os.path.splitext(handfile)[0])
sys.dont_write_bytecode = sys_byte_code_bak
# 从 ``PYTHONPATH`` 中移除我们自己添加的路径
# (仅仅出于严谨,尽量不污染 ``PYTHONPATH`` )
if added_to_path:
del sys.path[0]
# 将我们移动的 PATH 放回原处
if index is not None:
sys.path.insert(index + 1, directory)
del sys.path[0]
# 实际加载 Command
docstring, commands = get_commands_from_module(imported)
return docstring, commands
|
def load_handfile(path, importer=None):
"""
导入传入的 ``handfile`` 文件路径,并返回(docstring, callables)
也就是 handfile 包的 ``__doc__`` 属性 (字符串) 和一个 ``{'name': callable}``
的字典,包含所有通过 mohand 的 command 测试的 callables
:param str path: 待导入的 handfile 文件路径
:param function importer: 可选,包导入函数,默认为 ``__import__``
:return: 包描述文档,仅含终端命令函数的对象字典
:rtype: (str, dict(str, object))
"""
if importer is None:
importer = __import__
# 获取路径&文件名
directory, handfile = os.path.split(path)
# 如果路径不在 ``PYTHONPATH`` 中,则添加,以便于我们的导入正常工作
added_to_path = False
index = None
if directory not in sys.path:
sys.path.insert(0, directory)
added_to_path = True
# 如果路径在 ``PYTHONPATH`` 中,则临时将其移到最前,否则其他的 ``handfile``
# 文件将会被优先导入,而不是我们想要导入的那个
else:
i = sys.path.index(directory)
if i != 0:
# 为之后的恢复保存索引号
index = i
# 添加到最前,然后删除原始位置
sys.path.insert(0, directory)
del sys.path[i + 1]
# 执行导入(去除 .py 扩展名)
sys_byte_code_bak = sys.dont_write_bytecode
sys.dont_write_bytecode = True
imported = importer(os.path.splitext(handfile)[0])
sys.dont_write_bytecode = sys_byte_code_bak
# 从 ``PYTHONPATH`` 中移除我们自己添加的路径
# (仅仅出于严谨,尽量不污染 ``PYTHONPATH`` )
if added_to_path:
del sys.path[0]
# 将我们移动的 PATH 放回原处
if index is not None:
sys.path.insert(index + 1, directory)
del sys.path[0]
# 实际加载 Command
docstring, commands = get_commands_from_module(imported)
return docstring, commands
|
[
"导入传入的",
"handfile",
"文件路径,并返回",
"(",
"docstring",
"callables",
")"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/load_file.py#L115-L170
|
[
"def",
"load_handfile",
"(",
"path",
",",
"importer",
"=",
"None",
")",
":",
"if",
"importer",
"is",
"None",
":",
"importer",
"=",
"__import__",
"# 获取路径&文件名",
"directory",
",",
"handfile",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"# 如果路径不在 ``PYTHONPATH`` 中,则添加,以便于我们的导入正常工作",
"added_to_path",
"=",
"False",
"index",
"=",
"None",
"if",
"directory",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"directory",
")",
"added_to_path",
"=",
"True",
"# 如果路径在 ``PYTHONPATH`` 中,则临时将其移到最前,否则其他的 ``handfile``",
"# 文件将会被优先导入,而不是我们想要导入的那个",
"else",
":",
"i",
"=",
"sys",
".",
"path",
".",
"index",
"(",
"directory",
")",
"if",
"i",
"!=",
"0",
":",
"# 为之后的恢复保存索引号",
"index",
"=",
"i",
"# 添加到最前,然后删除原始位置",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"directory",
")",
"del",
"sys",
".",
"path",
"[",
"i",
"+",
"1",
"]",
"# 执行导入(去除 .py 扩展名)",
"sys_byte_code_bak",
"=",
"sys",
".",
"dont_write_bytecode",
"sys",
".",
"dont_write_bytecode",
"=",
"True",
"imported",
"=",
"importer",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"handfile",
")",
"[",
"0",
"]",
")",
"sys",
".",
"dont_write_bytecode",
"=",
"sys_byte_code_bak",
"# 从 ``PYTHONPATH`` 中移除我们自己添加的路径",
"# (仅仅出于严谨,尽量不污染 ``PYTHONPATH`` )",
"if",
"added_to_path",
":",
"del",
"sys",
".",
"path",
"[",
"0",
"]",
"# 将我们移动的 PATH 放回原处",
"if",
"index",
"is",
"not",
"None",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"index",
"+",
"1",
",",
"directory",
")",
"del",
"sys",
".",
"path",
"[",
"0",
"]",
"# 实际加载 Command",
"docstring",
",",
"commands",
"=",
"get_commands_from_module",
"(",
"imported",
")",
"return",
"docstring",
",",
"commands"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
GitReleaseChecks.reasonable_desired_version
|
Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next version name
|
autorelease/git_repo_checks.py
|
def reasonable_desired_version(self, desired_version, allow_equal=False,
allow_patch_skip=False):
"""
Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next version name
"""
try:
desired_version = desired_version.base_version
except:
pass
(new_major, new_minor, new_patch) = \
map(int, desired_version.split('.'))
tag_versions = self._versions_from_tags()
if not tag_versions:
# no tags yet, and legal version is legal!
return ""
max_version = max(self._versions_from_tags()).base_version
(old_major, old_minor, old_patch) = \
map(int, str(max_version).split('.'))
update_str = str(max_version) + " -> " + str(desired_version)
v_desired = vers.Version(desired_version)
v_max = vers.Version(max_version)
if allow_equal and v_desired == v_max:
return ""
if v_desired < v_max:
return ("Bad update: New version doesn't increase on last tag: "
+ update_str + "\n")
bad_update = skipped_version((old_major, old_minor, old_patch),
(new_major, new_minor, new_patch),
allow_patch_skip)
msg = ""
if bad_update:
msg = ("Bad update: Did you skip a version from "
+ update_str + "?\n")
return msg
|
def reasonable_desired_version(self, desired_version, allow_equal=False,
allow_patch_skip=False):
"""
Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next version name
"""
try:
desired_version = desired_version.base_version
except:
pass
(new_major, new_minor, new_patch) = \
map(int, desired_version.split('.'))
tag_versions = self._versions_from_tags()
if not tag_versions:
# no tags yet, and legal version is legal!
return ""
max_version = max(self._versions_from_tags()).base_version
(old_major, old_minor, old_patch) = \
map(int, str(max_version).split('.'))
update_str = str(max_version) + " -> " + str(desired_version)
v_desired = vers.Version(desired_version)
v_max = vers.Version(max_version)
if allow_equal and v_desired == v_max:
return ""
if v_desired < v_max:
return ("Bad update: New version doesn't increase on last tag: "
+ update_str + "\n")
bad_update = skipped_version((old_major, old_minor, old_patch),
(new_major, new_minor, new_patch),
allow_patch_skip)
msg = ""
if bad_update:
msg = ("Bad update: Did you skip a version from "
+ update_str + "?\n")
return msg
|
[
"Determine",
"whether",
"the",
"desired",
"version",
"is",
"a",
"reasonable",
"next",
"version",
"."
] |
dwhswenson/autorelease
|
python
|
https://github.com/dwhswenson/autorelease/blob/339c32c3934e4751857f35aaa2bfffaaaf3b39c4/autorelease/git_repo_checks.py#L50-L96
|
[
"def",
"reasonable_desired_version",
"(",
"self",
",",
"desired_version",
",",
"allow_equal",
"=",
"False",
",",
"allow_patch_skip",
"=",
"False",
")",
":",
"try",
":",
"desired_version",
"=",
"desired_version",
".",
"base_version",
"except",
":",
"pass",
"(",
"new_major",
",",
"new_minor",
",",
"new_patch",
")",
"=",
"map",
"(",
"int",
",",
"desired_version",
".",
"split",
"(",
"'.'",
")",
")",
"tag_versions",
"=",
"self",
".",
"_versions_from_tags",
"(",
")",
"if",
"not",
"tag_versions",
":",
"# no tags yet, and legal version is legal!",
"return",
"\"\"",
"max_version",
"=",
"max",
"(",
"self",
".",
"_versions_from_tags",
"(",
")",
")",
".",
"base_version",
"(",
"old_major",
",",
"old_minor",
",",
"old_patch",
")",
"=",
"map",
"(",
"int",
",",
"str",
"(",
"max_version",
")",
".",
"split",
"(",
"'.'",
")",
")",
"update_str",
"=",
"str",
"(",
"max_version",
")",
"+",
"\" -> \"",
"+",
"str",
"(",
"desired_version",
")",
"v_desired",
"=",
"vers",
".",
"Version",
"(",
"desired_version",
")",
"v_max",
"=",
"vers",
".",
"Version",
"(",
"max_version",
")",
"if",
"allow_equal",
"and",
"v_desired",
"==",
"v_max",
":",
"return",
"\"\"",
"if",
"v_desired",
"<",
"v_max",
":",
"return",
"(",
"\"Bad update: New version doesn't increase on last tag: \"",
"+",
"update_str",
"+",
"\"\\n\"",
")",
"bad_update",
"=",
"skipped_version",
"(",
"(",
"old_major",
",",
"old_minor",
",",
"old_patch",
")",
",",
"(",
"new_major",
",",
"new_minor",
",",
"new_patch",
")",
",",
"allow_patch_skip",
")",
"msg",
"=",
"\"\"",
"if",
"bad_update",
":",
"msg",
"=",
"(",
"\"Bad update: Did you skip a version from \"",
"+",
"update_str",
"+",
"\"?\\n\"",
")",
"return",
"msg"
] |
339c32c3934e4751857f35aaa2bfffaaaf3b39c4
|
test
|
handle_ssl_redirect
|
Check if a route needs ssl, and redirect it if not. Also redirects back to http for non-ssl routes. Static routes
are served as both http and https
:return: A response to be returned or None
|
littlefish/sslutil.py
|
def handle_ssl_redirect():
"""
Check if a route needs ssl, and redirect it if not. Also redirects back to http for non-ssl routes. Static routes
are served as both http and https
:return: A response to be returned or None
"""
if request.endpoint and request.endpoint not in ['static', 'filemanager.static']:
needs_ssl = False
ssl_enabled = False
view_function = current_app.view_functions[request.endpoint]
if request.endpoint.startswith('admin.') or \
(hasattr(view_function, 'ssl_required') and view_function.ssl_required):
needs_ssl = True
ssl_enabled = True
if hasattr(view_function, 'ssl_allowed') and view_function.ssl_allowed:
ssl_enabled = True
if (hasattr(view_function, 'ssl_disabled') and view_function.ssl_disabled):
needs_ssl = False
ssl_enabled = False
if current_app.config['SSL_ENABLED']:
if needs_ssl and not request.is_secure:
log.debug('Redirecting to https: %s' % request.endpoint)
return redirect(request.url.replace("http://", "https://"))
elif not ssl_enabled and request.is_secure:
log.debug('Redirecting to http: %s' % request.endpoint)
return redirect(request.url.replace("https://", "http://"))
elif needs_ssl:
log.info('Not redirecting to HTTPS for endpoint %s as SSL_ENABLED is set to False' % request.endpoint)
|
def handle_ssl_redirect():
"""
Check if a route needs ssl, and redirect it if not. Also redirects back to http for non-ssl routes. Static routes
are served as both http and https
:return: A response to be returned or None
"""
if request.endpoint and request.endpoint not in ['static', 'filemanager.static']:
needs_ssl = False
ssl_enabled = False
view_function = current_app.view_functions[request.endpoint]
if request.endpoint.startswith('admin.') or \
(hasattr(view_function, 'ssl_required') and view_function.ssl_required):
needs_ssl = True
ssl_enabled = True
if hasattr(view_function, 'ssl_allowed') and view_function.ssl_allowed:
ssl_enabled = True
if (hasattr(view_function, 'ssl_disabled') and view_function.ssl_disabled):
needs_ssl = False
ssl_enabled = False
if current_app.config['SSL_ENABLED']:
if needs_ssl and not request.is_secure:
log.debug('Redirecting to https: %s' % request.endpoint)
return redirect(request.url.replace("http://", "https://"))
elif not ssl_enabled and request.is_secure:
log.debug('Redirecting to http: %s' % request.endpoint)
return redirect(request.url.replace("https://", "http://"))
elif needs_ssl:
log.info('Not redirecting to HTTPS for endpoint %s as SSL_ENABLED is set to False' % request.endpoint)
|
[
"Check",
"if",
"a",
"route",
"needs",
"ssl",
"and",
"redirect",
"it",
"if",
"not",
".",
"Also",
"redirects",
"back",
"to",
"http",
"for",
"non",
"-",
"ssl",
"routes",
".",
"Static",
"routes",
"are",
"served",
"as",
"both",
"http",
"and",
"https"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/sslutil.py#L44-L75
|
[
"def",
"handle_ssl_redirect",
"(",
")",
":",
"if",
"request",
".",
"endpoint",
"and",
"request",
".",
"endpoint",
"not",
"in",
"[",
"'static'",
",",
"'filemanager.static'",
"]",
":",
"needs_ssl",
"=",
"False",
"ssl_enabled",
"=",
"False",
"view_function",
"=",
"current_app",
".",
"view_functions",
"[",
"request",
".",
"endpoint",
"]",
"if",
"request",
".",
"endpoint",
".",
"startswith",
"(",
"'admin.'",
")",
"or",
"(",
"hasattr",
"(",
"view_function",
",",
"'ssl_required'",
")",
"and",
"view_function",
".",
"ssl_required",
")",
":",
"needs_ssl",
"=",
"True",
"ssl_enabled",
"=",
"True",
"if",
"hasattr",
"(",
"view_function",
",",
"'ssl_allowed'",
")",
"and",
"view_function",
".",
"ssl_allowed",
":",
"ssl_enabled",
"=",
"True",
"if",
"(",
"hasattr",
"(",
"view_function",
",",
"'ssl_disabled'",
")",
"and",
"view_function",
".",
"ssl_disabled",
")",
":",
"needs_ssl",
"=",
"False",
"ssl_enabled",
"=",
"False",
"if",
"current_app",
".",
"config",
"[",
"'SSL_ENABLED'",
"]",
":",
"if",
"needs_ssl",
"and",
"not",
"request",
".",
"is_secure",
":",
"log",
".",
"debug",
"(",
"'Redirecting to https: %s'",
"%",
"request",
".",
"endpoint",
")",
"return",
"redirect",
"(",
"request",
".",
"url",
".",
"replace",
"(",
"\"http://\"",
",",
"\"https://\"",
")",
")",
"elif",
"not",
"ssl_enabled",
"and",
"request",
".",
"is_secure",
":",
"log",
".",
"debug",
"(",
"'Redirecting to http: %s'",
"%",
"request",
".",
"endpoint",
")",
"return",
"redirect",
"(",
"request",
".",
"url",
".",
"replace",
"(",
"\"https://\"",
",",
"\"http://\"",
")",
")",
"elif",
"needs_ssl",
":",
"log",
".",
"info",
"(",
"'Not redirecting to HTTPS for endpoint %s as SSL_ENABLED is set to False'",
"%",
"request",
".",
"endpoint",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
init
|
Initialise this library. The following config variables need to be in your Flask config:
REDIS_HOST: The host of the Redis server
REDIS_PORT: The port of the Redis server
REDIS_PASSWORD: The password used to connect to Redis or None
REDIS_GLOBAL_KEY_PREFIX: A short string unique to your application i.e. 'MYAPP'. This will be turned into
a prefix like '~~MYAPP~~:' and will be used to allow multiple applications to share
a single redis server
REDIS_LOCK_TIMEOUT: An integer with the number of seconds to wait before automatically releasing a lock.
A good number is 60 * 5 for 5 minutes. This stops locks from being held indefinitely
if something goes wrong, but bear in mind this can also cause concurrency issues if
you ave a locking process that takes longer than this timeout!
|
littlefish/redisutil.py
|
def init(app):
"""
Initialise this library. The following config variables need to be in your Flask config:
REDIS_HOST: The host of the Redis server
REDIS_PORT: The port of the Redis server
REDIS_PASSWORD: The password used to connect to Redis or None
REDIS_GLOBAL_KEY_PREFIX: A short string unique to your application i.e. 'MYAPP'. This will be turned into
a prefix like '~~MYAPP~~:' and will be used to allow multiple applications to share
a single redis server
REDIS_LOCK_TIMEOUT: An integer with the number of seconds to wait before automatically releasing a lock.
A good number is 60 * 5 for 5 minutes. This stops locks from being held indefinitely
if something goes wrong, but bear in mind this can also cause concurrency issues if
you ave a locking process that takes longer than this timeout!
"""
global connection, LOCK_TIMEOUT, GLOBAL_KEY_PREFIX
host = app.config['REDIS_HOST']
port = app.config['REDIS_PORT']
password = app.config['REDIS_PASSWORD']
GLOBAL_KEY_PREFIX = '~~{}~~:'.format(app.config['REDIS_GLOBAL_KEY_PREFIX'])
LOCK_TIMEOUT = app.config['REDIS_LOCK_TIMEOUT']
connection = redis.StrictRedis(host=host, port=port, password=password)
|
def init(app):
"""
Initialise this library. The following config variables need to be in your Flask config:
REDIS_HOST: The host of the Redis server
REDIS_PORT: The port of the Redis server
REDIS_PASSWORD: The password used to connect to Redis or None
REDIS_GLOBAL_KEY_PREFIX: A short string unique to your application i.e. 'MYAPP'. This will be turned into
a prefix like '~~MYAPP~~:' and will be used to allow multiple applications to share
a single redis server
REDIS_LOCK_TIMEOUT: An integer with the number of seconds to wait before automatically releasing a lock.
A good number is 60 * 5 for 5 minutes. This stops locks from being held indefinitely
if something goes wrong, but bear in mind this can also cause concurrency issues if
you ave a locking process that takes longer than this timeout!
"""
global connection, LOCK_TIMEOUT, GLOBAL_KEY_PREFIX
host = app.config['REDIS_HOST']
port = app.config['REDIS_PORT']
password = app.config['REDIS_PASSWORD']
GLOBAL_KEY_PREFIX = '~~{}~~:'.format(app.config['REDIS_GLOBAL_KEY_PREFIX'])
LOCK_TIMEOUT = app.config['REDIS_LOCK_TIMEOUT']
connection = redis.StrictRedis(host=host, port=port, password=password)
|
[
"Initialise",
"this",
"library",
".",
"The",
"following",
"config",
"variables",
"need",
"to",
"be",
"in",
"your",
"Flask",
"config",
":"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/redisutil.py#L62-L86
|
[
"def",
"init",
"(",
"app",
")",
":",
"global",
"connection",
",",
"LOCK_TIMEOUT",
",",
"GLOBAL_KEY_PREFIX",
"host",
"=",
"app",
".",
"config",
"[",
"'REDIS_HOST'",
"]",
"port",
"=",
"app",
".",
"config",
"[",
"'REDIS_PORT'",
"]",
"password",
"=",
"app",
".",
"config",
"[",
"'REDIS_PASSWORD'",
"]",
"GLOBAL_KEY_PREFIX",
"=",
"'~~{}~~:'",
".",
"format",
"(",
"app",
".",
"config",
"[",
"'REDIS_GLOBAL_KEY_PREFIX'",
"]",
")",
"LOCK_TIMEOUT",
"=",
"app",
".",
"config",
"[",
"'REDIS_LOCK_TIMEOUT'",
"]",
"connection",
"=",
"redis",
".",
"StrictRedis",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"password",
"=",
"password",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
get_enable_celery_error_reporting_function
|
Use this to enable error reporting. You need to put the following in your tasks.py or wherever you
want to create your celery instance:
celery = Celery(__name__)
enable_celery_email_logging = get_enable_celery_error_reporting_function('My Website [LIVE]', 'errors@mywebsite.com')
after_setup_logger.connect(enable_celery_email_logging)
after_setup_task_logger.connect(enable_celery_email_logging)
|
littlefish/celeryutil.py
|
def get_enable_celery_error_reporting_function(site_name, from_address):
"""
Use this to enable error reporting. You need to put the following in your tasks.py or wherever you
want to create your celery instance:
celery = Celery(__name__)
enable_celery_email_logging = get_enable_celery_error_reporting_function('My Website [LIVE]', 'errors@mywebsite.com')
after_setup_logger.connect(enable_celery_email_logging)
after_setup_task_logger.connect(enable_celery_email_logging)
"""
def enable_celery_email_logging(sender, signal, logger, loglevel, logfile, format, colorize, **kwargs):
from celery import current_app
log.info('>> Initialising Celery task error reporting for logger {}'.format(logger.name))
send_errors = current_app.conf['CELERY_SEND_TASK_ERROR_EMAILS']
send_warnings = current_app.conf['CELERY_SEND_TASK_WARNING_EMAILS']
if send_errors or send_warnings:
error_email_subject = '{} Celery ERROR!'.format(site_name)
celery_handler = CeleryEmailHandler(from_address, current_app.conf['ADMIN_EMAILS'],
error_email_subject)
if send_warnings:
celery_handler.setLevel(logging.WARNING)
else:
celery_handler.setLevel(logging.ERROR)
logger.addHandler(celery_handler)
return enable_celery_email_logging
|
def get_enable_celery_error_reporting_function(site_name, from_address):
"""
Use this to enable error reporting. You need to put the following in your tasks.py or wherever you
want to create your celery instance:
celery = Celery(__name__)
enable_celery_email_logging = get_enable_celery_error_reporting_function('My Website [LIVE]', 'errors@mywebsite.com')
after_setup_logger.connect(enable_celery_email_logging)
after_setup_task_logger.connect(enable_celery_email_logging)
"""
def enable_celery_email_logging(sender, signal, logger, loglevel, logfile, format, colorize, **kwargs):
from celery import current_app
log.info('>> Initialising Celery task error reporting for logger {}'.format(logger.name))
send_errors = current_app.conf['CELERY_SEND_TASK_ERROR_EMAILS']
send_warnings = current_app.conf['CELERY_SEND_TASK_WARNING_EMAILS']
if send_errors or send_warnings:
error_email_subject = '{} Celery ERROR!'.format(site_name)
celery_handler = CeleryEmailHandler(from_address, current_app.conf['ADMIN_EMAILS'],
error_email_subject)
if send_warnings:
celery_handler.setLevel(logging.WARNING)
else:
celery_handler.setLevel(logging.ERROR)
logger.addHandler(celery_handler)
return enable_celery_email_logging
|
[
"Use",
"this",
"to",
"enable",
"error",
"reporting",
".",
"You",
"need",
"to",
"put",
"the",
"following",
"in",
"your",
"tasks",
".",
"py",
"or",
"wherever",
"you",
"want",
"to",
"create",
"your",
"celery",
"instance",
":"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/celeryutil.py#L24-L54
|
[
"def",
"get_enable_celery_error_reporting_function",
"(",
"site_name",
",",
"from_address",
")",
":",
"def",
"enable_celery_email_logging",
"(",
"sender",
",",
"signal",
",",
"logger",
",",
"loglevel",
",",
"logfile",
",",
"format",
",",
"colorize",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"celery",
"import",
"current_app",
"log",
".",
"info",
"(",
"'>> Initialising Celery task error reporting for logger {}'",
".",
"format",
"(",
"logger",
".",
"name",
")",
")",
"send_errors",
"=",
"current_app",
".",
"conf",
"[",
"'CELERY_SEND_TASK_ERROR_EMAILS'",
"]",
"send_warnings",
"=",
"current_app",
".",
"conf",
"[",
"'CELERY_SEND_TASK_WARNING_EMAILS'",
"]",
"if",
"send_errors",
"or",
"send_warnings",
":",
"error_email_subject",
"=",
"'{} Celery ERROR!'",
".",
"format",
"(",
"site_name",
")",
"celery_handler",
"=",
"CeleryEmailHandler",
"(",
"from_address",
",",
"current_app",
".",
"conf",
"[",
"'ADMIN_EMAILS'",
"]",
",",
"error_email_subject",
")",
"if",
"send_warnings",
":",
"celery_handler",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"else",
":",
"celery_handler",
".",
"setLevel",
"(",
"logging",
".",
"ERROR",
")",
"logger",
".",
"addHandler",
"(",
"celery_handler",
")",
"return",
"enable_celery_email_logging"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
init_celery
|
Initialise Celery and set up logging
:param app: Flask app
:param celery: Celery instance
|
littlefish/celeryutil.py
|
def init_celery(app, celery):
"""
Initialise Celery and set up logging
:param app: Flask app
:param celery: Celery instance
"""
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
|
def init_celery(app, celery):
"""
Initialise Celery and set up logging
:param app: Flask app
:param celery: Celery instance
"""
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
|
[
"Initialise",
"Celery",
"and",
"set",
"up",
"logging"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/celeryutil.py#L57-L77
|
[
"def",
"init_celery",
"(",
"app",
",",
"celery",
")",
":",
"celery",
".",
"conf",
".",
"update",
"(",
"app",
".",
"config",
")",
"TaskBase",
"=",
"celery",
".",
"Task",
"class",
"ContextTask",
"(",
"TaskBase",
")",
":",
"abstract",
"=",
"True",
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"return",
"TaskBase",
".",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"celery",
".",
"Task",
"=",
"ContextTask",
"return",
"celery"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
queue_email
|
Add a mail to the queue to be sent.
WARNING: Commits by default!
:param to_addresses: The names and addresses to send the email to, i.e. "Steve<steve@fig14.com>, info@fig14.com"
:param from_address: Who the email is from i.e. "Stephen Brown <s@fig14.com>"
:param subject: The email subject
:param body: The html / text body of the email
:param commit: Whether to commit to the database
:param html: Is this a html email?
:param session: The sqlalchemy session or None to use db.session
|
littlefish/background/emailqueue.py
|
def queue_email(to_addresses, from_address, subject, body, commit=True, html=True, session=None):
"""
Add a mail to the queue to be sent.
WARNING: Commits by default!
:param to_addresses: The names and addresses to send the email to, i.e. "Steve<steve@fig14.com>, info@fig14.com"
:param from_address: Who the email is from i.e. "Stephen Brown <s@fig14.com>"
:param subject: The email subject
:param body: The html / text body of the email
:param commit: Whether to commit to the database
:param html: Is this a html email?
:param session: The sqlalchemy session or None to use db.session
"""
from models import QueuedEmail
if session is None:
session = _db.session
log.info('Queuing mail to %s: %s' % (to_addresses, subject))
queued_email = QueuedEmail(html, to_addresses, from_address, subject, body, STATUS_QUEUED)
session.add(queued_email)
session.commit()
return queued_email
|
def queue_email(to_addresses, from_address, subject, body, commit=True, html=True, session=None):
"""
Add a mail to the queue to be sent.
WARNING: Commits by default!
:param to_addresses: The names and addresses to send the email to, i.e. "Steve<steve@fig14.com>, info@fig14.com"
:param from_address: Who the email is from i.e. "Stephen Brown <s@fig14.com>"
:param subject: The email subject
:param body: The html / text body of the email
:param commit: Whether to commit to the database
:param html: Is this a html email?
:param session: The sqlalchemy session or None to use db.session
"""
from models import QueuedEmail
if session is None:
session = _db.session
log.info('Queuing mail to %s: %s' % (to_addresses, subject))
queued_email = QueuedEmail(html, to_addresses, from_address, subject, body, STATUS_QUEUED)
session.add(queued_email)
session.commit()
return queued_email
|
[
"Add",
"a",
"mail",
"to",
"the",
"queue",
"to",
"be",
"sent",
"."
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/background/emailqueue.py#L113-L137
|
[
"def",
"queue_email",
"(",
"to_addresses",
",",
"from_address",
",",
"subject",
",",
"body",
",",
"commit",
"=",
"True",
",",
"html",
"=",
"True",
",",
"session",
"=",
"None",
")",
":",
"from",
"models",
"import",
"QueuedEmail",
"if",
"session",
"is",
"None",
":",
"session",
"=",
"_db",
".",
"session",
"log",
".",
"info",
"(",
"'Queuing mail to %s: %s'",
"%",
"(",
"to_addresses",
",",
"subject",
")",
")",
"queued_email",
"=",
"QueuedEmail",
"(",
"html",
",",
"to_addresses",
",",
"from_address",
",",
"subject",
",",
"body",
",",
"STATUS_QUEUED",
")",
"session",
".",
"add",
"(",
"queued_email",
")",
"session",
".",
"commit",
"(",
")",
"return",
"queued_email"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
parse_accept
|
Parse an HTTP accept-like header.
:param str header_value: the header value to parse
:return: a :class:`list` of :class:`.ContentType` instances
in decreasing quality order. Each instance is augmented
with the associated quality as a ``float`` property
named ``quality``.
``Accept`` is a class of headers that contain a list of values
and an associated preference value. The ever present `Accept`_
header is a perfect example. It is a list of content types and
an optional parameter named ``q`` that indicates the relative
weight of a particular type. The most basic example is::
Accept: audio/*;q=0.2, audio/basic
Which states that I prefer the ``audio/basic`` content type
but will accept other ``audio`` sub-types with an 80% mark down.
.. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
|
ietfparse/headers.py
|
def parse_accept(header_value):
"""Parse an HTTP accept-like header.
:param str header_value: the header value to parse
:return: a :class:`list` of :class:`.ContentType` instances
in decreasing quality order. Each instance is augmented
with the associated quality as a ``float`` property
named ``quality``.
``Accept`` is a class of headers that contain a list of values
and an associated preference value. The ever present `Accept`_
header is a perfect example. It is a list of content types and
an optional parameter named ``q`` that indicates the relative
weight of a particular type. The most basic example is::
Accept: audio/*;q=0.2, audio/basic
Which states that I prefer the ``audio/basic`` content type
but will accept other ``audio`` sub-types with an 80% mark down.
.. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
"""
next_explicit_q = decimal.ExtendedContext.next_plus(decimal.Decimal('5.0'))
headers = [parse_content_type(header)
for header in parse_list(header_value)]
for header in headers:
q = header.parameters.pop('q', None)
if q is None:
q = '1.0'
elif float(q) == 1.0:
q = float(next_explicit_q)
next_explicit_q = next_explicit_q.next_minus()
header.quality = float(q)
def ordering(left, right):
"""
Method for sorting the header values
:param mixed left:
:param mixed right:
:rtype: mixed
"""
if left.quality != right.quality:
return right.quality - left.quality
if left == right:
return 0
if left > right:
return -1
return 1
return sorted(headers, key=functools.cmp_to_key(ordering))
|
def parse_accept(header_value):
"""Parse an HTTP accept-like header.
:param str header_value: the header value to parse
:return: a :class:`list` of :class:`.ContentType` instances
in decreasing quality order. Each instance is augmented
with the associated quality as a ``float`` property
named ``quality``.
``Accept`` is a class of headers that contain a list of values
and an associated preference value. The ever present `Accept`_
header is a perfect example. It is a list of content types and
an optional parameter named ``q`` that indicates the relative
weight of a particular type. The most basic example is::
Accept: audio/*;q=0.2, audio/basic
Which states that I prefer the ``audio/basic`` content type
but will accept other ``audio`` sub-types with an 80% mark down.
.. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
"""
next_explicit_q = decimal.ExtendedContext.next_plus(decimal.Decimal('5.0'))
headers = [parse_content_type(header)
for header in parse_list(header_value)]
for header in headers:
q = header.parameters.pop('q', None)
if q is None:
q = '1.0'
elif float(q) == 1.0:
q = float(next_explicit_q)
next_explicit_q = next_explicit_q.next_minus()
header.quality = float(q)
def ordering(left, right):
"""
Method for sorting the header values
:param mixed left:
:param mixed right:
:rtype: mixed
"""
if left.quality != right.quality:
return right.quality - left.quality
if left == right:
return 0
if left > right:
return -1
return 1
return sorted(headers, key=functools.cmp_to_key(ordering))
|
[
"Parse",
"an",
"HTTP",
"accept",
"-",
"like",
"header",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L34-L86
|
[
"def",
"parse_accept",
"(",
"header_value",
")",
":",
"next_explicit_q",
"=",
"decimal",
".",
"ExtendedContext",
".",
"next_plus",
"(",
"decimal",
".",
"Decimal",
"(",
"'5.0'",
")",
")",
"headers",
"=",
"[",
"parse_content_type",
"(",
"header",
")",
"for",
"header",
"in",
"parse_list",
"(",
"header_value",
")",
"]",
"for",
"header",
"in",
"headers",
":",
"q",
"=",
"header",
".",
"parameters",
".",
"pop",
"(",
"'q'",
",",
"None",
")",
"if",
"q",
"is",
"None",
":",
"q",
"=",
"'1.0'",
"elif",
"float",
"(",
"q",
")",
"==",
"1.0",
":",
"q",
"=",
"float",
"(",
"next_explicit_q",
")",
"next_explicit_q",
"=",
"next_explicit_q",
".",
"next_minus",
"(",
")",
"header",
".",
"quality",
"=",
"float",
"(",
"q",
")",
"def",
"ordering",
"(",
"left",
",",
"right",
")",
":",
"\"\"\"\n Method for sorting the header values\n\n :param mixed left:\n :param mixed right:\n :rtype: mixed\n\n \"\"\"",
"if",
"left",
".",
"quality",
"!=",
"right",
".",
"quality",
":",
"return",
"right",
".",
"quality",
"-",
"left",
".",
"quality",
"if",
"left",
"==",
"right",
":",
"return",
"0",
"if",
"left",
">",
"right",
":",
"return",
"-",
"1",
"return",
"1",
"return",
"sorted",
"(",
"headers",
",",
"key",
"=",
"functools",
".",
"cmp_to_key",
"(",
"ordering",
")",
")"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
parse_cache_control
|
Parse a `Cache-Control`_ header, returning a dictionary of key-value pairs.
Any of the ``Cache-Control`` parameters that do not have directives, such
as ``public`` or ``no-cache`` will be returned with a value of ``True``
if they are set in the header.
:param str header_value: ``Cache-Control`` header value to parse
:return: the parsed ``Cache-Control`` header values
:rtype: dict
.. _Cache-Control: https://tools.ietf.org/html/rfc7234#section-5.2
|
ietfparse/headers.py
|
def parse_cache_control(header_value):
"""
Parse a `Cache-Control`_ header, returning a dictionary of key-value pairs.
Any of the ``Cache-Control`` parameters that do not have directives, such
as ``public`` or ``no-cache`` will be returned with a value of ``True``
if they are set in the header.
:param str header_value: ``Cache-Control`` header value to parse
:return: the parsed ``Cache-Control`` header values
:rtype: dict
.. _Cache-Control: https://tools.ietf.org/html/rfc7234#section-5.2
"""
directives = {}
for segment in parse_list(header_value):
name, sep, value = segment.partition('=')
if sep != '=':
directives[name] = None
elif sep and value:
value = _dequote(value.strip())
try:
directives[name] = int(value)
except ValueError:
directives[name] = value
# NB ``name='' is never valid and is ignored!
# convert parameterless boolean directives
for name in _CACHE_CONTROL_BOOL_DIRECTIVES:
if directives.get(name, '') is None:
directives[name] = True
return directives
|
def parse_cache_control(header_value):
"""
Parse a `Cache-Control`_ header, returning a dictionary of key-value pairs.
Any of the ``Cache-Control`` parameters that do not have directives, such
as ``public`` or ``no-cache`` will be returned with a value of ``True``
if they are set in the header.
:param str header_value: ``Cache-Control`` header value to parse
:return: the parsed ``Cache-Control`` header values
:rtype: dict
.. _Cache-Control: https://tools.ietf.org/html/rfc7234#section-5.2
"""
directives = {}
for segment in parse_list(header_value):
name, sep, value = segment.partition('=')
if sep != '=':
directives[name] = None
elif sep and value:
value = _dequote(value.strip())
try:
directives[name] = int(value)
except ValueError:
directives[name] = value
# NB ``name='' is never valid and is ignored!
# convert parameterless boolean directives
for name in _CACHE_CONTROL_BOOL_DIRECTIVES:
if directives.get(name, '') is None:
directives[name] = True
return directives
|
[
"Parse",
"a",
"Cache",
"-",
"Control",
"_",
"header",
"returning",
"a",
"dictionary",
"of",
"key",
"-",
"value",
"pairs",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L165-L199
|
[
"def",
"parse_cache_control",
"(",
"header_value",
")",
":",
"directives",
"=",
"{",
"}",
"for",
"segment",
"in",
"parse_list",
"(",
"header_value",
")",
":",
"name",
",",
"sep",
",",
"value",
"=",
"segment",
".",
"partition",
"(",
"'='",
")",
"if",
"sep",
"!=",
"'='",
":",
"directives",
"[",
"name",
"]",
"=",
"None",
"elif",
"sep",
"and",
"value",
":",
"value",
"=",
"_dequote",
"(",
"value",
".",
"strip",
"(",
")",
")",
"try",
":",
"directives",
"[",
"name",
"]",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"directives",
"[",
"name",
"]",
"=",
"value",
"# NB ``name='' is never valid and is ignored!",
"# convert parameterless boolean directives",
"for",
"name",
"in",
"_CACHE_CONTROL_BOOL_DIRECTIVES",
":",
"if",
"directives",
".",
"get",
"(",
"name",
",",
"''",
")",
"is",
"None",
":",
"directives",
"[",
"name",
"]",
"=",
"True",
"return",
"directives"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
parse_content_type
|
Parse a content type like header.
:param str content_type: the string to parse as a content type
:param bool normalize_parameter_values:
setting this to ``False`` will enable strict RFC2045 compliance
in which content parameter values are case preserving.
:return: a :class:`~ietfparse.datastructures.ContentType` instance
|
ietfparse/headers.py
|
def parse_content_type(content_type, normalize_parameter_values=True):
"""Parse a content type like header.
:param str content_type: the string to parse as a content type
:param bool normalize_parameter_values:
setting this to ``False`` will enable strict RFC2045 compliance
in which content parameter values are case preserving.
:return: a :class:`~ietfparse.datastructures.ContentType` instance
"""
parts = _remove_comments(content_type).split(';')
content_type, content_subtype = parts.pop(0).split('/')
if '+' in content_subtype:
content_subtype, content_suffix = content_subtype.split('+')
else:
content_suffix = None
parameters = _parse_parameter_list(
parts, normalize_parameter_values=normalize_parameter_values)
return datastructures.ContentType(content_type, content_subtype,
dict(parameters),
content_suffix)
|
def parse_content_type(content_type, normalize_parameter_values=True):
"""Parse a content type like header.
:param str content_type: the string to parse as a content type
:param bool normalize_parameter_values:
setting this to ``False`` will enable strict RFC2045 compliance
in which content parameter values are case preserving.
:return: a :class:`~ietfparse.datastructures.ContentType` instance
"""
parts = _remove_comments(content_type).split(';')
content_type, content_subtype = parts.pop(0).split('/')
if '+' in content_subtype:
content_subtype, content_suffix = content_subtype.split('+')
else:
content_suffix = None
parameters = _parse_parameter_list(
parts, normalize_parameter_values=normalize_parameter_values)
return datastructures.ContentType(content_type, content_subtype,
dict(parameters),
content_suffix)
|
[
"Parse",
"a",
"content",
"type",
"like",
"header",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L202-L223
|
[
"def",
"parse_content_type",
"(",
"content_type",
",",
"normalize_parameter_values",
"=",
"True",
")",
":",
"parts",
"=",
"_remove_comments",
"(",
"content_type",
")",
".",
"split",
"(",
"';'",
")",
"content_type",
",",
"content_subtype",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"'+'",
"in",
"content_subtype",
":",
"content_subtype",
",",
"content_suffix",
"=",
"content_subtype",
".",
"split",
"(",
"'+'",
")",
"else",
":",
"content_suffix",
"=",
"None",
"parameters",
"=",
"_parse_parameter_list",
"(",
"parts",
",",
"normalize_parameter_values",
"=",
"normalize_parameter_values",
")",
"return",
"datastructures",
".",
"ContentType",
"(",
"content_type",
",",
"content_subtype",
",",
"dict",
"(",
"parameters",
")",
",",
"content_suffix",
")"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
parse_forwarded
|
Parse RFC7239 Forwarded header.
:param str header_value: value to parse
:keyword bool only_standard_parameters: if this keyword is specified
and given a *truthy* value, then a non-standard parameter name
will result in :exc:`~ietfparse.errors.StrictHeaderParsingFailure`
:return: an ordered :class:`list` of :class:`dict` instances
:raises: :exc:`ietfparse.errors.StrictHeaderParsingFailure` is
raised if `only_standard_parameters` is enabled and a non-standard
parameter name is encountered
This function parses a :rfc:`7239` HTTP header into a :class:`list`
of :class:`dict` instances with each instance containing the param
values. The list is ordered as received from left to right and the
parameter names are folded to lower case strings.
|
ietfparse/headers.py
|
def parse_forwarded(header_value, only_standard_parameters=False):
"""
Parse RFC7239 Forwarded header.
:param str header_value: value to parse
:keyword bool only_standard_parameters: if this keyword is specified
and given a *truthy* value, then a non-standard parameter name
will result in :exc:`~ietfparse.errors.StrictHeaderParsingFailure`
:return: an ordered :class:`list` of :class:`dict` instances
:raises: :exc:`ietfparse.errors.StrictHeaderParsingFailure` is
raised if `only_standard_parameters` is enabled and a non-standard
parameter name is encountered
This function parses a :rfc:`7239` HTTP header into a :class:`list`
of :class:`dict` instances with each instance containing the param
values. The list is ordered as received from left to right and the
parameter names are folded to lower case strings.
"""
result = []
for entry in parse_list(header_value):
param_tuples = _parse_parameter_list(entry.split(';'),
normalize_parameter_names=True,
normalize_parameter_values=False)
if only_standard_parameters:
for name, _ in param_tuples:
if name not in ('for', 'proto', 'by', 'host'):
raise errors.StrictHeaderParsingFailure('Forwarded',
header_value)
result.append(dict(param_tuples))
return result
|
def parse_forwarded(header_value, only_standard_parameters=False):
"""
Parse RFC7239 Forwarded header.
:param str header_value: value to parse
:keyword bool only_standard_parameters: if this keyword is specified
and given a *truthy* value, then a non-standard parameter name
will result in :exc:`~ietfparse.errors.StrictHeaderParsingFailure`
:return: an ordered :class:`list` of :class:`dict` instances
:raises: :exc:`ietfparse.errors.StrictHeaderParsingFailure` is
raised if `only_standard_parameters` is enabled and a non-standard
parameter name is encountered
This function parses a :rfc:`7239` HTTP header into a :class:`list`
of :class:`dict` instances with each instance containing the param
values. The list is ordered as received from left to right and the
parameter names are folded to lower case strings.
"""
result = []
for entry in parse_list(header_value):
param_tuples = _parse_parameter_list(entry.split(';'),
normalize_parameter_names=True,
normalize_parameter_values=False)
if only_standard_parameters:
for name, _ in param_tuples:
if name not in ('for', 'proto', 'by', 'host'):
raise errors.StrictHeaderParsingFailure('Forwarded',
header_value)
result.append(dict(param_tuples))
return result
|
[
"Parse",
"RFC7239",
"Forwarded",
"header",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L226-L256
|
[
"def",
"parse_forwarded",
"(",
"header_value",
",",
"only_standard_parameters",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"for",
"entry",
"in",
"parse_list",
"(",
"header_value",
")",
":",
"param_tuples",
"=",
"_parse_parameter_list",
"(",
"entry",
".",
"split",
"(",
"';'",
")",
",",
"normalize_parameter_names",
"=",
"True",
",",
"normalize_parameter_values",
"=",
"False",
")",
"if",
"only_standard_parameters",
":",
"for",
"name",
",",
"_",
"in",
"param_tuples",
":",
"if",
"name",
"not",
"in",
"(",
"'for'",
",",
"'proto'",
",",
"'by'",
",",
"'host'",
")",
":",
"raise",
"errors",
".",
"StrictHeaderParsingFailure",
"(",
"'Forwarded'",
",",
"header_value",
")",
"result",
".",
"append",
"(",
"dict",
"(",
"param_tuples",
")",
")",
"return",
"result"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
parse_link
|
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all parameters.
:return: a sequence of :class:`~ietfparse.datastructures.LinkHeader`
instances
:raises ietfparse.errors.MalformedLinkValue:
if the specified `header_value` cannot be parsed
|
ietfparse/headers.py
|
def parse_link(header_value, strict=True):
"""
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all parameters.
:return: a sequence of :class:`~ietfparse.datastructures.LinkHeader`
instances
:raises ietfparse.errors.MalformedLinkValue:
if the specified `header_value` cannot be parsed
"""
sanitized = _remove_comments(header_value)
links = []
def parse_links(buf):
"""
Find quoted parts, these are allowed to contain commas
however, it is much easier to parse if they do not so
replace them with \000. Since the NUL byte is not allowed
to be there, we can replace it with a comma later on.
A similar trick is performed on semicolons with \001.
:param str buf: The link buffer
:return:
"""
quoted = re.findall('"([^"]*)"', buf)
for segment in quoted:
left, match, right = buf.partition(segment)
match = match.replace(',', '\000')
match = match.replace(';', '\001')
buf = ''.join([left, match, right])
while buf:
matched = re.match(r'<(?P<link>[^>]*)>\s*(?P<params>.*)', buf)
if matched:
groups = matched.groupdict()
params, _, buf = groups['params'].partition(',')
params = params.replace('\000', ',') # undo comma hackery
if params and not params.startswith(';'):
raise errors.MalformedLinkValue(
'Param list missing opening semicolon ')
yield (groups['link'].strip(),
[p.replace('\001', ';').strip()
for p in params[1:].split(';') if p])
buf = buf.strip()
else:
raise errors.MalformedLinkValue('Malformed link header', buf)
for target, param_list in parse_links(sanitized):
parser = _helpers.ParameterParser(strict=strict)
for name, value in _parse_parameter_list(param_list):
parser.add_value(name, value)
links.append(datastructures.LinkHeader(target=target,
parameters=parser.values))
return links
|
def parse_link(header_value, strict=True):
"""
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all parameters.
:return: a sequence of :class:`~ietfparse.datastructures.LinkHeader`
instances
:raises ietfparse.errors.MalformedLinkValue:
if the specified `header_value` cannot be parsed
"""
sanitized = _remove_comments(header_value)
links = []
def parse_links(buf):
"""
Find quoted parts, these are allowed to contain commas
however, it is much easier to parse if they do not so
replace them with \000. Since the NUL byte is not allowed
to be there, we can replace it with a comma later on.
A similar trick is performed on semicolons with \001.
:param str buf: The link buffer
:return:
"""
quoted = re.findall('"([^"]*)"', buf)
for segment in quoted:
left, match, right = buf.partition(segment)
match = match.replace(',', '\000')
match = match.replace(';', '\001')
buf = ''.join([left, match, right])
while buf:
matched = re.match(r'<(?P<link>[^>]*)>\s*(?P<params>.*)', buf)
if matched:
groups = matched.groupdict()
params, _, buf = groups['params'].partition(',')
params = params.replace('\000', ',') # undo comma hackery
if params and not params.startswith(';'):
raise errors.MalformedLinkValue(
'Param list missing opening semicolon ')
yield (groups['link'].strip(),
[p.replace('\001', ';').strip()
for p in params[1:].split(';') if p])
buf = buf.strip()
else:
raise errors.MalformedLinkValue('Malformed link header', buf)
for target, param_list in parse_links(sanitized):
parser = _helpers.ParameterParser(strict=strict)
for name, value in _parse_parameter_list(param_list):
parser.add_value(name, value)
links.append(datastructures.LinkHeader(target=target,
parameters=parser.values))
return links
|
[
"Parse",
"a",
"HTTP",
"Link",
"header",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L259-L318
|
[
"def",
"parse_link",
"(",
"header_value",
",",
"strict",
"=",
"True",
")",
":",
"sanitized",
"=",
"_remove_comments",
"(",
"header_value",
")",
"links",
"=",
"[",
"]",
"def",
"parse_links",
"(",
"buf",
")",
":",
"\"\"\"\n Find quoted parts, these are allowed to contain commas\n however, it is much easier to parse if they do not so\n replace them with \\000. Since the NUL byte is not allowed\n to be there, we can replace it with a comma later on.\n A similar trick is performed on semicolons with \\001.\n\n :param str buf: The link buffer\n :return:\n \"\"\"",
"quoted",
"=",
"re",
".",
"findall",
"(",
"'\"([^\"]*)\"'",
",",
"buf",
")",
"for",
"segment",
"in",
"quoted",
":",
"left",
",",
"match",
",",
"right",
"=",
"buf",
".",
"partition",
"(",
"segment",
")",
"match",
"=",
"match",
".",
"replace",
"(",
"','",
",",
"'\\000'",
")",
"match",
"=",
"match",
".",
"replace",
"(",
"';'",
",",
"'\\001'",
")",
"buf",
"=",
"''",
".",
"join",
"(",
"[",
"left",
",",
"match",
",",
"right",
"]",
")",
"while",
"buf",
":",
"matched",
"=",
"re",
".",
"match",
"(",
"r'<(?P<link>[^>]*)>\\s*(?P<params>.*)'",
",",
"buf",
")",
"if",
"matched",
":",
"groups",
"=",
"matched",
".",
"groupdict",
"(",
")",
"params",
",",
"_",
",",
"buf",
"=",
"groups",
"[",
"'params'",
"]",
".",
"partition",
"(",
"','",
")",
"params",
"=",
"params",
".",
"replace",
"(",
"'\\000'",
",",
"','",
")",
"# undo comma hackery",
"if",
"params",
"and",
"not",
"params",
".",
"startswith",
"(",
"';'",
")",
":",
"raise",
"errors",
".",
"MalformedLinkValue",
"(",
"'Param list missing opening semicolon '",
")",
"yield",
"(",
"groups",
"[",
"'link'",
"]",
".",
"strip",
"(",
")",
",",
"[",
"p",
".",
"replace",
"(",
"'\\001'",
",",
"';'",
")",
".",
"strip",
"(",
")",
"for",
"p",
"in",
"params",
"[",
"1",
":",
"]",
".",
"split",
"(",
"';'",
")",
"if",
"p",
"]",
")",
"buf",
"=",
"buf",
".",
"strip",
"(",
")",
"else",
":",
"raise",
"errors",
".",
"MalformedLinkValue",
"(",
"'Malformed link header'",
",",
"buf",
")",
"for",
"target",
",",
"param_list",
"in",
"parse_links",
"(",
"sanitized",
")",
":",
"parser",
"=",
"_helpers",
".",
"ParameterParser",
"(",
"strict",
"=",
"strict",
")",
"for",
"name",
",",
"value",
"in",
"_parse_parameter_list",
"(",
"param_list",
")",
":",
"parser",
".",
"add_value",
"(",
"name",
",",
"value",
")",
"links",
".",
"append",
"(",
"datastructures",
".",
"LinkHeader",
"(",
"target",
"=",
"target",
",",
"parameters",
"=",
"parser",
".",
"values",
")",
")",
"return",
"links"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
parse_list
|
Parse a comma-separated list header.
:param str value: header value to split into elements
:return: list of header elements as strings
|
ietfparse/headers.py
|
def parse_list(value):
"""
Parse a comma-separated list header.
:param str value: header value to split into elements
:return: list of header elements as strings
"""
segments = _QUOTED_SEGMENT_RE.findall(value)
for segment in segments:
left, match, right = value.partition(segment)
value = ''.join([left, match.replace(',', '\000'), right])
return [_dequote(x.strip()).replace('\000', ',')
for x in value.split(',')]
|
def parse_list(value):
"""
Parse a comma-separated list header.
:param str value: header value to split into elements
:return: list of header elements as strings
"""
segments = _QUOTED_SEGMENT_RE.findall(value)
for segment in segments:
left, match, right = value.partition(segment)
value = ''.join([left, match.replace(',', '\000'), right])
return [_dequote(x.strip()).replace('\000', ',')
for x in value.split(',')]
|
[
"Parse",
"a",
"comma",
"-",
"separated",
"list",
"header",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L321-L334
|
[
"def",
"parse_list",
"(",
"value",
")",
":",
"segments",
"=",
"_QUOTED_SEGMENT_RE",
".",
"findall",
"(",
"value",
")",
"for",
"segment",
"in",
"segments",
":",
"left",
",",
"match",
",",
"right",
"=",
"value",
".",
"partition",
"(",
"segment",
")",
"value",
"=",
"''",
".",
"join",
"(",
"[",
"left",
",",
"match",
".",
"replace",
"(",
"','",
",",
"'\\000'",
")",
",",
"right",
"]",
")",
"return",
"[",
"_dequote",
"(",
"x",
".",
"strip",
"(",
")",
")",
".",
"replace",
"(",
"'\\000'",
",",
"','",
")",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
_parse_parameter_list
|
Parse a named parameter list in the "common" format.
:param parameter_list: sequence of string values to parse
:keyword bool normalize_parameter_names: if specified and *truthy*
then parameter names will be case-folded to lower case
:keyword bool normalize_parameter_values: if omitted or specified
as *truthy*, then parameter values are case-folded to lower case
:keyword bool normalized_parameter_values: alternate way to spell
``normalize_parameter_values`` -- this one is deprecated
:return: a sequence containing the name to value pairs
The parsed values are normalized according to the keyword parameters
and returned as :class:`tuple` of name to value pairs preserving the
ordering from `parameter_list`. The values will have quotes removed
if they were present.
|
ietfparse/headers.py
|
def _parse_parameter_list(parameter_list,
normalized_parameter_values=_DEF_PARAM_VALUE,
normalize_parameter_names=False,
normalize_parameter_values=True):
"""
Parse a named parameter list in the "common" format.
:param parameter_list: sequence of string values to parse
:keyword bool normalize_parameter_names: if specified and *truthy*
then parameter names will be case-folded to lower case
:keyword bool normalize_parameter_values: if omitted or specified
as *truthy*, then parameter values are case-folded to lower case
:keyword bool normalized_parameter_values: alternate way to spell
``normalize_parameter_values`` -- this one is deprecated
:return: a sequence containing the name to value pairs
The parsed values are normalized according to the keyword parameters
and returned as :class:`tuple` of name to value pairs preserving the
ordering from `parameter_list`. The values will have quotes removed
if they were present.
"""
if normalized_parameter_values is not _DEF_PARAM_VALUE: # pragma: no cover
warnings.warn('normalized_parameter_values keyword to '
'_parse_parameter_list is deprecated, use '
'normalize_parameter_values instead',
DeprecationWarning)
normalize_parameter_values = normalized_parameter_values
parameters = []
for param in parameter_list:
param = param.strip()
if param:
name, value = param.split('=')
if normalize_parameter_names:
name = name.lower()
if normalize_parameter_values:
value = value.lower()
parameters.append((name, _dequote(value.strip())))
return parameters
|
def _parse_parameter_list(parameter_list,
normalized_parameter_values=_DEF_PARAM_VALUE,
normalize_parameter_names=False,
normalize_parameter_values=True):
"""
Parse a named parameter list in the "common" format.
:param parameter_list: sequence of string values to parse
:keyword bool normalize_parameter_names: if specified and *truthy*
then parameter names will be case-folded to lower case
:keyword bool normalize_parameter_values: if omitted or specified
as *truthy*, then parameter values are case-folded to lower case
:keyword bool normalized_parameter_values: alternate way to spell
``normalize_parameter_values`` -- this one is deprecated
:return: a sequence containing the name to value pairs
The parsed values are normalized according to the keyword parameters
and returned as :class:`tuple` of name to value pairs preserving the
ordering from `parameter_list`. The values will have quotes removed
if they were present.
"""
if normalized_parameter_values is not _DEF_PARAM_VALUE: # pragma: no cover
warnings.warn('normalized_parameter_values keyword to '
'_parse_parameter_list is deprecated, use '
'normalize_parameter_values instead',
DeprecationWarning)
normalize_parameter_values = normalized_parameter_values
parameters = []
for param in parameter_list:
param = param.strip()
if param:
name, value = param.split('=')
if normalize_parameter_names:
name = name.lower()
if normalize_parameter_values:
value = value.lower()
parameters.append((name, _dequote(value.strip())))
return parameters
|
[
"Parse",
"a",
"named",
"parameter",
"list",
"in",
"the",
"common",
"format",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L337-L375
|
[
"def",
"_parse_parameter_list",
"(",
"parameter_list",
",",
"normalized_parameter_values",
"=",
"_DEF_PARAM_VALUE",
",",
"normalize_parameter_names",
"=",
"False",
",",
"normalize_parameter_values",
"=",
"True",
")",
":",
"if",
"normalized_parameter_values",
"is",
"not",
"_DEF_PARAM_VALUE",
":",
"# pragma: no cover",
"warnings",
".",
"warn",
"(",
"'normalized_parameter_values keyword to '",
"'_parse_parameter_list is deprecated, use '",
"'normalize_parameter_values instead'",
",",
"DeprecationWarning",
")",
"normalize_parameter_values",
"=",
"normalized_parameter_values",
"parameters",
"=",
"[",
"]",
"for",
"param",
"in",
"parameter_list",
":",
"param",
"=",
"param",
".",
"strip",
"(",
")",
"if",
"param",
":",
"name",
",",
"value",
"=",
"param",
".",
"split",
"(",
"'='",
")",
"if",
"normalize_parameter_names",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"normalize_parameter_values",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"parameters",
".",
"append",
"(",
"(",
"name",
",",
"_dequote",
"(",
"value",
".",
"strip",
"(",
")",
")",
")",
")",
"return",
"parameters"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
_parse_qualified_list
|
Parse a header value, returning a sorted list of values based upon
the quality rules specified in https://tools.ietf.org/html/rfc7231 for
the Accept-* headers.
:param str value: The value to parse into a list
:rtype: list
|
ietfparse/headers.py
|
def _parse_qualified_list(value):
"""
Parse a header value, returning a sorted list of values based upon
the quality rules specified in https://tools.ietf.org/html/rfc7231 for
the Accept-* headers.
:param str value: The value to parse into a list
:rtype: list
"""
found_wildcard = False
values, rejected_values = [], []
parsed = parse_list(value)
default = float(len(parsed) + 1)
highest = default + 1.0
for raw_str in parsed:
charset, _, parameter_str = raw_str.replace(' ', '').partition(';')
if charset == '*':
found_wildcard = True
continue
params = dict(_parse_parameter_list(parameter_str.split(';')))
quality = float(params.pop('q', default))
if quality < 0.001:
rejected_values.append(charset)
elif quality == 1.0:
values.append((highest + default, charset))
else:
values.append((quality, charset))
default -= 1.0
parsed = [value[1] for value in sorted(values, reverse=True)]
if found_wildcard:
parsed.append('*')
parsed.extend(rejected_values)
return parsed
|
def _parse_qualified_list(value):
"""
Parse a header value, returning a sorted list of values based upon
the quality rules specified in https://tools.ietf.org/html/rfc7231 for
the Accept-* headers.
:param str value: The value to parse into a list
:rtype: list
"""
found_wildcard = False
values, rejected_values = [], []
parsed = parse_list(value)
default = float(len(parsed) + 1)
highest = default + 1.0
for raw_str in parsed:
charset, _, parameter_str = raw_str.replace(' ', '').partition(';')
if charset == '*':
found_wildcard = True
continue
params = dict(_parse_parameter_list(parameter_str.split(';')))
quality = float(params.pop('q', default))
if quality < 0.001:
rejected_values.append(charset)
elif quality == 1.0:
values.append((highest + default, charset))
else:
values.append((quality, charset))
default -= 1.0
parsed = [value[1] for value in sorted(values, reverse=True)]
if found_wildcard:
parsed.append('*')
parsed.extend(rejected_values)
return parsed
|
[
"Parse",
"a",
"header",
"value",
"returning",
"a",
"sorted",
"list",
"of",
"values",
"based",
"upon",
"the",
"quality",
"rules",
"specified",
"in",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc7231",
"for",
"the",
"Accept",
"-",
"*",
"headers",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L378-L411
|
[
"def",
"_parse_qualified_list",
"(",
"value",
")",
":",
"found_wildcard",
"=",
"False",
"values",
",",
"rejected_values",
"=",
"[",
"]",
",",
"[",
"]",
"parsed",
"=",
"parse_list",
"(",
"value",
")",
"default",
"=",
"float",
"(",
"len",
"(",
"parsed",
")",
"+",
"1",
")",
"highest",
"=",
"default",
"+",
"1.0",
"for",
"raw_str",
"in",
"parsed",
":",
"charset",
",",
"_",
",",
"parameter_str",
"=",
"raw_str",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"partition",
"(",
"';'",
")",
"if",
"charset",
"==",
"'*'",
":",
"found_wildcard",
"=",
"True",
"continue",
"params",
"=",
"dict",
"(",
"_parse_parameter_list",
"(",
"parameter_str",
".",
"split",
"(",
"';'",
")",
")",
")",
"quality",
"=",
"float",
"(",
"params",
".",
"pop",
"(",
"'q'",
",",
"default",
")",
")",
"if",
"quality",
"<",
"0.001",
":",
"rejected_values",
".",
"append",
"(",
"charset",
")",
"elif",
"quality",
"==",
"1.0",
":",
"values",
".",
"append",
"(",
"(",
"highest",
"+",
"default",
",",
"charset",
")",
")",
"else",
":",
"values",
".",
"append",
"(",
"(",
"quality",
",",
"charset",
")",
")",
"default",
"-=",
"1.0",
"parsed",
"=",
"[",
"value",
"[",
"1",
"]",
"for",
"value",
"in",
"sorted",
"(",
"values",
",",
"reverse",
"=",
"True",
")",
"]",
"if",
"found_wildcard",
":",
"parsed",
".",
"append",
"(",
"'*'",
")",
"parsed",
".",
"extend",
"(",
"rejected_values",
")",
"return",
"parsed"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
parse_link_header
|
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all parameters.
:return: a sequence of :class:`~ietfparse.datastructures.LinkHeader`
instances
:raises ietfparse.errors.MalformedLinkValue:
if the specified `header_value` cannot be parsed
.. deprecated:: 1.3.0
Use :func:`~ietfparse.headers.parse_link` instead.
|
ietfparse/headers.py
|
def parse_link_header(header_value, strict=True):
"""
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all parameters.
:return: a sequence of :class:`~ietfparse.datastructures.LinkHeader`
instances
:raises ietfparse.errors.MalformedLinkValue:
if the specified `header_value` cannot be parsed
.. deprecated:: 1.3.0
Use :func:`~ietfparse.headers.parse_link` instead.
"""
warnings.warn("deprecated", DeprecationWarning)
return parse_link(header_value, strict)
|
def parse_link_header(header_value, strict=True):
"""
Parse a HTTP Link header.
:param str header_value: the header value to parse
:param bool strict: set this to ``False`` to disable semantic
checking. Syntactical errors will still raise an exception.
Use this if you want to receive all parameters.
:return: a sequence of :class:`~ietfparse.datastructures.LinkHeader`
instances
:raises ietfparse.errors.MalformedLinkValue:
if the specified `header_value` cannot be parsed
.. deprecated:: 1.3.0
Use :func:`~ietfparse.headers.parse_link` instead.
"""
warnings.warn("deprecated", DeprecationWarning)
return parse_link(header_value, strict)
|
[
"Parse",
"a",
"HTTP",
"Link",
"header",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/headers.py#L475-L493
|
[
"def",
"parse_link_header",
"(",
"header_value",
",",
"strict",
"=",
"True",
")",
":",
"warnings",
".",
"warn",
"(",
"\"deprecated\"",
",",
"DeprecationWarning",
")",
"return",
"parse_link",
"(",
"header_value",
",",
"strict",
")"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
resize_image_to_fit
|
Resize the image to fit inside dest rectangle. Resultant image may be smaller than target
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled image
|
littlefish/imageutil.py
|
def resize_image_to_fit(image, dest_w, dest_h):
"""
Resize the image to fit inside dest rectangle. Resultant image may be smaller than target
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled image
"""
dest_w = float(dest_w)
dest_h = float(dest_h)
dest_ratio = dest_w / dest_h
# Calculate the apect ratio of the image
src_w = float(image.size[0])
src_h = float(image.size[1])
src_ratio = src_w / src_h
if src_ratio < dest_ratio:
# Image is tall and thin - we need to scale to the right height and then pad
scale = dest_h / src_h
scaled_h = dest_h
scaled_w = src_w * scale
else:
# Image is short and wide - we need to scale to the right height and then crop
scale = dest_w / src_w
scaled_w = dest_w
scaled_h = src_h * scale
scaled_image = image.resize((int(scaled_w), int(scaled_h)), PIL.Image.ANTIALIAS)
return scaled_image
|
def resize_image_to_fit(image, dest_w, dest_h):
"""
Resize the image to fit inside dest rectangle. Resultant image may be smaller than target
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled image
"""
dest_w = float(dest_w)
dest_h = float(dest_h)
dest_ratio = dest_w / dest_h
# Calculate the apect ratio of the image
src_w = float(image.size[0])
src_h = float(image.size[1])
src_ratio = src_w / src_h
if src_ratio < dest_ratio:
# Image is tall and thin - we need to scale to the right height and then pad
scale = dest_h / src_h
scaled_h = dest_h
scaled_w = src_w * scale
else:
# Image is short and wide - we need to scale to the right height and then crop
scale = dest_w / src_w
scaled_w = dest_w
scaled_h = src_h * scale
scaled_image = image.resize((int(scaled_w), int(scaled_h)), PIL.Image.ANTIALIAS)
return scaled_image
|
[
"Resize",
"the",
"image",
"to",
"fit",
"inside",
"dest",
"rectangle",
".",
"Resultant",
"image",
"may",
"be",
"smaller",
"than",
"target",
":",
"param",
"image",
":",
"PIL",
".",
"Image",
":",
"param",
"dest_w",
":",
"Target",
"width",
":",
"param",
"dest_h",
":",
"Target",
"height",
":",
"return",
":",
"Scaled",
"image"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/imageutil.py#L16-L47
|
[
"def",
"resize_image_to_fit",
"(",
"image",
",",
"dest_w",
",",
"dest_h",
")",
":",
"dest_w",
"=",
"float",
"(",
"dest_w",
")",
"dest_h",
"=",
"float",
"(",
"dest_h",
")",
"dest_ratio",
"=",
"dest_w",
"/",
"dest_h",
"# Calculate the apect ratio of the image",
"src_w",
"=",
"float",
"(",
"image",
".",
"size",
"[",
"0",
"]",
")",
"src_h",
"=",
"float",
"(",
"image",
".",
"size",
"[",
"1",
"]",
")",
"src_ratio",
"=",
"src_w",
"/",
"src_h",
"if",
"src_ratio",
"<",
"dest_ratio",
":",
"# Image is tall and thin - we need to scale to the right height and then pad",
"scale",
"=",
"dest_h",
"/",
"src_h",
"scaled_h",
"=",
"dest_h",
"scaled_w",
"=",
"src_w",
"*",
"scale",
"else",
":",
"# Image is short and wide - we need to scale to the right height and then crop",
"scale",
"=",
"dest_w",
"/",
"src_w",
"scaled_w",
"=",
"dest_w",
"scaled_h",
"=",
"src_h",
"*",
"scale",
"scaled_image",
"=",
"image",
".",
"resize",
"(",
"(",
"int",
"(",
"scaled_w",
")",
",",
"int",
"(",
"scaled_h",
")",
")",
",",
"PIL",
".",
"Image",
".",
"ANTIALIAS",
")",
"return",
"scaled_image"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
resize_crop_image
|
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled and cropped image
|
littlefish/imageutil.py
|
def resize_crop_image(image, dest_w, dest_h, pad_when_tall=False):
"""
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled and cropped image
"""
# Now we need to resize it
dest_w = float(dest_w)
dest_h = float(dest_h)
dest_ratio = dest_w / dest_h
# Calculate the apect ratio of the image
src_w = float(image.size[0])
src_h = float(image.size[1])
src_ratio = src_w / src_h
if src_ratio < dest_ratio:
# Image is tall and thin - we need to scale to the right width and then crop
scale = dest_w / src_w
scaled_w = dest_w
scaled_h = src_h * scale
# Cropping values
left = 0
right = dest_w
top = (scaled_h - dest_h) / 2.0
bottom = top + dest_h
else:
# Image is short and wide - we need to scale to the right height and then crop
scale = dest_h / src_h
scaled_h = dest_h
scaled_w = src_w * scale
# Cropping values
left = (scaled_w - dest_w) / 2.0
right = left + dest_w
top = 0
bottom = dest_h
if pad_when_tall:
# Now, for images that are really tall and thin, we start to have issues as we only show a small section of them
# (i.e. nasonex). To deal with this we will resize and pad in this situation
if (bottom - top) < (scaled_h * 0.66):
log.info('Image would crop too much - returning padded image instead')
return resize_pad_image(image, dest_w, dest_h)
if src_w > dest_w or src_h > dest_h:
# This means we are shrinking the image which is ok!
scaled_image = image.resize((int(scaled_w), int(scaled_h)), PIL.Image.ANTIALIAS)
cropped_image = scaled_image.crop((int(left), int(top), int(right), int(bottom)))
return cropped_image
elif scaled_w < src_w or scaled_h < src_h:
# Just crop is as we don't want to stretch the image
cropped_image = image.crop((int(left), int(top), int(right), int(bottom)))
return cropped_image
else:
return image
|
def resize_crop_image(image, dest_w, dest_h, pad_when_tall=False):
"""
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:return: Scaled and cropped image
"""
# Now we need to resize it
dest_w = float(dest_w)
dest_h = float(dest_h)
dest_ratio = dest_w / dest_h
# Calculate the apect ratio of the image
src_w = float(image.size[0])
src_h = float(image.size[1])
src_ratio = src_w / src_h
if src_ratio < dest_ratio:
# Image is tall and thin - we need to scale to the right width and then crop
scale = dest_w / src_w
scaled_w = dest_w
scaled_h = src_h * scale
# Cropping values
left = 0
right = dest_w
top = (scaled_h - dest_h) / 2.0
bottom = top + dest_h
else:
# Image is short and wide - we need to scale to the right height and then crop
scale = dest_h / src_h
scaled_h = dest_h
scaled_w = src_w * scale
# Cropping values
left = (scaled_w - dest_w) / 2.0
right = left + dest_w
top = 0
bottom = dest_h
if pad_when_tall:
# Now, for images that are really tall and thin, we start to have issues as we only show a small section of them
# (i.e. nasonex). To deal with this we will resize and pad in this situation
if (bottom - top) < (scaled_h * 0.66):
log.info('Image would crop too much - returning padded image instead')
return resize_pad_image(image, dest_w, dest_h)
if src_w > dest_w or src_h > dest_h:
# This means we are shrinking the image which is ok!
scaled_image = image.resize((int(scaled_w), int(scaled_h)), PIL.Image.ANTIALIAS)
cropped_image = scaled_image.crop((int(left), int(top), int(right), int(bottom)))
return cropped_image
elif scaled_w < src_w or scaled_h < src_h:
# Just crop is as we don't want to stretch the image
cropped_image = image.crop((int(left), int(top), int(right), int(bottom)))
return cropped_image
else:
return image
|
[
":",
"param",
"image",
":",
"PIL",
".",
"Image",
":",
"param",
"dest_w",
":",
"Target",
"width",
":",
"param",
"dest_h",
":",
"Target",
"height",
":",
"return",
":",
"Scaled",
"and",
"cropped",
"image"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/imageutil.py#L50-L112
|
[
"def",
"resize_crop_image",
"(",
"image",
",",
"dest_w",
",",
"dest_h",
",",
"pad_when_tall",
"=",
"False",
")",
":",
"# Now we need to resize it",
"dest_w",
"=",
"float",
"(",
"dest_w",
")",
"dest_h",
"=",
"float",
"(",
"dest_h",
")",
"dest_ratio",
"=",
"dest_w",
"/",
"dest_h",
"# Calculate the apect ratio of the image",
"src_w",
"=",
"float",
"(",
"image",
".",
"size",
"[",
"0",
"]",
")",
"src_h",
"=",
"float",
"(",
"image",
".",
"size",
"[",
"1",
"]",
")",
"src_ratio",
"=",
"src_w",
"/",
"src_h",
"if",
"src_ratio",
"<",
"dest_ratio",
":",
"# Image is tall and thin - we need to scale to the right width and then crop",
"scale",
"=",
"dest_w",
"/",
"src_w",
"scaled_w",
"=",
"dest_w",
"scaled_h",
"=",
"src_h",
"*",
"scale",
"# Cropping values",
"left",
"=",
"0",
"right",
"=",
"dest_w",
"top",
"=",
"(",
"scaled_h",
"-",
"dest_h",
")",
"/",
"2.0",
"bottom",
"=",
"top",
"+",
"dest_h",
"else",
":",
"# Image is short and wide - we need to scale to the right height and then crop",
"scale",
"=",
"dest_h",
"/",
"src_h",
"scaled_h",
"=",
"dest_h",
"scaled_w",
"=",
"src_w",
"*",
"scale",
"# Cropping values",
"left",
"=",
"(",
"scaled_w",
"-",
"dest_w",
")",
"/",
"2.0",
"right",
"=",
"left",
"+",
"dest_w",
"top",
"=",
"0",
"bottom",
"=",
"dest_h",
"if",
"pad_when_tall",
":",
"# Now, for images that are really tall and thin, we start to have issues as we only show a small section of them",
"# (i.e. nasonex). To deal with this we will resize and pad in this situation",
"if",
"(",
"bottom",
"-",
"top",
")",
"<",
"(",
"scaled_h",
"*",
"0.66",
")",
":",
"log",
".",
"info",
"(",
"'Image would crop too much - returning padded image instead'",
")",
"return",
"resize_pad_image",
"(",
"image",
",",
"dest_w",
",",
"dest_h",
")",
"if",
"src_w",
">",
"dest_w",
"or",
"src_h",
">",
"dest_h",
":",
"# This means we are shrinking the image which is ok!",
"scaled_image",
"=",
"image",
".",
"resize",
"(",
"(",
"int",
"(",
"scaled_w",
")",
",",
"int",
"(",
"scaled_h",
")",
")",
",",
"PIL",
".",
"Image",
".",
"ANTIALIAS",
")",
"cropped_image",
"=",
"scaled_image",
".",
"crop",
"(",
"(",
"int",
"(",
"left",
")",
",",
"int",
"(",
"top",
")",
",",
"int",
"(",
"right",
")",
",",
"int",
"(",
"bottom",
")",
")",
")",
"return",
"cropped_image",
"elif",
"scaled_w",
"<",
"src_w",
"or",
"scaled_h",
"<",
"src_h",
":",
"# Just crop is as we don't want to stretch the image",
"cropped_image",
"=",
"image",
".",
"crop",
"(",
"(",
"int",
"(",
"left",
")",
",",
"int",
"(",
"top",
")",
",",
"int",
"(",
"right",
")",
",",
"int",
"(",
"bottom",
")",
")",
")",
"return",
"cropped_image",
"else",
":",
"return",
"image"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
resize_pad_image
|
Resize the image and pad to the correct aspect ratio.
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:param pad_with_transparent: If True, make additional padding transparent
:return: Scaled and padded image
|
littlefish/imageutil.py
|
def resize_pad_image(image, dest_w, dest_h, pad_with_transparent=False):
"""
Resize the image and pad to the correct aspect ratio.
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:param pad_with_transparent: If True, make additional padding transparent
:return: Scaled and padded image
"""
dest_w = float(dest_w)
dest_h = float(dest_h)
dest_ratio = dest_w / dest_h
# Calculate the apect ratio of the image
src_w = float(image.size[0])
src_h = float(image.size[1])
src_ratio = src_w / src_h
if src_ratio < dest_ratio:
# Image is tall and thin - we need to scale to the right height and then pad
scale = dest_h / src_h
scaled_h = dest_h
scaled_w = src_w * scale
offset = (int((dest_w - scaled_w) / 2), 0)
else:
# Image is short and wide - we need to scale to the right height and then crop
scale = dest_w / src_w
scaled_w = dest_w
scaled_h = src_h * scale
offset = (0, int((dest_h - scaled_h) / 2))
scaled_image = image.resize((int(scaled_w), int(scaled_h)), PIL.Image.ANTIALIAS)
# Normally we will want to copy the source mode for the destination image, but in some
# cases the source image will use a Palletted (mode=='P') in which case we need to change
# the mode
mode = scaled_image.mode
log.debug('Padding image with mode: "{}"'.format(mode))
if pad_with_transparent and mode != 'RGBA':
old_mode = mode
mode = 'RGBA'
scaled_image = scaled_image.convert(mode)
log.debug('Changed mode from "{}" to "{}"'.format(old_mode, mode))
elif mode == 'P':
if 'transparency' in scaled_image.info:
mode = 'RGBA'
else:
mode = 'RGB'
scaled_image = scaled_image.convert(mode)
log.debug('Changed mode from "P" to "{}"'.format(mode))
if pad_with_transparent:
pad_colour = (255, 255, 255, 0)
else:
# Get the pixel colour for coordinate (0,0)
pixels = scaled_image.load()
pad_colour = pixels[0, 0]
padded_image = PIL.Image.new(mode, (int(dest_w), int(dest_h)), pad_colour)
padded_image.paste(scaled_image, offset)
return padded_image
|
def resize_pad_image(image, dest_w, dest_h, pad_with_transparent=False):
"""
Resize the image and pad to the correct aspect ratio.
:param image: PIL.Image
:param dest_w: Target width
:param dest_h: Target height
:param pad_with_transparent: If True, make additional padding transparent
:return: Scaled and padded image
"""
dest_w = float(dest_w)
dest_h = float(dest_h)
dest_ratio = dest_w / dest_h
# Calculate the apect ratio of the image
src_w = float(image.size[0])
src_h = float(image.size[1])
src_ratio = src_w / src_h
if src_ratio < dest_ratio:
# Image is tall and thin - we need to scale to the right height and then pad
scale = dest_h / src_h
scaled_h = dest_h
scaled_w = src_w * scale
offset = (int((dest_w - scaled_w) / 2), 0)
else:
# Image is short and wide - we need to scale to the right height and then crop
scale = dest_w / src_w
scaled_w = dest_w
scaled_h = src_h * scale
offset = (0, int((dest_h - scaled_h) / 2))
scaled_image = image.resize((int(scaled_w), int(scaled_h)), PIL.Image.ANTIALIAS)
# Normally we will want to copy the source mode for the destination image, but in some
# cases the source image will use a Palletted (mode=='P') in which case we need to change
# the mode
mode = scaled_image.mode
log.debug('Padding image with mode: "{}"'.format(mode))
if pad_with_transparent and mode != 'RGBA':
old_mode = mode
mode = 'RGBA'
scaled_image = scaled_image.convert(mode)
log.debug('Changed mode from "{}" to "{}"'.format(old_mode, mode))
elif mode == 'P':
if 'transparency' in scaled_image.info:
mode = 'RGBA'
else:
mode = 'RGB'
scaled_image = scaled_image.convert(mode)
log.debug('Changed mode from "P" to "{}"'.format(mode))
if pad_with_transparent:
pad_colour = (255, 255, 255, 0)
else:
# Get the pixel colour for coordinate (0,0)
pixels = scaled_image.load()
pad_colour = pixels[0, 0]
padded_image = PIL.Image.new(mode, (int(dest_w), int(dest_h)), pad_colour)
padded_image.paste(scaled_image, offset)
return padded_image
|
[
"Resize",
"the",
"image",
"and",
"pad",
"to",
"the",
"correct",
"aspect",
"ratio",
".",
":",
"param",
"image",
":",
"PIL",
".",
"Image",
":",
"param",
"dest_w",
":",
"Target",
"width",
":",
"param",
"dest_h",
":",
"Target",
"height",
":",
"param",
"pad_with_transparent",
":",
"If",
"True",
"make",
"additional",
"padding",
"transparent"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/imageutil.py#L115-L181
|
[
"def",
"resize_pad_image",
"(",
"image",
",",
"dest_w",
",",
"dest_h",
",",
"pad_with_transparent",
"=",
"False",
")",
":",
"dest_w",
"=",
"float",
"(",
"dest_w",
")",
"dest_h",
"=",
"float",
"(",
"dest_h",
")",
"dest_ratio",
"=",
"dest_w",
"/",
"dest_h",
"# Calculate the apect ratio of the image",
"src_w",
"=",
"float",
"(",
"image",
".",
"size",
"[",
"0",
"]",
")",
"src_h",
"=",
"float",
"(",
"image",
".",
"size",
"[",
"1",
"]",
")",
"src_ratio",
"=",
"src_w",
"/",
"src_h",
"if",
"src_ratio",
"<",
"dest_ratio",
":",
"# Image is tall and thin - we need to scale to the right height and then pad",
"scale",
"=",
"dest_h",
"/",
"src_h",
"scaled_h",
"=",
"dest_h",
"scaled_w",
"=",
"src_w",
"*",
"scale",
"offset",
"=",
"(",
"int",
"(",
"(",
"dest_w",
"-",
"scaled_w",
")",
"/",
"2",
")",
",",
"0",
")",
"else",
":",
"# Image is short and wide - we need to scale to the right height and then crop",
"scale",
"=",
"dest_w",
"/",
"src_w",
"scaled_w",
"=",
"dest_w",
"scaled_h",
"=",
"src_h",
"*",
"scale",
"offset",
"=",
"(",
"0",
",",
"int",
"(",
"(",
"dest_h",
"-",
"scaled_h",
")",
"/",
"2",
")",
")",
"scaled_image",
"=",
"image",
".",
"resize",
"(",
"(",
"int",
"(",
"scaled_w",
")",
",",
"int",
"(",
"scaled_h",
")",
")",
",",
"PIL",
".",
"Image",
".",
"ANTIALIAS",
")",
"# Normally we will want to copy the source mode for the destination image, but in some",
"# cases the source image will use a Palletted (mode=='P') in which case we need to change",
"# the mode",
"mode",
"=",
"scaled_image",
".",
"mode",
"log",
".",
"debug",
"(",
"'Padding image with mode: \"{}\"'",
".",
"format",
"(",
"mode",
")",
")",
"if",
"pad_with_transparent",
"and",
"mode",
"!=",
"'RGBA'",
":",
"old_mode",
"=",
"mode",
"mode",
"=",
"'RGBA'",
"scaled_image",
"=",
"scaled_image",
".",
"convert",
"(",
"mode",
")",
"log",
".",
"debug",
"(",
"'Changed mode from \"{}\" to \"{}\"'",
".",
"format",
"(",
"old_mode",
",",
"mode",
")",
")",
"elif",
"mode",
"==",
"'P'",
":",
"if",
"'transparency'",
"in",
"scaled_image",
".",
"info",
":",
"mode",
"=",
"'RGBA'",
"else",
":",
"mode",
"=",
"'RGB'",
"scaled_image",
"=",
"scaled_image",
".",
"convert",
"(",
"mode",
")",
"log",
".",
"debug",
"(",
"'Changed mode from \"P\" to \"{}\"'",
".",
"format",
"(",
"mode",
")",
")",
"if",
"pad_with_transparent",
":",
"pad_colour",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"0",
")",
"else",
":",
"# Get the pixel colour for coordinate (0,0)",
"pixels",
"=",
"scaled_image",
".",
"load",
"(",
")",
"pad_colour",
"=",
"pixels",
"[",
"0",
",",
"0",
"]",
"padded_image",
"=",
"PIL",
".",
"Image",
".",
"new",
"(",
"mode",
",",
"(",
"int",
"(",
"dest_w",
")",
",",
"int",
"(",
"dest_h",
")",
")",
",",
"pad_colour",
")",
"padded_image",
".",
"paste",
"(",
"scaled_image",
",",
"offset",
")",
"return",
"padded_image"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
resize_image_to_fit_width
|
Resize and image to fit the passed in width, keeping the aspect ratio the same
:param image: PIL.Image
:param dest_w: The desired width
|
littlefish/imageutil.py
|
def resize_image_to_fit_width(image, dest_w):
"""
Resize and image to fit the passed in width, keeping the aspect ratio the same
:param image: PIL.Image
:param dest_w: The desired width
"""
scale_factor = dest_w / image.size[0]
dest_h = image.size[1] * scale_factor
scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)
return scaled_image
|
def resize_image_to_fit_width(image, dest_w):
"""
Resize and image to fit the passed in width, keeping the aspect ratio the same
:param image: PIL.Image
:param dest_w: The desired width
"""
scale_factor = dest_w / image.size[0]
dest_h = image.size[1] * scale_factor
scaled_image = image.resize((int(dest_w), int(dest_h)), PIL.Image.ANTIALIAS)
return scaled_image
|
[
"Resize",
"and",
"image",
"to",
"fit",
"the",
"passed",
"in",
"width",
"keeping",
"the",
"aspect",
"ratio",
"the",
"same"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/imageutil.py#L184-L196
|
[
"def",
"resize_image_to_fit_width",
"(",
"image",
",",
"dest_w",
")",
":",
"scale_factor",
"=",
"dest_w",
"/",
"image",
".",
"size",
"[",
"0",
"]",
"dest_h",
"=",
"image",
".",
"size",
"[",
"1",
"]",
"*",
"scale_factor",
"scaled_image",
"=",
"image",
".",
"resize",
"(",
"(",
"int",
"(",
"dest_w",
")",
",",
"int",
"(",
"dest_h",
")",
")",
",",
"PIL",
".",
"Image",
".",
"ANTIALIAS",
")",
"return",
"scaled_image"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
ParameterParser.add_value
|
Add a new value to the list.
:param str name: name of the value that is being parsed
:param str value: value that is being parsed
:raises ietfparse.errors.MalformedLinkValue:
if *strict mode* is enabled and a validation error
is detected
This method implements most of the validation mentioned in
sections 5.3 and 5.4 of :rfc:`5988`. The ``_rfc_values``
dictionary contains the appropriate values for the attributes
that get special handling. If *strict mode* is enabled, then
only values that are acceptable will be added to ``_values``.
|
ietfparse/_helpers.py
|
def add_value(self, name, value):
"""
Add a new value to the list.
:param str name: name of the value that is being parsed
:param str value: value that is being parsed
:raises ietfparse.errors.MalformedLinkValue:
if *strict mode* is enabled and a validation error
is detected
This method implements most of the validation mentioned in
sections 5.3 and 5.4 of :rfc:`5988`. The ``_rfc_values``
dictionary contains the appropriate values for the attributes
that get special handling. If *strict mode* is enabled, then
only values that are acceptable will be added to ``_values``.
"""
try:
if self._rfc_values[name] is None:
self._rfc_values[name] = value
elif self.strict:
if name in ('media', 'type'):
raise errors.MalformedLinkValue(
'More than one {} parameter present'.format(name))
return
except KeyError:
pass
if self.strict and name in ('title', 'title*'):
return
self._values.append((name, value))
|
def add_value(self, name, value):
"""
Add a new value to the list.
:param str name: name of the value that is being parsed
:param str value: value that is being parsed
:raises ietfparse.errors.MalformedLinkValue:
if *strict mode* is enabled and a validation error
is detected
This method implements most of the validation mentioned in
sections 5.3 and 5.4 of :rfc:`5988`. The ``_rfc_values``
dictionary contains the appropriate values for the attributes
that get special handling. If *strict mode* is enabled, then
only values that are acceptable will be added to ``_values``.
"""
try:
if self._rfc_values[name] is None:
self._rfc_values[name] = value
elif self.strict:
if name in ('media', 'type'):
raise errors.MalformedLinkValue(
'More than one {} parameter present'.format(name))
return
except KeyError:
pass
if self.strict and name in ('title', 'title*'):
return
self._values.append((name, value))
|
[
"Add",
"a",
"new",
"value",
"to",
"the",
"list",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/_helpers.py#L49-L80
|
[
"def",
"add_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"try",
":",
"if",
"self",
".",
"_rfc_values",
"[",
"name",
"]",
"is",
"None",
":",
"self",
".",
"_rfc_values",
"[",
"name",
"]",
"=",
"value",
"elif",
"self",
".",
"strict",
":",
"if",
"name",
"in",
"(",
"'media'",
",",
"'type'",
")",
":",
"raise",
"errors",
".",
"MalformedLinkValue",
"(",
"'More than one {} parameter present'",
".",
"format",
"(",
"name",
")",
")",
"return",
"except",
"KeyError",
":",
"pass",
"if",
"self",
".",
"strict",
"and",
"name",
"in",
"(",
"'title'",
",",
"'title*'",
")",
":",
"return",
"self",
".",
"_values",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
ParameterParser.values
|
The name/value mapping that was parsed.
:returns: a sequence of name/value pairs.
|
ietfparse/_helpers.py
|
def values(self):
"""
The name/value mapping that was parsed.
:returns: a sequence of name/value pairs.
"""
values = self._values[:]
if self.strict:
if self._rfc_values['title*']:
values.append(('title*', self._rfc_values['title*']))
if self._rfc_values['title']:
values.append(('title', self._rfc_values['title*']))
elif self._rfc_values['title']:
values.append(('title', self._rfc_values['title']))
return values
|
def values(self):
"""
The name/value mapping that was parsed.
:returns: a sequence of name/value pairs.
"""
values = self._values[:]
if self.strict:
if self._rfc_values['title*']:
values.append(('title*', self._rfc_values['title*']))
if self._rfc_values['title']:
values.append(('title', self._rfc_values['title*']))
elif self._rfc_values['title']:
values.append(('title', self._rfc_values['title']))
return values
|
[
"The",
"name",
"/",
"value",
"mapping",
"that",
"was",
"parsed",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/_helpers.py#L83-L98
|
[
"def",
"values",
"(",
"self",
")",
":",
"values",
"=",
"self",
".",
"_values",
"[",
":",
"]",
"if",
"self",
".",
"strict",
":",
"if",
"self",
".",
"_rfc_values",
"[",
"'title*'",
"]",
":",
"values",
".",
"append",
"(",
"(",
"'title*'",
",",
"self",
".",
"_rfc_values",
"[",
"'title*'",
"]",
")",
")",
"if",
"self",
".",
"_rfc_values",
"[",
"'title'",
"]",
":",
"values",
".",
"append",
"(",
"(",
"'title'",
",",
"self",
".",
"_rfc_values",
"[",
"'title*'",
"]",
")",
")",
"elif",
"self",
".",
"_rfc_values",
"[",
"'title'",
"]",
":",
"values",
".",
"append",
"(",
"(",
"'title'",
",",
"self",
".",
"_rfc_values",
"[",
"'title'",
"]",
")",
")",
"return",
"values"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
Youtube.download
|
Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage
|
music2storage/service.py
|
def download(self, url):
"""
Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage
"""
try:
yt = YouTube(url)
except RegexMatchError:
log.error(f"Cannot download file at {url}")
else:
stream = yt.streams.first()
log.info(f"Download for {stream.default_filename} has started")
start_time = time()
stream.download()
end_time = time()
log.info(f"Download for {stream.default_filename} has finished in {end_time - start_time} seconds")
return stream.default_filename
|
def download(self, url):
"""
Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage
"""
try:
yt = YouTube(url)
except RegexMatchError:
log.error(f"Cannot download file at {url}")
else:
stream = yt.streams.first()
log.info(f"Download for {stream.default_filename} has started")
start_time = time()
stream.download()
end_time = time()
log.info(f"Download for {stream.default_filename} has finished in {end_time - start_time} seconds")
return stream.default_filename
|
[
"Downloads",
"a",
"MP4",
"or",
"WebM",
"file",
"that",
"is",
"associated",
"with",
"the",
"video",
"at",
"the",
"URL",
"passed",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/service.py#L49-L68
|
[
"def",
"download",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"yt",
"=",
"YouTube",
"(",
"url",
")",
"except",
"RegexMatchError",
":",
"log",
".",
"error",
"(",
"f\"Cannot download file at {url}\"",
")",
"else",
":",
"stream",
"=",
"yt",
".",
"streams",
".",
"first",
"(",
")",
"log",
".",
"info",
"(",
"f\"Download for {stream.default_filename} has started\"",
")",
"start_time",
"=",
"time",
"(",
")",
"stream",
".",
"download",
"(",
")",
"end_time",
"=",
"time",
"(",
")",
"log",
".",
"info",
"(",
"f\"Download for {stream.default_filename} has finished in {end_time - start_time} seconds\"",
")",
"return",
"stream",
".",
"default_filename"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
Soundcloud.download
|
Downloads a MP3 file that is associated with the track at the URL passed.
:param str url: URL of the track to be downloaded
|
music2storage/service.py
|
def download(self, url):
"""
Downloads a MP3 file that is associated with the track at the URL passed.
:param str url: URL of the track to be downloaded
"""
try:
track = self.client.get('/resolve', url=url)
except HTTPError:
log.error(f"{url} is not a Soundcloud URL.")
return
r = requests.get(self.client.get(track.stream_url, allow_redirects=False).location, stream=True)
total_size = int(r.headers['content-length'])
chunk_size = 1000000
file_name = track.title + '.mp3'
with open(file_name, 'wb') as f:
for data in tqdm(r.iter_content(chunk_size), desc=track.title, total=total_size / chunk_size, unit='MB', file=sys.stdout):
f.write(data)
return file_name
|
def download(self, url):
"""
Downloads a MP3 file that is associated with the track at the URL passed.
:param str url: URL of the track to be downloaded
"""
try:
track = self.client.get('/resolve', url=url)
except HTTPError:
log.error(f"{url} is not a Soundcloud URL.")
return
r = requests.get(self.client.get(track.stream_url, allow_redirects=False).location, stream=True)
total_size = int(r.headers['content-length'])
chunk_size = 1000000
file_name = track.title + '.mp3'
with open(file_name, 'wb') as f:
for data in tqdm(r.iter_content(chunk_size), desc=track.title, total=total_size / chunk_size, unit='MB', file=sys.stdout):
f.write(data)
return file_name
|
[
"Downloads",
"a",
"MP3",
"file",
"that",
"is",
"associated",
"with",
"the",
"track",
"at",
"the",
"URL",
"passed",
".",
":",
"param",
"str",
"url",
":",
"URL",
"of",
"the",
"track",
"to",
"be",
"downloaded"
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/service.py#L82-L101
|
[
"def",
"download",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"track",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/resolve'",
",",
"url",
"=",
"url",
")",
"except",
"HTTPError",
":",
"log",
".",
"error",
"(",
"f\"{url} is not a Soundcloud URL.\"",
")",
"return",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"client",
".",
"get",
"(",
"track",
".",
"stream_url",
",",
"allow_redirects",
"=",
"False",
")",
".",
"location",
",",
"stream",
"=",
"True",
")",
"total_size",
"=",
"int",
"(",
"r",
".",
"headers",
"[",
"'content-length'",
"]",
")",
"chunk_size",
"=",
"1000000",
"file_name",
"=",
"track",
".",
"title",
"+",
"'.mp3'",
"with",
"open",
"(",
"file_name",
",",
"'wb'",
")",
"as",
"f",
":",
"for",
"data",
"in",
"tqdm",
"(",
"r",
".",
"iter_content",
"(",
"chunk_size",
")",
",",
"desc",
"=",
"track",
".",
"title",
",",
"total",
"=",
"total_size",
"/",
"chunk_size",
",",
"unit",
"=",
"'MB'",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"f",
".",
"write",
"(",
"data",
")",
"return",
"file_name"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
GoogleDrive.connect
|
Creates connection to the Google Drive API, sets the connection attribute to make requests, and creates the Music folder if it doesn't exist.
|
music2storage/service.py
|
def connect(self):
"""Creates connection to the Google Drive API, sets the connection attribute to make requests, and creates the Music folder if it doesn't exist."""
SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('drive_credentials.json')
creds = store.get()
if not creds or creds.invalid:
try:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
except InvalidClientSecretsError:
log.error('ERROR: Could not find client_secret.json in current directory, please obtain it from the API console.')
return
creds = tools.run_flow(flow, store)
self.connection = build('drive', 'v3', http=creds.authorize(Http()))
response = self.connection.files().list(q="name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false").execute()
try:
folder_id = response.get('files', [])[0]['id']
except IndexError:
log.warning('Music folder is missing. Creating it.')
folder_metadata = {'name': 'Music', 'mimeType': 'application/vnd.google-apps.folder'}
folder = self.connection.files().create(body=folder_metadata, fields='id').execute()
|
def connect(self):
"""Creates connection to the Google Drive API, sets the connection attribute to make requests, and creates the Music folder if it doesn't exist."""
SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('drive_credentials.json')
creds = store.get()
if not creds or creds.invalid:
try:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
except InvalidClientSecretsError:
log.error('ERROR: Could not find client_secret.json in current directory, please obtain it from the API console.')
return
creds = tools.run_flow(flow, store)
self.connection = build('drive', 'v3', http=creds.authorize(Http()))
response = self.connection.files().list(q="name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false").execute()
try:
folder_id = response.get('files', [])[0]['id']
except IndexError:
log.warning('Music folder is missing. Creating it.')
folder_metadata = {'name': 'Music', 'mimeType': 'application/vnd.google-apps.folder'}
folder = self.connection.files().create(body=folder_metadata, fields='id').execute()
|
[
"Creates",
"connection",
"to",
"the",
"Google",
"Drive",
"API",
"sets",
"the",
"connection",
"attribute",
"to",
"make",
"requests",
"and",
"creates",
"the",
"Music",
"folder",
"if",
"it",
"doesn",
"t",
"exist",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/service.py#L111-L132
|
[
"def",
"connect",
"(",
"self",
")",
":",
"SCOPES",
"=",
"'https://www.googleapis.com/auth/drive'",
"store",
"=",
"file",
".",
"Storage",
"(",
"'drive_credentials.json'",
")",
"creds",
"=",
"store",
".",
"get",
"(",
")",
"if",
"not",
"creds",
"or",
"creds",
".",
"invalid",
":",
"try",
":",
"flow",
"=",
"client",
".",
"flow_from_clientsecrets",
"(",
"'client_secret.json'",
",",
"SCOPES",
")",
"except",
"InvalidClientSecretsError",
":",
"log",
".",
"error",
"(",
"'ERROR: Could not find client_secret.json in current directory, please obtain it from the API console.'",
")",
"return",
"creds",
"=",
"tools",
".",
"run_flow",
"(",
"flow",
",",
"store",
")",
"self",
".",
"connection",
"=",
"build",
"(",
"'drive'",
",",
"'v3'",
",",
"http",
"=",
"creds",
".",
"authorize",
"(",
"Http",
"(",
")",
")",
")",
"response",
"=",
"self",
".",
"connection",
".",
"files",
"(",
")",
".",
"list",
"(",
"q",
"=",
"\"name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false\"",
")",
".",
"execute",
"(",
")",
"try",
":",
"folder_id",
"=",
"response",
".",
"get",
"(",
"'files'",
",",
"[",
"]",
")",
"[",
"0",
"]",
"[",
"'id'",
"]",
"except",
"IndexError",
":",
"log",
".",
"warning",
"(",
"'Music folder is missing. Creating it.'",
")",
"folder_metadata",
"=",
"{",
"'name'",
":",
"'Music'",
",",
"'mimeType'",
":",
"'application/vnd.google-apps.folder'",
"}",
"folder",
"=",
"self",
".",
"connection",
".",
"files",
"(",
")",
".",
"create",
"(",
"body",
"=",
"folder_metadata",
",",
"fields",
"=",
"'id'",
")",
".",
"execute",
"(",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
GoogleDrive.upload
|
Uploads the file associated with the file_name passed to Google Drive in the Music folder.
:param str file_name: Filename of the file to be uploaded
:return str: Original filename passed as an argument (in order for the worker to send it to the delete queue)
|
music2storage/service.py
|
def upload(self, file_name):
"""
Uploads the file associated with the file_name passed to Google Drive in the Music folder.
:param str file_name: Filename of the file to be uploaded
:return str: Original filename passed as an argument (in order for the worker to send it to the delete queue)
"""
response = self.connection.files().list(q="name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false").execute()
folder_id = response.get('files', [])[0]['id']
file_metadata = {'name': file_name, 'parents': [folder_id]}
media = MediaFileUpload(file_name, mimetype='audio/mpeg')
log.info(f"Upload for {file_name} has started")
start_time = time()
self.connection.files().create(body=file_metadata, media_body=media, fields='id').execute()
end_time = time()
log.info(f"Upload for {file_name} has finished in {end_time - start_time} seconds")
return file_name
|
def upload(self, file_name):
"""
Uploads the file associated with the file_name passed to Google Drive in the Music folder.
:param str file_name: Filename of the file to be uploaded
:return str: Original filename passed as an argument (in order for the worker to send it to the delete queue)
"""
response = self.connection.files().list(q="name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false").execute()
folder_id = response.get('files', [])[0]['id']
file_metadata = {'name': file_name, 'parents': [folder_id]}
media = MediaFileUpload(file_name, mimetype='audio/mpeg')
log.info(f"Upload for {file_name} has started")
start_time = time()
self.connection.files().create(body=file_metadata, media_body=media, fields='id').execute()
end_time = time()
log.info(f"Upload for {file_name} has finished in {end_time - start_time} seconds")
return file_name
|
[
"Uploads",
"the",
"file",
"associated",
"with",
"the",
"file_name",
"passed",
"to",
"Google",
"Drive",
"in",
"the",
"Music",
"folder",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/service.py#L134-L153
|
[
"def",
"upload",
"(",
"self",
",",
"file_name",
")",
":",
"response",
"=",
"self",
".",
"connection",
".",
"files",
"(",
")",
".",
"list",
"(",
"q",
"=",
"\"name='Music' and mimeType='application/vnd.google-apps.folder' and trashed=false\"",
")",
".",
"execute",
"(",
")",
"folder_id",
"=",
"response",
".",
"get",
"(",
"'files'",
",",
"[",
"]",
")",
"[",
"0",
"]",
"[",
"'id'",
"]",
"file_metadata",
"=",
"{",
"'name'",
":",
"file_name",
",",
"'parents'",
":",
"[",
"folder_id",
"]",
"}",
"media",
"=",
"MediaFileUpload",
"(",
"file_name",
",",
"mimetype",
"=",
"'audio/mpeg'",
")",
"log",
".",
"info",
"(",
"f\"Upload for {file_name} has started\"",
")",
"start_time",
"=",
"time",
"(",
")",
"self",
".",
"connection",
".",
"files",
"(",
")",
".",
"create",
"(",
"body",
"=",
"file_metadata",
",",
"media_body",
"=",
"media",
",",
"fields",
"=",
"'id'",
")",
".",
"execute",
"(",
")",
"end_time",
"=",
"time",
"(",
")",
"log",
".",
"info",
"(",
"f\"Upload for {file_name} has finished in {end_time - start_time} seconds\"",
")",
"return",
"file_name"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
LocalStorage.connect
|
Initializes the connection attribute with the path to the user home folder's Music folder, and creates it if it doesn't exist.
|
music2storage/service.py
|
def connect(self):
"""Initializes the connection attribute with the path to the user home folder's Music folder, and creates it if it doesn't exist."""
if self.music_folder is None:
music_folder = os.path.join(os.path.expanduser('~'), 'Music')
if not os.path.exists(music_folder):
os.makedirs(music_folder)
self.music_folder = music_folder
|
def connect(self):
"""Initializes the connection attribute with the path to the user home folder's Music folder, and creates it if it doesn't exist."""
if self.music_folder is None:
music_folder = os.path.join(os.path.expanduser('~'), 'Music')
if not os.path.exists(music_folder):
os.makedirs(music_folder)
self.music_folder = music_folder
|
[
"Initializes",
"the",
"connection",
"attribute",
"with",
"the",
"path",
"to",
"the",
"user",
"home",
"folder",
"s",
"Music",
"folder",
"and",
"creates",
"it",
"if",
"it",
"doesn",
"t",
"exist",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/service.py#L167-L174
|
[
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"music_folder",
"is",
"None",
":",
"music_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'Music'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"music_folder",
")",
":",
"os",
".",
"makedirs",
"(",
"music_folder",
")",
"self",
".",
"music_folder",
"=",
"music_folder"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
LocalStorage.upload
|
Moves the file associated with the file_name passed to the Music folder in the local storage.
:param str file_name: Filename of the file to be uploaded
|
music2storage/service.py
|
def upload(self, file_name):
"""
Moves the file associated with the file_name passed to the Music folder in the local storage.
:param str file_name: Filename of the file to be uploaded
"""
log.info(f"Upload for {file_name} has started")
start_time = time()
os.rename(file_name, os.path.join(self.music_folder, file_name))
end_time = time()
log.info(f"Upload for {file_name} has finished in {end_time - start_time} seconds")
|
def upload(self, file_name):
"""
Moves the file associated with the file_name passed to the Music folder in the local storage.
:param str file_name: Filename of the file to be uploaded
"""
log.info(f"Upload for {file_name} has started")
start_time = time()
os.rename(file_name, os.path.join(self.music_folder, file_name))
end_time = time()
log.info(f"Upload for {file_name} has finished in {end_time - start_time} seconds")
|
[
"Moves",
"the",
"file",
"associated",
"with",
"the",
"file_name",
"passed",
"to",
"the",
"Music",
"folder",
"in",
"the",
"local",
"storage",
".",
":",
"param",
"str",
"file_name",
":",
"Filename",
"of",
"the",
"file",
"to",
"be",
"uploaded"
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/service.py#L176-L187
|
[
"def",
"upload",
"(",
"self",
",",
"file_name",
")",
":",
"log",
".",
"info",
"(",
"f\"Upload for {file_name} has started\"",
")",
"start_time",
"=",
"time",
"(",
")",
"os",
".",
"rename",
"(",
"file_name",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"music_folder",
",",
"file_name",
")",
")",
"end_time",
"=",
"time",
"(",
")",
"log",
".",
"info",
"(",
"f\"Upload for {file_name} has finished in {end_time - start_time} seconds\"",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
RunParameters.write_run_parameters_to_file
|
All of the class properties are written to a text file
Each property is on a new line with the key and value seperated with an equals sign '='
This is the mane planarrad properties file used by slabtool
|
libplanarradpy/planrad.py
|
def write_run_parameters_to_file(self):
"""All of the class properties are written to a text file
Each property is on a new line with the key and value seperated with an equals sign '='
This is the mane planarrad properties file used by slabtool
"""
self.update_filenames()
lg.info('Writing Inputs to file : ' + self.project_file)
# First update the file names in case we changed the file values. the file name includes the file values
# self.updateFileNames()
f = open(self.project_file, 'w')
f.write('name = ' + self.project_file + '\n')
f.write('band_count = ' + str(len(self.wavelengths)) + '\n')
f.write('bs_name = ' + str(len(self.wavelengths)) + ' Bands (' + str(self.wavelengths[0]) + '-' + str(
self.wavelengths[len(self.wavelengths) - 1]) + ' nm) \n')
f.write('bs_code = ' + str(len(self.wavelengths)) + '\n')
f.write('band_centres_data = ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
# f.write('band_widths_data = ')
# for i in range(0, len(self.wavelengths) - 1): # Find better way to do this!
# width = self.wavelengths[i + 1] - self.wavelengths[i]
# f.write(str(width))
# if i < len(self.wavelengths) - 2:
# f.write(',')
f.write('\n')
f.write('ds_name = ' + self.ds_name + '\n')
f.write('ds_code = ' + self.ds_code + '\n')
f.write('partition = ' + self.partition + '\n')
f.write('vn = ' + str(self.vn) + '\n')
f.write('hn = ' + str(self.hn) + '\n')
f.write('theta_points=')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('depth = ' + str(self.depth) + '\n')
f.write('sample_point_distance = ' + str(self.sample_point_distance) + '\n')
f.write('sample_point_delta_distance = ' + str(self.sample_point_delta_distance) + '\n')
f.write('\n')
f.write('sky_fp = ' + self.sky_file + '\n') # need to create these files from sky tool
f.write('water_surface_fp =' + self.water_surface_file)
f.write('\n')
f.write('atten_fp = ' + self.attenuation_file + '\n')
f.write('scat_fp = ' + self.scattering_file + '\n')
f.write('pf_fp = ' + self.phase_function_file + '\n')
f.write('bottom_reflec_diffuse_fp = ' + self.bottom_reflectance_file + '\n')
f.write('sky_type = ' + self.sky_type + '\n')
f.write('sky_azimuth = ' + str(self.sky_azimuth) + '\n')
f.write('sky_zenith = ' + str(self.sky_zenith) + '\n')
f.write('sky_C = ' + str(self.sky_c) + '\n')
f.write('sky_rdif = ' + str(self.sky_r_dif) + '\n')
f.write('iface_type = ' + self.iface_type + '\n')
f.write('iface_refrac_index_0 = ' + str(self.iface_0_ri) + '\n')
f.write('iface_refrac_index_1 = ' + str(self.iface_1_ri) + '\n')
# f.write('iop_atten_data = 1\n')
# f.write('iop_absorp_data = 0\n')
f.write('iop_type = ' + self.iop_type + '\n')
f.write('iop_backscatter_proportion_list = ' + str(self.iop_backscatter_proportion_list) + '\n')
f.write('bound_bottom_reflec_diffuse_data = ' + str(self.bound_bottom_reflec_diffuse_data) + '\n')
f.write('sky_sub_quad_count = ' + self.sky_sub_quad_count + '\n')
f.write('iface_sub_quad_count = ' + self.iface_sub_quad_count + '\n')
f.write('pf_sub_quad_count = ' + self.pf_sub_quad_count + '\n')
f.write('integrator = ' + self.integrator + '\n')
f.write('euler_steps_per_optical_depth = ' + str(self.euler_steps_per_optical_depth) + '\n')
f.write('midpoint_steps_per_optical_depth = ' + str(self.midpoint_steps_per_optical_depth) + '\n')
f.write('runga4_steps_per_optical_depth = ' + str(self.runga4_steps_per_optical_depth) + '\n')
f.write('runga4adap_min_steps_per_optical_depth = ' + str(self.runga4adap_min_steps_per_optical_depth) + '\n')
f.write('runga4adap_max_steps_per_optical_depth = ' + str(self.runga4adap_max_steps_per_optical_depth) + '\n')
f.write('runga4adap_min_error = ' + str(self.runga4adap_min_error) + '\n')
f.write('runga4adap_max_error = ' + str(self.runga4adap_max_error) + '\n')
f.write('\n')
f.write('Ld_b_image_save_fp = ' + os.path.join(self.output_path,
'image_Ld_b.ppm') + '\n') #todo update this in the constructor not here
f.write('Ld_b_image_sens_k = ' + str(self.ld_b_image_sens_k) + '\n')
f.write('\n')
f.write('Ld_b_save_fp = ' + os.path.join(self.output_path,
'Ld_b_data') + '\n')
f.write('\n')
f.write('report_save_fp = ' + self.report_file)
f.write('\n')
f.write('verbose = ' + str(self.verbose) + '\n')
f.close()
|
def write_run_parameters_to_file(self):
"""All of the class properties are written to a text file
Each property is on a new line with the key and value seperated with an equals sign '='
This is the mane planarrad properties file used by slabtool
"""
self.update_filenames()
lg.info('Writing Inputs to file : ' + self.project_file)
# First update the file names in case we changed the file values. the file name includes the file values
# self.updateFileNames()
f = open(self.project_file, 'w')
f.write('name = ' + self.project_file + '\n')
f.write('band_count = ' + str(len(self.wavelengths)) + '\n')
f.write('bs_name = ' + str(len(self.wavelengths)) + ' Bands (' + str(self.wavelengths[0]) + '-' + str(
self.wavelengths[len(self.wavelengths) - 1]) + ' nm) \n')
f.write('bs_code = ' + str(len(self.wavelengths)) + '\n')
f.write('band_centres_data = ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
# f.write('band_widths_data = ')
# for i in range(0, len(self.wavelengths) - 1): # Find better way to do this!
# width = self.wavelengths[i + 1] - self.wavelengths[i]
# f.write(str(width))
# if i < len(self.wavelengths) - 2:
# f.write(',')
f.write('\n')
f.write('ds_name = ' + self.ds_name + '\n')
f.write('ds_code = ' + self.ds_code + '\n')
f.write('partition = ' + self.partition + '\n')
f.write('vn = ' + str(self.vn) + '\n')
f.write('hn = ' + str(self.hn) + '\n')
f.write('theta_points=')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('depth = ' + str(self.depth) + '\n')
f.write('sample_point_distance = ' + str(self.sample_point_distance) + '\n')
f.write('sample_point_delta_distance = ' + str(self.sample_point_delta_distance) + '\n')
f.write('\n')
f.write('sky_fp = ' + self.sky_file + '\n') # need to create these files from sky tool
f.write('water_surface_fp =' + self.water_surface_file)
f.write('\n')
f.write('atten_fp = ' + self.attenuation_file + '\n')
f.write('scat_fp = ' + self.scattering_file + '\n')
f.write('pf_fp = ' + self.phase_function_file + '\n')
f.write('bottom_reflec_diffuse_fp = ' + self.bottom_reflectance_file + '\n')
f.write('sky_type = ' + self.sky_type + '\n')
f.write('sky_azimuth = ' + str(self.sky_azimuth) + '\n')
f.write('sky_zenith = ' + str(self.sky_zenith) + '\n')
f.write('sky_C = ' + str(self.sky_c) + '\n')
f.write('sky_rdif = ' + str(self.sky_r_dif) + '\n')
f.write('iface_type = ' + self.iface_type + '\n')
f.write('iface_refrac_index_0 = ' + str(self.iface_0_ri) + '\n')
f.write('iface_refrac_index_1 = ' + str(self.iface_1_ri) + '\n')
# f.write('iop_atten_data = 1\n')
# f.write('iop_absorp_data = 0\n')
f.write('iop_type = ' + self.iop_type + '\n')
f.write('iop_backscatter_proportion_list = ' + str(self.iop_backscatter_proportion_list) + '\n')
f.write('bound_bottom_reflec_diffuse_data = ' + str(self.bound_bottom_reflec_diffuse_data) + '\n')
f.write('sky_sub_quad_count = ' + self.sky_sub_quad_count + '\n')
f.write('iface_sub_quad_count = ' + self.iface_sub_quad_count + '\n')
f.write('pf_sub_quad_count = ' + self.pf_sub_quad_count + '\n')
f.write('integrator = ' + self.integrator + '\n')
f.write('euler_steps_per_optical_depth = ' + str(self.euler_steps_per_optical_depth) + '\n')
f.write('midpoint_steps_per_optical_depth = ' + str(self.midpoint_steps_per_optical_depth) + '\n')
f.write('runga4_steps_per_optical_depth = ' + str(self.runga4_steps_per_optical_depth) + '\n')
f.write('runga4adap_min_steps_per_optical_depth = ' + str(self.runga4adap_min_steps_per_optical_depth) + '\n')
f.write('runga4adap_max_steps_per_optical_depth = ' + str(self.runga4adap_max_steps_per_optical_depth) + '\n')
f.write('runga4adap_min_error = ' + str(self.runga4adap_min_error) + '\n')
f.write('runga4adap_max_error = ' + str(self.runga4adap_max_error) + '\n')
f.write('\n')
f.write('Ld_b_image_save_fp = ' + os.path.join(self.output_path,
'image_Ld_b.ppm') + '\n') #todo update this in the constructor not here
f.write('Ld_b_image_sens_k = ' + str(self.ld_b_image_sens_k) + '\n')
f.write('\n')
f.write('Ld_b_save_fp = ' + os.path.join(self.output_path,
'Ld_b_data') + '\n')
f.write('\n')
f.write('report_save_fp = ' + self.report_file)
f.write('\n')
f.write('verbose = ' + str(self.verbose) + '\n')
f.close()
|
[
"All",
"of",
"the",
"class",
"properties",
"are",
"written",
"to",
"a",
"text",
"file"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L147-L232
|
[
"def",
"write_run_parameters_to_file",
"(",
"self",
")",
":",
"self",
".",
"update_filenames",
"(",
")",
"lg",
".",
"info",
"(",
"'Writing Inputs to file : '",
"+",
"self",
".",
"project_file",
")",
"# First update the file names in case we changed the file values. the file name includes the file values",
"# self.updateFileNames()",
"f",
"=",
"open",
"(",
"self",
".",
"project_file",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"'name = '",
"+",
"self",
".",
"project_file",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_count = '",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"wavelengths",
")",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'bs_name = '",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"wavelengths",
")",
")",
"+",
"' Bands ('",
"+",
"str",
"(",
"self",
".",
"wavelengths",
"[",
"0",
"]",
")",
"+",
"'-'",
"+",
"str",
"(",
"self",
".",
"wavelengths",
"[",
"len",
"(",
"self",
".",
"wavelengths",
")",
"-",
"1",
"]",
")",
"+",
"' nm) \\n'",
")",
"f",
".",
"write",
"(",
"'bs_code = '",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"wavelengths",
")",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_centres_data = '",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"wave",
")",
"for",
"wave",
"in",
"self",
".",
"wavelengths",
"]",
")",
"+",
"'\\n'",
")",
"# f.write('band_widths_data = ')",
"# for i in range(0, len(self.wavelengths) - 1): # Find better way to do this!",
"# width = self.wavelengths[i + 1] - self.wavelengths[i]",
"# f.write(str(width))",
"# if i < len(self.wavelengths) - 2:",
"# f.write(',')",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'ds_name = '",
"+",
"self",
".",
"ds_name",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'ds_code = '",
"+",
"self",
".",
"ds_code",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'partition = '",
"+",
"self",
".",
"partition",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'vn = '",
"+",
"str",
"(",
"self",
".",
"vn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'hn = '",
"+",
"str",
"(",
"self",
".",
"hn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'theta_points='",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"theta",
")",
"for",
"theta",
"in",
"self",
".",
"theta_points",
"]",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'depth = '",
"+",
"str",
"(",
"self",
".",
"depth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sample_point_distance = '",
"+",
"str",
"(",
"self",
".",
"sample_point_distance",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sample_point_delta_distance = '",
"+",
"str",
"(",
"self",
".",
"sample_point_delta_distance",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_fp = '",
"+",
"self",
".",
"sky_file",
"+",
"'\\n'",
")",
"# need to create these files from sky tool",
"f",
".",
"write",
"(",
"'water_surface_fp ='",
"+",
"self",
".",
"water_surface_file",
")",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'atten_fp = '",
"+",
"self",
".",
"attenuation_file",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'scat_fp = '",
"+",
"self",
".",
"scattering_file",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'pf_fp = '",
"+",
"self",
".",
"phase_function_file",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'bottom_reflec_diffuse_fp = '",
"+",
"self",
".",
"bottom_reflectance_file",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_type = '",
"+",
"self",
".",
"sky_type",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_azimuth = '",
"+",
"str",
"(",
"self",
".",
"sky_azimuth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_zenith = '",
"+",
"str",
"(",
"self",
".",
"sky_zenith",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_C = '",
"+",
"str",
"(",
"self",
".",
"sky_c",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_rdif = '",
"+",
"str",
"(",
"self",
".",
"sky_r_dif",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'iface_type = '",
"+",
"self",
".",
"iface_type",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'iface_refrac_index_0 = '",
"+",
"str",
"(",
"self",
".",
"iface_0_ri",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'iface_refrac_index_1 = '",
"+",
"str",
"(",
"self",
".",
"iface_1_ri",
")",
"+",
"'\\n'",
")",
"# f.write('iop_atten_data = 1\\n')",
"# f.write('iop_absorp_data = 0\\n')",
"f",
".",
"write",
"(",
"'iop_type = '",
"+",
"self",
".",
"iop_type",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'iop_backscatter_proportion_list = '",
"+",
"str",
"(",
"self",
".",
"iop_backscatter_proportion_list",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'bound_bottom_reflec_diffuse_data = '",
"+",
"str",
"(",
"self",
".",
"bound_bottom_reflec_diffuse_data",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_sub_quad_count = '",
"+",
"self",
".",
"sky_sub_quad_count",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'iface_sub_quad_count = '",
"+",
"self",
".",
"iface_sub_quad_count",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'pf_sub_quad_count = '",
"+",
"self",
".",
"pf_sub_quad_count",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'integrator = '",
"+",
"self",
".",
"integrator",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'euler_steps_per_optical_depth = '",
"+",
"str",
"(",
"self",
".",
"euler_steps_per_optical_depth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'midpoint_steps_per_optical_depth = '",
"+",
"str",
"(",
"self",
".",
"midpoint_steps_per_optical_depth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'runga4_steps_per_optical_depth = '",
"+",
"str",
"(",
"self",
".",
"runga4_steps_per_optical_depth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'runga4adap_min_steps_per_optical_depth = '",
"+",
"str",
"(",
"self",
".",
"runga4adap_min_steps_per_optical_depth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'runga4adap_max_steps_per_optical_depth = '",
"+",
"str",
"(",
"self",
".",
"runga4adap_max_steps_per_optical_depth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'runga4adap_min_error = '",
"+",
"str",
"(",
"self",
".",
"runga4adap_min_error",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'runga4adap_max_error = '",
"+",
"str",
"(",
"self",
".",
"runga4adap_max_error",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'Ld_b_image_save_fp = '",
"+",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output_path",
",",
"'image_Ld_b.ppm'",
")",
"+",
"'\\n'",
")",
"#todo update this in the constructor not here",
"f",
".",
"write",
"(",
"'Ld_b_image_sens_k = '",
"+",
"str",
"(",
"self",
".",
"ld_b_image_sens_k",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'Ld_b_save_fp = '",
"+",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output_path",
",",
"'Ld_b_data'",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'report_save_fp = '",
"+",
"self",
".",
"report_file",
")",
"f",
".",
"write",
"(",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'verbose = '",
"+",
"str",
"(",
"self",
".",
"verbose",
")",
"+",
"'\\n'",
")",
"f",
".",
"close",
"(",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
RunParameters.write_sky_params_to_file
|
Writes the params to file that skytool_Free needs to generate the sky radiance distribution.
|
libplanarradpy/planrad.py
|
def write_sky_params_to_file(self):
"""Writes the params to file that skytool_Free needs to generate the sky radiance distribution."""
inp_file = self.sky_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
f = open(inp_file, 'w')
f.write('verbose= ' + str(self.verbose) + '\n')
f.write('band_count= ' + str(self.num_bands) + '\n')
f.write('band_centres_data= ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
f.write('partition= ' + self.partition + '\n')
f.write('vn= ' + str(self.vn) + '\n')
f.write('hn= ' + str(self.hn) + '\n')
f.write('rdif= ' + str(self.sky_r_dif) + '\n')
f.write('theta_points= ')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('type= ' + self.sky_type + '\n')
f.write('azimuth= ' + str(self.sky_azimuth) + '\n')
f.write('zenith= ' + str(self.sky_zenith) + '\n')
f.write('sky_save_fp= ' + inp_file.strip('_params.txt') + '\n')
f.write('sky_image_save_fp= ' + self.sky_file + '.ppm' + '\n')
f.write('sky_image_size= 256' + '\n')
if self.sky_type == 'hlideal':
f.write('C= ' + str(self.sky_c) + '\n')
f.write('rdif= ' + str(self.sky_r_dif) + '\n')
f.flush()
f.close()
|
def write_sky_params_to_file(self):
"""Writes the params to file that skytool_Free needs to generate the sky radiance distribution."""
inp_file = self.sky_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
f = open(inp_file, 'w')
f.write('verbose= ' + str(self.verbose) + '\n')
f.write('band_count= ' + str(self.num_bands) + '\n')
f.write('band_centres_data= ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
f.write('partition= ' + self.partition + '\n')
f.write('vn= ' + str(self.vn) + '\n')
f.write('hn= ' + str(self.hn) + '\n')
f.write('rdif= ' + str(self.sky_r_dif) + '\n')
f.write('theta_points= ')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('type= ' + self.sky_type + '\n')
f.write('azimuth= ' + str(self.sky_azimuth) + '\n')
f.write('zenith= ' + str(self.sky_zenith) + '\n')
f.write('sky_save_fp= ' + inp_file.strip('_params.txt') + '\n')
f.write('sky_image_save_fp= ' + self.sky_file + '.ppm' + '\n')
f.write('sky_image_size= 256' + '\n')
if self.sky_type == 'hlideal':
f.write('C= ' + str(self.sky_c) + '\n')
f.write('rdif= ' + str(self.sky_r_dif) + '\n')
f.flush()
f.close()
|
[
"Writes",
"the",
"params",
"to",
"file",
"that",
"skytool_Free",
"needs",
"to",
"generate",
"the",
"sky",
"radiance",
"distribution",
"."
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L234-L262
|
[
"def",
"write_sky_params_to_file",
"(",
"self",
")",
":",
"inp_file",
"=",
"self",
".",
"sky_file",
"+",
"'_params.txt'",
"lg",
".",
"info",
"(",
"'Writing Inputs to file : '",
"+",
"inp_file",
")",
"f",
"=",
"open",
"(",
"inp_file",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"'verbose= '",
"+",
"str",
"(",
"self",
".",
"verbose",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_count= '",
"+",
"str",
"(",
"self",
".",
"num_bands",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_centres_data= '",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"wave",
")",
"for",
"wave",
"in",
"self",
".",
"wavelengths",
"]",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'partition= '",
"+",
"self",
".",
"partition",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'vn= '",
"+",
"str",
"(",
"self",
".",
"vn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'hn= '",
"+",
"str",
"(",
"self",
".",
"hn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'rdif= '",
"+",
"str",
"(",
"self",
".",
"sky_r_dif",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'theta_points= '",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"theta",
")",
"for",
"theta",
"in",
"self",
".",
"theta_points",
"]",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'type= '",
"+",
"self",
".",
"sky_type",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'azimuth= '",
"+",
"str",
"(",
"self",
".",
"sky_azimuth",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'zenith= '",
"+",
"str",
"(",
"self",
".",
"sky_zenith",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_save_fp= '",
"+",
"inp_file",
".",
"strip",
"(",
"'_params.txt'",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_image_save_fp= '",
"+",
"self",
".",
"sky_file",
"+",
"'.ppm'",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'sky_image_size= 256'",
"+",
"'\\n'",
")",
"if",
"self",
".",
"sky_type",
"==",
"'hlideal'",
":",
"f",
".",
"write",
"(",
"'C= '",
"+",
"str",
"(",
"self",
".",
"sky_c",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'rdif= '",
"+",
"str",
"(",
"self",
".",
"sky_r_dif",
")",
"+",
"'\\n'",
")",
"f",
".",
"flush",
"(",
")",
"f",
".",
"close",
"(",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
RunParameters.write_surf_params_to_file
|
Write the params to file that surftool_Free needs to generate the surface facets
|
libplanarradpy/planrad.py
|
def write_surf_params_to_file(self):
"""Write the params to file that surftool_Free needs to generate the surface facets"""
inp_file = self.water_surface_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
if self.surf_state == 'flat': # this is the only one that currently works.
lg.info('Surface Type is :: flat')
f = open(inp_file, 'w')
f.write('verbose= ' + str(self.verbose) + '\n')
f.write('band_count= ' + str(self.num_bands) + '\n')
f.write('band_centres_data= ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
f.write('partition= ' + self.partition + '\n')
f.write('vn= ' + str(self.vn) + '\n')
f.write('hn= ' + str(self.hn) + '\n')
f.write('theta_points= ')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('type= ' + self.iface_type + '\n')
f.write('refrac_index_0= ' + str(self.iface_0_ri) + '\n')
f.write('refrac_index_1= ' + str(self.iface_1_ri) + '\n')
f.write('wind_speed= ' + str(self.wind_speed) + '\n')
f.write('wind_direc= ' + str(self.wind_direc) + '\n')
f.write('crosswind_vertices= ' + str(self.crosswind_vertices) + '\n')
f.write('upwind_vertices= ' + str(self.upwind_vertices) + '\n')
f.write('surface_size= ' + str(self.surface_size) + '\n')
f.write('surface_radius=' + str(self.surface_radius) + '\n')
f.write('target_size= ' + str(self.target_size) + '\n')
f.write('rays_per_quad= ' + str(self.rays_per_quad) + '\n')
f.write('surface_count= ' + str(self.surface_count) + '\n')
f.write('azimuthally_average= ' + str(self.azimuthally_average) + '\n')
f.write('surface_save_fp= ' + inp_file.strip('_params.txt') + '\n')
f.flush()
f.close()
|
def write_surf_params_to_file(self):
"""Write the params to file that surftool_Free needs to generate the surface facets"""
inp_file = self.water_surface_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
if self.surf_state == 'flat': # this is the only one that currently works.
lg.info('Surface Type is :: flat')
f = open(inp_file, 'w')
f.write('verbose= ' + str(self.verbose) + '\n')
f.write('band_count= ' + str(self.num_bands) + '\n')
f.write('band_centres_data= ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
f.write('partition= ' + self.partition + '\n')
f.write('vn= ' + str(self.vn) + '\n')
f.write('hn= ' + str(self.hn) + '\n')
f.write('theta_points= ')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('type= ' + self.iface_type + '\n')
f.write('refrac_index_0= ' + str(self.iface_0_ri) + '\n')
f.write('refrac_index_1= ' + str(self.iface_1_ri) + '\n')
f.write('wind_speed= ' + str(self.wind_speed) + '\n')
f.write('wind_direc= ' + str(self.wind_direc) + '\n')
f.write('crosswind_vertices= ' + str(self.crosswind_vertices) + '\n')
f.write('upwind_vertices= ' + str(self.upwind_vertices) + '\n')
f.write('surface_size= ' + str(self.surface_size) + '\n')
f.write('surface_radius=' + str(self.surface_radius) + '\n')
f.write('target_size= ' + str(self.target_size) + '\n')
f.write('rays_per_quad= ' + str(self.rays_per_quad) + '\n')
f.write('surface_count= ' + str(self.surface_count) + '\n')
f.write('azimuthally_average= ' + str(self.azimuthally_average) + '\n')
f.write('surface_save_fp= ' + inp_file.strip('_params.txt') + '\n')
f.flush()
f.close()
|
[
"Write",
"the",
"params",
"to",
"file",
"that",
"surftool_Free",
"needs",
"to",
"generate",
"the",
"surface",
"facets"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L264-L298
|
[
"def",
"write_surf_params_to_file",
"(",
"self",
")",
":",
"inp_file",
"=",
"self",
".",
"water_surface_file",
"+",
"'_params.txt'",
"lg",
".",
"info",
"(",
"'Writing Inputs to file : '",
"+",
"inp_file",
")",
"if",
"self",
".",
"surf_state",
"==",
"'flat'",
":",
"# this is the only one that currently works.",
"lg",
".",
"info",
"(",
"'Surface Type is :: flat'",
")",
"f",
"=",
"open",
"(",
"inp_file",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"'verbose= '",
"+",
"str",
"(",
"self",
".",
"verbose",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_count= '",
"+",
"str",
"(",
"self",
".",
"num_bands",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_centres_data= '",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"wave",
")",
"for",
"wave",
"in",
"self",
".",
"wavelengths",
"]",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'partition= '",
"+",
"self",
".",
"partition",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'vn= '",
"+",
"str",
"(",
"self",
".",
"vn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'hn= '",
"+",
"str",
"(",
"self",
".",
"hn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'theta_points= '",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"theta",
")",
"for",
"theta",
"in",
"self",
".",
"theta_points",
"]",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'type= '",
"+",
"self",
".",
"iface_type",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'refrac_index_0= '",
"+",
"str",
"(",
"self",
".",
"iface_0_ri",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'refrac_index_1= '",
"+",
"str",
"(",
"self",
".",
"iface_1_ri",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'wind_speed= '",
"+",
"str",
"(",
"self",
".",
"wind_speed",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'wind_direc= '",
"+",
"str",
"(",
"self",
".",
"wind_direc",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'crosswind_vertices= '",
"+",
"str",
"(",
"self",
".",
"crosswind_vertices",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'upwind_vertices= '",
"+",
"str",
"(",
"self",
".",
"upwind_vertices",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'surface_size= '",
"+",
"str",
"(",
"self",
".",
"surface_size",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'surface_radius='",
"+",
"str",
"(",
"self",
".",
"surface_radius",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'target_size= '",
"+",
"str",
"(",
"self",
".",
"target_size",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'rays_per_quad= '",
"+",
"str",
"(",
"self",
".",
"rays_per_quad",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'surface_count= '",
"+",
"str",
"(",
"self",
".",
"surface_count",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'azimuthally_average= '",
"+",
"str",
"(",
"self",
".",
"azimuthally_average",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'surface_save_fp= '",
"+",
"inp_file",
".",
"strip",
"(",
"'_params.txt'",
")",
"+",
"'\\n'",
")",
"f",
".",
"flush",
"(",
")",
"f",
".",
"close",
"(",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
RunParameters.write_phase_params_to_file
|
Write the params to file that surftool_Free needs to generate the surface facets
|
libplanarradpy/planrad.py
|
def write_phase_params_to_file(self):
"""Write the params to file that surftool_Free needs to generate the surface facets"""
inp_file = os.path.join(os.path.join(self.input_path, 'phase_files'), self.phase_function_file) + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
if self.iop_type == 'isotropic' or 'isotropic_integ' or 'petzold' or 'pure_water ':
lg.info('Iop type is :: ' + self.iop_type)
f = open(inp_file, 'w')
f.write('verbose = ' + str(self.verbose) + '\n')
f.write('band_count = ' + str(self.num_bands) + '\n')
f.write('band_centres_data = ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
f.write('partition = ' + self.partition + '\n')
f.write('vn = ' + str(self.vn) + '\n')
f.write('hn = ' + str(self.hn) + '\n')
f.write('theta_points = ')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('type = ' + self.iop_type + '\n')
f.write('phase_func_save_fp = ' + inp_file.strip('_params.txt') + '\n')
f.flush()
f.close()
|
def write_phase_params_to_file(self):
"""Write the params to file that surftool_Free needs to generate the surface facets"""
inp_file = os.path.join(os.path.join(self.input_path, 'phase_files'), self.phase_function_file) + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
if self.iop_type == 'isotropic' or 'isotropic_integ' or 'petzold' or 'pure_water ':
lg.info('Iop type is :: ' + self.iop_type)
f = open(inp_file, 'w')
f.write('verbose = ' + str(self.verbose) + '\n')
f.write('band_count = ' + str(self.num_bands) + '\n')
f.write('band_centres_data = ')
f.write(",".join([str(wave) for wave in self.wavelengths]) + '\n')
f.write('partition = ' + self.partition + '\n')
f.write('vn = ' + str(self.vn) + '\n')
f.write('hn = ' + str(self.hn) + '\n')
f.write('theta_points = ')
f.write(",".join([str(theta) for theta in self.theta_points]) + '\n')
f.write('type = ' + self.iop_type + '\n')
f.write('phase_func_save_fp = ' + inp_file.strip('_params.txt') + '\n')
f.flush()
f.close()
|
[
"Write",
"the",
"params",
"to",
"file",
"that",
"surftool_Free",
"needs",
"to",
"generate",
"the",
"surface",
"facets"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L300-L322
|
[
"def",
"write_phase_params_to_file",
"(",
"self",
")",
":",
"inp_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"input_path",
",",
"'phase_files'",
")",
",",
"self",
".",
"phase_function_file",
")",
"+",
"'_params.txt'",
"lg",
".",
"info",
"(",
"'Writing Inputs to file : '",
"+",
"inp_file",
")",
"if",
"self",
".",
"iop_type",
"==",
"'isotropic'",
"or",
"'isotropic_integ'",
"or",
"'petzold'",
"or",
"'pure_water '",
":",
"lg",
".",
"info",
"(",
"'Iop type is :: '",
"+",
"self",
".",
"iop_type",
")",
"f",
"=",
"open",
"(",
"inp_file",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"'verbose = '",
"+",
"str",
"(",
"self",
".",
"verbose",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_count = '",
"+",
"str",
"(",
"self",
".",
"num_bands",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'band_centres_data = '",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"wave",
")",
"for",
"wave",
"in",
"self",
".",
"wavelengths",
"]",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'partition = '",
"+",
"self",
".",
"partition",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'vn = '",
"+",
"str",
"(",
"self",
".",
"vn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'hn = '",
"+",
"str",
"(",
"self",
".",
"hn",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'theta_points = '",
")",
"f",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"theta",
")",
"for",
"theta",
"in",
"self",
".",
"theta_points",
"]",
")",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'type = '",
"+",
"self",
".",
"iop_type",
"+",
"'\\n'",
")",
"f",
".",
"write",
"(",
"'phase_func_save_fp = '",
"+",
"inp_file",
".",
"strip",
"(",
"'_params.txt'",
")",
"+",
"'\\n'",
")",
"f",
".",
"flush",
"(",
")",
"f",
".",
"close",
"(",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
RunParameters.update_filenames
|
Does nothing currently. May not need this method
|
libplanarradpy/planrad.py
|
def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'),
'sky_' + self.sky_state + '_z' + str(
self.sky_zenith) + '_a' + str(
self.sky_azimuth) + '_' + str(
self.num_bands) + '_' + self.ds_code))
|
def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'),
'sky_' + self.sky_state + '_z' + str(
self.sky_zenith) + '_a' + str(
self.sky_azimuth) + '_' + str(
self.num_bands) + '_' + self.ds_code))
|
[
"Does",
"nothing",
"currently",
".",
"May",
"not",
"need",
"this",
"method"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L324-L330
|
[
"def",
"update_filenames",
"(",
"self",
")",
":",
"self",
".",
"sky_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"input_path",
",",
"'sky_files'",
")",
",",
"'sky_'",
"+",
"self",
".",
"sky_state",
"+",
"'_z'",
"+",
"str",
"(",
"self",
".",
"sky_zenith",
")",
"+",
"'_a'",
"+",
"str",
"(",
"self",
".",
"sky_azimuth",
")",
"+",
"'_'",
"+",
"str",
"(",
"self",
".",
"num_bands",
")",
"+",
"'_'",
"+",
"self",
".",
"ds_code",
")",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.build_bbp
|
Builds the particle backscattering function :math:`X(\\frac{550}{\\lambda})^Y`
:param x: function coefficient
:param y: order of the power function
:param wave_const: wave constant default 550 (nm)
:returns null:
|
libplanarradpy/planrad.py
|
def build_bbp(self, x, y, wave_const=550):
"""
Builds the particle backscattering function :math:`X(\\frac{550}{\\lambda})^Y`
:param x: function coefficient
:param y: order of the power function
:param wave_const: wave constant default 550 (nm)
:returns null:
"""
lg.info('Building b_bp spectra')
self.b_bp = x * (wave_const / self.wavelengths) ** y
|
def build_bbp(self, x, y, wave_const=550):
"""
Builds the particle backscattering function :math:`X(\\frac{550}{\\lambda})^Y`
:param x: function coefficient
:param y: order of the power function
:param wave_const: wave constant default 550 (nm)
:returns null:
"""
lg.info('Building b_bp spectra')
self.b_bp = x * (wave_const / self.wavelengths) ** y
|
[
"Builds",
"the",
"particle",
"backscattering",
"function",
":",
"math",
":",
"X",
"(",
"\\\\",
"frac",
"{",
"550",
"}",
"{",
"\\\\",
"lambda",
"}",
")",
"^Y"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L357-L367
|
[
"def",
"build_bbp",
"(",
"self",
",",
"x",
",",
"y",
",",
"wave_const",
"=",
"550",
")",
":",
"lg",
".",
"info",
"(",
"'Building b_bp spectra'",
")",
"self",
".",
"b_bp",
"=",
"x",
"*",
"(",
"wave_const",
"/",
"self",
".",
"wavelengths",
")",
"**",
"y"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.build_a_cdom
|
Builds the CDOM absorption function :: :math:`G \exp (-S(\lambda - 400))`
:param g: function coefficient
:param s: slope factor
:param wave_const: wave constant default = 400 (nm)
:returns null:
|
libplanarradpy/planrad.py
|
def build_a_cdom(self, g, s, wave_const=400):
"""
Builds the CDOM absorption function :: :math:`G \exp (-S(\lambda - 400))`
:param g: function coefficient
:param s: slope factor
:param wave_const: wave constant default = 400 (nm)
:returns null:
"""
lg.info('building CDOM absorption')
self.a_cdom = g * scipy.exp(-s * (self.wavelengths - wave_const))
|
def build_a_cdom(self, g, s, wave_const=400):
"""
Builds the CDOM absorption function :: :math:`G \exp (-S(\lambda - 400))`
:param g: function coefficient
:param s: slope factor
:param wave_const: wave constant default = 400 (nm)
:returns null:
"""
lg.info('building CDOM absorption')
self.a_cdom = g * scipy.exp(-s * (self.wavelengths - wave_const))
|
[
"Builds",
"the",
"CDOM",
"absorption",
"function",
"::",
":",
"math",
":",
"G",
"\\",
"exp",
"(",
"-",
"S",
"(",
"\\",
"lambda",
"-",
"400",
"))"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L369-L379
|
[
"def",
"build_a_cdom",
"(",
"self",
",",
"g",
",",
"s",
",",
"wave_const",
"=",
"400",
")",
":",
"lg",
".",
"info",
"(",
"'building CDOM absorption'",
")",
"self",
".",
"a_cdom",
"=",
"g",
"*",
"scipy",
".",
"exp",
"(",
"-",
"s",
"*",
"(",
"self",
".",
"wavelengths",
"-",
"wave_const",
")",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.read_aphi_from_file
|
Read the phytoplankton absorption file from a csv formatted file
:param file_name: filename and path of the csv file
|
libplanarradpy/planrad.py
|
def read_aphi_from_file(self, file_name):
"""Read the phytoplankton absorption file from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading ahpi absorption')
try:
self.a_phi = self._read_iop_from_file(file_name)
except:
lg.exception('Problem reading file :: ' + file_name)
self.a_phi = -1
|
def read_aphi_from_file(self, file_name):
"""Read the phytoplankton absorption file from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading ahpi absorption')
try:
self.a_phi = self._read_iop_from_file(file_name)
except:
lg.exception('Problem reading file :: ' + file_name)
self.a_phi = -1
|
[
"Read",
"the",
"phytoplankton",
"absorption",
"file",
"from",
"a",
"csv",
"formatted",
"file"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L381-L391
|
[
"def",
"read_aphi_from_file",
"(",
"self",
",",
"file_name",
")",
":",
"lg",
".",
"info",
"(",
"'Reading ahpi absorption'",
")",
"try",
":",
"self",
".",
"a_phi",
"=",
"self",
".",
"_read_iop_from_file",
"(",
"file_name",
")",
"except",
":",
"lg",
".",
"exception",
"(",
"'Problem reading file :: '",
"+",
"file_name",
")",
"self",
".",
"a_phi",
"=",
"-",
"1"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.scale_aphi
|
Scale the spectra by multiplying by linear scaling factor
:param scale_parameter: Linear scaling factor
|
libplanarradpy/planrad.py
|
def scale_aphi(self, scale_parameter):
"""Scale the spectra by multiplying by linear scaling factor
:param scale_parameter: Linear scaling factor
"""
lg.info('Scaling a_phi by :: ' + str(scale_parameter))
try:
self.a_phi = self.a_phi * scale_parameter
except:
lg.exception("Can't scale a_phi, check that it has been defined ")
|
def scale_aphi(self, scale_parameter):
"""Scale the spectra by multiplying by linear scaling factor
:param scale_parameter: Linear scaling factor
"""
lg.info('Scaling a_phi by :: ' + str(scale_parameter))
try:
self.a_phi = self.a_phi * scale_parameter
except:
lg.exception("Can't scale a_phi, check that it has been defined ")
|
[
"Scale",
"the",
"spectra",
"by",
"multiplying",
"by",
"linear",
"scaling",
"factor"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L393-L402
|
[
"def",
"scale_aphi",
"(",
"self",
",",
"scale_parameter",
")",
":",
"lg",
".",
"info",
"(",
"'Scaling a_phi by :: '",
"+",
"str",
"(",
"scale_parameter",
")",
")",
"try",
":",
"self",
".",
"a_phi",
"=",
"self",
".",
"a_phi",
"*",
"scale_parameter",
"except",
":",
"lg",
".",
"exception",
"(",
"\"Can't scale a_phi, check that it has been defined \"",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.read_pure_water_absorption_from_file
|
Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file
|
libplanarradpy/planrad.py
|
def read_pure_water_absorption_from_file(self, file_name):
"""Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water absorption from file')
try:
self.a_water = self._read_iop_from_file(file_name)
except:
lg.exception('Problem reading file :: ' + file_name)
|
def read_pure_water_absorption_from_file(self, file_name):
"""Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water absorption from file')
try:
self.a_water = self._read_iop_from_file(file_name)
except:
lg.exception('Problem reading file :: ' + file_name)
|
[
"Read",
"the",
"pure",
"water",
"absorption",
"from",
"a",
"csv",
"formatted",
"file"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L404-L413
|
[
"def",
"read_pure_water_absorption_from_file",
"(",
"self",
",",
"file_name",
")",
":",
"lg",
".",
"info",
"(",
"'Reading water absorption from file'",
")",
"try",
":",
"self",
".",
"a_water",
"=",
"self",
".",
"_read_iop_from_file",
"(",
"file_name",
")",
"except",
":",
"lg",
".",
"exception",
"(",
"'Problem reading file :: '",
"+",
"file_name",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.read_pure_water_scattering_from_file
|
Read the pure water scattering from a csv formatted file
:param file_name: filename and path of the csv file
|
libplanarradpy/planrad.py
|
def read_pure_water_scattering_from_file(self, file_name):
"""Read the pure water scattering from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water scattering from file')
try:
self.b_water = self._read_iop_from_file(file_name)
except:
lg.exception('Problem reading file :: ' + file_name)
|
def read_pure_water_scattering_from_file(self, file_name):
"""Read the pure water scattering from a csv formatted file
:param file_name: filename and path of the csv file
"""
lg.info('Reading water scattering from file')
try:
self.b_water = self._read_iop_from_file(file_name)
except:
lg.exception('Problem reading file :: ' + file_name)
|
[
"Read",
"the",
"pure",
"water",
"scattering",
"from",
"a",
"csv",
"formatted",
"file"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L416-L425
|
[
"def",
"read_pure_water_scattering_from_file",
"(",
"self",
",",
"file_name",
")",
":",
"lg",
".",
"info",
"(",
"'Reading water scattering from file'",
")",
"try",
":",
"self",
".",
"b_water",
"=",
"self",
".",
"_read_iop_from_file",
"(",
"file_name",
")",
"except",
":",
"lg",
".",
"exception",
"(",
"'Problem reading file :: '",
"+",
"file_name",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters._read_iop_from_file
|
Generic IOP reader that interpolates the iop to the common wavelengths defined in the constructor
:param file_name: filename and path of the csv file
:returns interpolated iop
|
libplanarradpy/planrad.py
|
def _read_iop_from_file(self, file_name):
"""
Generic IOP reader that interpolates the iop to the common wavelengths defined in the constructor
:param file_name: filename and path of the csv file
:returns interpolated iop
"""
lg.info('Reading :: ' + file_name + ' :: and interpolating to ' + str(self.wavelengths))
if os.path.isfile(file_name):
iop_reader = csv.reader(open(file_name), delimiter=',', quotechar='"')
wave = iop_reader.next()
iop = iop_reader.next()
else:
lg.exception('Problem reading file :: ' + file_name)
raise IOError
try:
wave = map(float, wave)
iop = map(float, iop)
return scipy.interp(self.wavelengths, wave, iop)
except IOError:
lg.exception('Error interpolating IOP to common wavelength')
return -1
|
def _read_iop_from_file(self, file_name):
"""
Generic IOP reader that interpolates the iop to the common wavelengths defined in the constructor
:param file_name: filename and path of the csv file
:returns interpolated iop
"""
lg.info('Reading :: ' + file_name + ' :: and interpolating to ' + str(self.wavelengths))
if os.path.isfile(file_name):
iop_reader = csv.reader(open(file_name), delimiter=',', quotechar='"')
wave = iop_reader.next()
iop = iop_reader.next()
else:
lg.exception('Problem reading file :: ' + file_name)
raise IOError
try:
wave = map(float, wave)
iop = map(float, iop)
return scipy.interp(self.wavelengths, wave, iop)
except IOError:
lg.exception('Error interpolating IOP to common wavelength')
return -1
|
[
"Generic",
"IOP",
"reader",
"that",
"interpolates",
"the",
"iop",
"to",
"the",
"common",
"wavelengths",
"defined",
"in",
"the",
"constructor"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L428-L451
|
[
"def",
"_read_iop_from_file",
"(",
"self",
",",
"file_name",
")",
":",
"lg",
".",
"info",
"(",
"'Reading :: '",
"+",
"file_name",
"+",
"' :: and interpolating to '",
"+",
"str",
"(",
"self",
".",
"wavelengths",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_name",
")",
":",
"iop_reader",
"=",
"csv",
".",
"reader",
"(",
"open",
"(",
"file_name",
")",
",",
"delimiter",
"=",
"','",
",",
"quotechar",
"=",
"'\"'",
")",
"wave",
"=",
"iop_reader",
".",
"next",
"(",
")",
"iop",
"=",
"iop_reader",
".",
"next",
"(",
")",
"else",
":",
"lg",
".",
"exception",
"(",
"'Problem reading file :: '",
"+",
"file_name",
")",
"raise",
"IOError",
"try",
":",
"wave",
"=",
"map",
"(",
"float",
",",
"wave",
")",
"iop",
"=",
"map",
"(",
"float",
",",
"iop",
")",
"return",
"scipy",
".",
"interp",
"(",
"self",
".",
"wavelengths",
",",
"wave",
",",
"iop",
")",
"except",
"IOError",
":",
"lg",
".",
"exception",
"(",
"'Error interpolating IOP to common wavelength'",
")",
"return",
"-",
"1"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters._write_iop_to_file
|
Generic iop file writer
:param iop numpy array to write to file
:param file_name the file and path to write the IOP to
|
libplanarradpy/planrad.py
|
def _write_iop_to_file(self, iop, file_name):
"""Generic iop file writer
:param iop numpy array to write to file
:param file_name the file and path to write the IOP to
"""
lg.info('Writing :: ' + file_name)
f = open(file_name, 'w')
for i in scipy.nditer(iop):
f.write(str(i) + '\n')
|
def _write_iop_to_file(self, iop, file_name):
"""Generic iop file writer
:param iop numpy array to write to file
:param file_name the file and path to write the IOP to
"""
lg.info('Writing :: ' + file_name)
f = open(file_name, 'w')
for i in scipy.nditer(iop):
f.write(str(i) + '\n')
|
[
"Generic",
"iop",
"file",
"writer"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L467-L476
|
[
"def",
"_write_iop_to_file",
"(",
"self",
",",
"iop",
",",
"file_name",
")",
":",
"lg",
".",
"info",
"(",
"'Writing :: '",
"+",
"file_name",
")",
"f",
"=",
"open",
"(",
"file_name",
",",
"'w'",
")",
"for",
"i",
"in",
"scipy",
".",
"nditer",
"(",
"iop",
")",
":",
"f",
".",
"write",
"(",
"str",
"(",
"i",
")",
"+",
"'\\n'",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.build_b
|
Calculates the total scattering from back-scattering
:param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833
b = ( bb[sea water] + bb[p] ) /0.01833
|
libplanarradpy/planrad.py
|
def build_b(self, scattering_fraction=0.01833):
"""Calculates the total scattering from back-scattering
:param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833
b = ( bb[sea water] + bb[p] ) /0.01833
"""
lg.info('Building b with scattering fraction of :: ' + str(scattering_fraction))
self.b = (self.b_b + self.b_water / 2.0) / scattering_fraction
|
def build_b(self, scattering_fraction=0.01833):
"""Calculates the total scattering from back-scattering
:param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833
b = ( bb[sea water] + bb[p] ) /0.01833
"""
lg.info('Building b with scattering fraction of :: ' + str(scattering_fraction))
self.b = (self.b_b + self.b_water / 2.0) / scattering_fraction
|
[
"Calculates",
"the",
"total",
"scattering",
"from",
"back",
"-",
"scattering"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L486-L494
|
[
"def",
"build_b",
"(",
"self",
",",
"scattering_fraction",
"=",
"0.01833",
")",
":",
"lg",
".",
"info",
"(",
"'Building b with scattering fraction of :: '",
"+",
"str",
"(",
"scattering_fraction",
")",
")",
"self",
".",
"b",
"=",
"(",
"self",
".",
"b_b",
"+",
"self",
".",
"b_water",
"/",
"2.0",
")",
"/",
"scattering_fraction"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.build_a
|
Calculates the total absorption from water, phytoplankton and CDOM
a = awater + acdom + aphi
|
libplanarradpy/planrad.py
|
def build_a(self):
"""Calculates the total absorption from water, phytoplankton and CDOM
a = awater + acdom + aphi
"""
lg.info('Building total absorption')
self.a = self.a_water + self.a_cdom + self.a_phi
|
def build_a(self):
"""Calculates the total absorption from water, phytoplankton and CDOM
a = awater + acdom + aphi
"""
lg.info('Building total absorption')
self.a = self.a_water + self.a_cdom + self.a_phi
|
[
"Calculates",
"the",
"total",
"absorption",
"from",
"water",
"phytoplankton",
"and",
"CDOM"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L496-L502
|
[
"def",
"build_a",
"(",
"self",
")",
":",
"lg",
".",
"info",
"(",
"'Building total absorption'",
")",
"self",
".",
"a",
"=",
"self",
".",
"a_water",
"+",
"self",
".",
"a_cdom",
"+",
"self",
".",
"a_phi"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.build_c
|
Calculates the total attenuation from the total absorption and total scattering
c = a + b
|
libplanarradpy/planrad.py
|
def build_c(self):
"""Calculates the total attenuation from the total absorption and total scattering
c = a + b
"""
lg.info('Building total attenuation C')
self.c = self.a + self.b
|
def build_c(self):
"""Calculates the total attenuation from the total absorption and total scattering
c = a + b
"""
lg.info('Building total attenuation C')
self.c = self.a + self.b
|
[
"Calculates",
"the",
"total",
"attenuation",
"from",
"the",
"total",
"absorption",
"and",
"total",
"scattering"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L504-L510
|
[
"def",
"build_c",
"(",
"self",
")",
":",
"lg",
".",
"info",
"(",
"'Building total attenuation C'",
")",
"self",
".",
"c",
"=",
"self",
".",
"a",
"+",
"self",
".",
"b"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BioOpticalParameters.build_all_iop
|
Meta method that calls all of the build methods in the correct order
self.build_a()
self.build_bb()
self.build_b()
self.build_c()
|
libplanarradpy/planrad.py
|
def build_all_iop(self):
"""Meta method that calls all of the build methods in the correct order
self.build_a()
self.build_bb()
self.build_b()
self.build_c()
"""
lg.info('Building all b and c from IOPs')
self.build_a()
self.build_bb()
self.build_b()
self.build_c()
|
def build_all_iop(self):
"""Meta method that calls all of the build methods in the correct order
self.build_a()
self.build_bb()
self.build_b()
self.build_c()
"""
lg.info('Building all b and c from IOPs')
self.build_a()
self.build_bb()
self.build_b()
self.build_c()
|
[
"Meta",
"method",
"that",
"calls",
"all",
"of",
"the",
"build",
"methods",
"in",
"the",
"correct",
"order"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L512-L525
|
[
"def",
"build_all_iop",
"(",
"self",
")",
":",
"lg",
".",
"info",
"(",
"'Building all b and c from IOPs'",
")",
"self",
".",
"build_a",
"(",
")",
"self",
".",
"build_bb",
"(",
")",
"self",
".",
"build_b",
"(",
")",
"self",
".",
"build_c",
"(",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
test
|
BatchRun.run
|
Distributes the work across the CPUs. It actually uses _run()
|
libplanarradpy/planrad.py
|
def run(self):
"""Distributes the work across the CPUs. It actually uses _run()"""
done = False
dir_list = []
tic = time.clock()
lg.info('Starting batch run at :: ' + str(tic))
if self.run_params.num_cpus == -1: # user hasn't set a throttle
self.run_params.num_cpus = os.sysconf("SC_NPROCESSORS_ONLN")
lg.info('Found ' + str(self.run_params.num_cpus) + ' CPUs')
# --------------------------------------------------#
# COUNT THE NUMBER OF DIRECTORIES TO ITERATE THROUGH
# --------------------------------------------------#
tmp_dir_list = os.listdir(self.batch_output)
for direc in tmp_dir_list:
dir_list.append(os.path.join(self.batch_output, direc))
num_dirs = len(dir_list)
lg.info('Found ' + str(num_dirs) + ' directories to process in ' + self.batch_output)
sub = scipy.floor(num_dirs / self.run_params.num_cpus)
remainder = num_dirs - (sub * self.run_params.num_cpus)
if remainder > 0:
lg.warning('Number of variations not evenly divisible by number of CPUs')
lg.warning('This is not a problem, last block will not use all available CPUs')
lg.warning('The remainder is :: ' + str(remainder))
while not done:
for l in range(0, int(sub)):
lg.info('Starting processing block of :: ' + str(self.run_params.num_cpus) + ' processes')
for m in range(0, self.run_params.num_cpus):
#row = (m * sub) + l
_dir = dir_list.pop()
#--------------------------------------------------#
# CHECK TO SEE IF REPORT HAS BEEN GENERATED AND DON'T
# BOTHER RUNNING AGAIN IF THEY DO EXIST
#--------------------------------------------------#
report_dir, report_file_name = os.path.split(self.run_params.report_file)
lg.debug(report_file_name)
lg.debug(os.path.join(_dir, report_file_name))
try:
rep_size = os.path.getsize(os.path.join(_dir, report_file_name.strip('\n')))
lg.debug('report size is :: ' + str(rep_size))
except:
rep_size = 0
if rep_size < 1.0: # TODO this is a spoof!
lg.info('No report file found, running process')
p = Process(target=self._run, args=(_dir,))
else:
lg.warning('Report file found :: ' + os.path.join(_dir, report_file_name.strip(
'\n')) + ' not redoing run ')
p = Process(target=self._dummy, args=(_dir,))
# !! for testing
#p = Process(target=self._dummy, args=(_dir,))
p.start()
lg.info('Starting Process :: Process ID :: ' + str(p.pid))
p.join()
self.run_params.num_cpus = remainder
remainder = 0
lg.info('Processing remainder')
sub = 1
if remainder == 0:
done = True
toc = time.clock() # this isn't working
lg.info('Ending batch run at :: ' + str(toc))
timeTaken = toc - tic
lg.info('Time taken ::' + str(timeTaken))
|
def run(self):
"""Distributes the work across the CPUs. It actually uses _run()"""
done = False
dir_list = []
tic = time.clock()
lg.info('Starting batch run at :: ' + str(tic))
if self.run_params.num_cpus == -1: # user hasn't set a throttle
self.run_params.num_cpus = os.sysconf("SC_NPROCESSORS_ONLN")
lg.info('Found ' + str(self.run_params.num_cpus) + ' CPUs')
# --------------------------------------------------#
# COUNT THE NUMBER OF DIRECTORIES TO ITERATE THROUGH
# --------------------------------------------------#
tmp_dir_list = os.listdir(self.batch_output)
for direc in tmp_dir_list:
dir_list.append(os.path.join(self.batch_output, direc))
num_dirs = len(dir_list)
lg.info('Found ' + str(num_dirs) + ' directories to process in ' + self.batch_output)
sub = scipy.floor(num_dirs / self.run_params.num_cpus)
remainder = num_dirs - (sub * self.run_params.num_cpus)
if remainder > 0:
lg.warning('Number of variations not evenly divisible by number of CPUs')
lg.warning('This is not a problem, last block will not use all available CPUs')
lg.warning('The remainder is :: ' + str(remainder))
while not done:
for l in range(0, int(sub)):
lg.info('Starting processing block of :: ' + str(self.run_params.num_cpus) + ' processes')
for m in range(0, self.run_params.num_cpus):
#row = (m * sub) + l
_dir = dir_list.pop()
#--------------------------------------------------#
# CHECK TO SEE IF REPORT HAS BEEN GENERATED AND DON'T
# BOTHER RUNNING AGAIN IF THEY DO EXIST
#--------------------------------------------------#
report_dir, report_file_name = os.path.split(self.run_params.report_file)
lg.debug(report_file_name)
lg.debug(os.path.join(_dir, report_file_name))
try:
rep_size = os.path.getsize(os.path.join(_dir, report_file_name.strip('\n')))
lg.debug('report size is :: ' + str(rep_size))
except:
rep_size = 0
if rep_size < 1.0: # TODO this is a spoof!
lg.info('No report file found, running process')
p = Process(target=self._run, args=(_dir,))
else:
lg.warning('Report file found :: ' + os.path.join(_dir, report_file_name.strip(
'\n')) + ' not redoing run ')
p = Process(target=self._dummy, args=(_dir,))
# !! for testing
#p = Process(target=self._dummy, args=(_dir,))
p.start()
lg.info('Starting Process :: Process ID :: ' + str(p.pid))
p.join()
self.run_params.num_cpus = remainder
remainder = 0
lg.info('Processing remainder')
sub = 1
if remainder == 0:
done = True
toc = time.clock() # this isn't working
lg.info('Ending batch run at :: ' + str(toc))
timeTaken = toc - tic
lg.info('Time taken ::' + str(timeTaken))
|
[
"Distributes",
"the",
"work",
"across",
"the",
"CPUs",
".",
"It",
"actually",
"uses",
"_run",
"()"
] |
marrabld/planarradpy
|
python
|
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L561-L637
|
[
"def",
"run",
"(",
"self",
")",
":",
"done",
"=",
"False",
"dir_list",
"=",
"[",
"]",
"tic",
"=",
"time",
".",
"clock",
"(",
")",
"lg",
".",
"info",
"(",
"'Starting batch run at :: '",
"+",
"str",
"(",
"tic",
")",
")",
"if",
"self",
".",
"run_params",
".",
"num_cpus",
"==",
"-",
"1",
":",
"# user hasn't set a throttle",
"self",
".",
"run_params",
".",
"num_cpus",
"=",
"os",
".",
"sysconf",
"(",
"\"SC_NPROCESSORS_ONLN\"",
")",
"lg",
".",
"info",
"(",
"'Found '",
"+",
"str",
"(",
"self",
".",
"run_params",
".",
"num_cpus",
")",
"+",
"' CPUs'",
")",
"# --------------------------------------------------#",
"# COUNT THE NUMBER OF DIRECTORIES TO ITERATE THROUGH",
"# --------------------------------------------------#",
"tmp_dir_list",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"batch_output",
")",
"for",
"direc",
"in",
"tmp_dir_list",
":",
"dir_list",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"batch_output",
",",
"direc",
")",
")",
"num_dirs",
"=",
"len",
"(",
"dir_list",
")",
"lg",
".",
"info",
"(",
"'Found '",
"+",
"str",
"(",
"num_dirs",
")",
"+",
"' directories to process in '",
"+",
"self",
".",
"batch_output",
")",
"sub",
"=",
"scipy",
".",
"floor",
"(",
"num_dirs",
"/",
"self",
".",
"run_params",
".",
"num_cpus",
")",
"remainder",
"=",
"num_dirs",
"-",
"(",
"sub",
"*",
"self",
".",
"run_params",
".",
"num_cpus",
")",
"if",
"remainder",
">",
"0",
":",
"lg",
".",
"warning",
"(",
"'Number of variations not evenly divisible by number of CPUs'",
")",
"lg",
".",
"warning",
"(",
"'This is not a problem, last block will not use all available CPUs'",
")",
"lg",
".",
"warning",
"(",
"'The remainder is :: '",
"+",
"str",
"(",
"remainder",
")",
")",
"while",
"not",
"done",
":",
"for",
"l",
"in",
"range",
"(",
"0",
",",
"int",
"(",
"sub",
")",
")",
":",
"lg",
".",
"info",
"(",
"'Starting processing block of :: '",
"+",
"str",
"(",
"self",
".",
"run_params",
".",
"num_cpus",
")",
"+",
"' processes'",
")",
"for",
"m",
"in",
"range",
"(",
"0",
",",
"self",
".",
"run_params",
".",
"num_cpus",
")",
":",
"#row = (m * sub) + l",
"_dir",
"=",
"dir_list",
".",
"pop",
"(",
")",
"#--------------------------------------------------#",
"# CHECK TO SEE IF REPORT HAS BEEN GENERATED AND DON'T",
"# BOTHER RUNNING AGAIN IF THEY DO EXIST",
"#--------------------------------------------------#",
"report_dir",
",",
"report_file_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"run_params",
".",
"report_file",
")",
"lg",
".",
"debug",
"(",
"report_file_name",
")",
"lg",
".",
"debug",
"(",
"os",
".",
"path",
".",
"join",
"(",
"_dir",
",",
"report_file_name",
")",
")",
"try",
":",
"rep_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"os",
".",
"path",
".",
"join",
"(",
"_dir",
",",
"report_file_name",
".",
"strip",
"(",
"'\\n'",
")",
")",
")",
"lg",
".",
"debug",
"(",
"'report size is :: '",
"+",
"str",
"(",
"rep_size",
")",
")",
"except",
":",
"rep_size",
"=",
"0",
"if",
"rep_size",
"<",
"1.0",
":",
"# TODO this is a spoof!",
"lg",
".",
"info",
"(",
"'No report file found, running process'",
")",
"p",
"=",
"Process",
"(",
"target",
"=",
"self",
".",
"_run",
",",
"args",
"=",
"(",
"_dir",
",",
")",
")",
"else",
":",
"lg",
".",
"warning",
"(",
"'Report file found :: '",
"+",
"os",
".",
"path",
".",
"join",
"(",
"_dir",
",",
"report_file_name",
".",
"strip",
"(",
"'\\n'",
")",
")",
"+",
"' not redoing run '",
")",
"p",
"=",
"Process",
"(",
"target",
"=",
"self",
".",
"_dummy",
",",
"args",
"=",
"(",
"_dir",
",",
")",
")",
"# !! for testing",
"#p = Process(target=self._dummy, args=(_dir,))",
"p",
".",
"start",
"(",
")",
"lg",
".",
"info",
"(",
"'Starting Process :: Process ID :: '",
"+",
"str",
"(",
"p",
".",
"pid",
")",
")",
"p",
".",
"join",
"(",
")",
"self",
".",
"run_params",
".",
"num_cpus",
"=",
"remainder",
"remainder",
"=",
"0",
"lg",
".",
"info",
"(",
"'Processing remainder'",
")",
"sub",
"=",
"1",
"if",
"remainder",
"==",
"0",
":",
"done",
"=",
"True",
"toc",
"=",
"time",
".",
"clock",
"(",
")",
"# this isn't working",
"lg",
".",
"info",
"(",
"'Ending batch run at :: '",
"+",
"str",
"(",
"toc",
")",
")",
"timeTaken",
"=",
"toc",
"-",
"tic",
"lg",
".",
"info",
"(",
"'Time taken ::'",
"+",
"str",
"(",
"timeTaken",
")",
")"
] |
5095d1cb98d4f67a7c3108c9282f2d59253e89a8
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.