code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import json
import pathlib
import traceback
import typing
def get_traceback_msg(err):
return ''.join(traceback.format_exception(
etype=type(err),
value=err,
tb=err.__traceback__))
def json_to_envfiles(output_file: pathlib.Path):
try:
output_name: str = output_file.stem
input_env_file_content: str = output_file.read_text()
input_env: dict[str, typing.Union[str, dict[str, str]]] = json.loads(input_env_file_content)
template_launch_json_file: typing.Optional[pathlib.Path] = pathlib.Path('template/launch.json')
if not template_launch_json_file.exists():
print('There\'s no launch.json template file for VS Code.\n'
'Place file on template/launch.json')
template_launch_json_file = None
else:
template_launch_json_file_content: dict[str, object] = json.loads(template_launch_json_file.read_text())
output_docker_file: pathlib.Path = pathlib.Path(output_name+'.env')
output_bash_file: pathlib.Path = pathlib.Path(output_name+'.sh')
output_ps_file: pathlib.Path = pathlib.Path(output_name+'.ps1')
output_launch_json_file: pathlib.Path = pathlib.Path('../.vscode/launch.json')
if output_docker_file.exists():
output_docker_file.unlink()
if output_bash_file.exists():
output_bash_file.unlink()
if output_ps_file.exists():
output_ps_file.unlink()
if template_launch_json_file is not None:
if not output_launch_json_file.parent.exists():
output_launch_json_file.parent.mkdir()
if output_launch_json_file.exists():
output_launch_json_file.unlink()
with output_docker_file.open('w') as docker_fp,\
output_bash_file.open('w') as bash_fp,\
output_ps_file.open('w') as ps_fp:
# Add Shebang
bash_fp.write('#!/usr/bin/env bash\n')
ps_fp.write('#!/usr/bin/env pwsh\n')
for env_name, env_value in input_env.items():
if env_name.startswith('__comment'):
comment_line = f'# {env_value}\n'
docker_fp.write(comment_line)
bash_fp.write(comment_line)
ps_fp.write(comment_line)
continue
elif env_name.startswith('__line_break'):
docker_fp.write('\n')
bash_fp.write('\n')
ps_fp.write('\n')
continue
docker_line = f'{env_name}='
bash_line = f'export {env_name}='
ps_line = f'$env:{env_name}='
if type(env_value) == dict:
bash_line += f'"{env_value["bash"]}"\n'
ps_line += f'"{env_value["powershell"]}"\n'
docker_line += f'"{env_value["vscode_launch"].format(**input_env)}"\n'
else:
bash_line += f'"{env_value}"\n'
ps_line += f'"{env_value}"\n'
docker_line += f'"{env_value}"\n'
docker_fp.write(docker_line)
bash_fp.write(bash_line)
ps_fp.write(ps_line)
if template_launch_json_file is not None:
with output_launch_json_file.open('w') as launch_json_fp:
launch_json_env = dict()
for k, v in input_env.items():
if k.startswith('__comment') or k.startswith('__line_break'):
continue
elif type(v) == str:
launch_json_env[k] = v
else:
launch_json_env[k] = v['vscode_launch'].format(**input_env)
template_launch_json_file_content['configurations'][0]['env'] = launch_json_env
launch_json_fp.write(json.dumps(template_launch_json_file_content, indent=4))
except Exception as e:
print('Exception raised!')
print(get_traceback_msg(e))
if __name__ == '__main__':
import os
import sys
if len(sys.argv) > 1:
target_file = pathlib.Path(sys.argv[1]).absolute()
if not target_file.exists():
print(target_file.as_posix())
# Ignore just now. We'll retry this after changing paths
target_file = None
else:
print('Need to specify target environment variables collection file(.json)')
os._exit(1)
os.chdir(pathlib.Path(__file__).parents[0])
if target_file is None:
target_file = pathlib.Path(sys.argv[1]).absolute()
if not target_file.exists():
raise FileNotFoundError()
json_to_envfiles(target_file)
| [
"json.loads",
"json.dumps",
"os._exit",
"pathlib.Path"
] | [((476, 510), 'json.loads', 'json.loads', (['input_env_file_content'], {}), '(input_env_file_content)\n', (486, 510), False, 'import json\n'), ((579, 615), 'pathlib.Path', 'pathlib.Path', (['"""template/launch.json"""'], {}), "('template/launch.json')\n", (591, 615), False, 'import pathlib\n'), ((1016, 1050), 'pathlib.Path', 'pathlib.Path', (["(output_name + '.env')"], {}), "(output_name + '.env')\n", (1028, 1050), False, 'import pathlib\n'), ((1090, 1123), 'pathlib.Path', 'pathlib.Path', (["(output_name + '.sh')"], {}), "(output_name + '.sh')\n", (1102, 1123), False, 'import pathlib\n'), ((1161, 1195), 'pathlib.Path', 'pathlib.Path', (["(output_name + '.ps1')"], {}), "(output_name + '.ps1')\n", (1173, 1195), False, 'import pathlib\n'), ((1242, 1280), 'pathlib.Path', 'pathlib.Path', (['"""../.vscode/launch.json"""'], {}), "('../.vscode/launch.json')\n", (1254, 1280), False, 'import pathlib\n'), ((4548, 4559), 'os._exit', 'os._exit', (['(1)'], {}), '(1)\n', (4556, 4559), False, 'import os\n'), ((4229, 4254), 'pathlib.Path', 'pathlib.Path', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (4241, 4254), False, 'import pathlib\n'), ((4574, 4596), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (4586, 4596), False, 'import pathlib\n'), ((4660, 4685), 'pathlib.Path', 'pathlib.Path', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (4672, 4685), False, 'import pathlib\n'), ((3968, 4023), 'json.dumps', 'json.dumps', (['template_launch_json_file_content'], {'indent': '(4)'}), '(template_launch_json_file_content, indent=4)\n', (3978, 4023), False, 'import json\n')] |
# -*- coding: utf-8 -*-
import csv
import logging as logmodule
import math
import os
import sys
import tempfile
from collections import OrderedDict
# On OS X, the default backend will fail if you are not using a Framework build of Python,
# e.g. in a virtualenv. To avoid having to set MPLBACKEND each time we use Studio,
# automatically set the backend.
if sys.platform.startswith("darwin"):
import matplotlib
if matplotlib.get_backend().lower() == "macosx":
matplotlib.use('PS')
import matplotlib.pyplot as plt
import numpy as np
import pdfkit
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.files.storage import default_storage
from django.template.loader import get_template
from django.utils.translation import ngettext
from django.utils.translation import ugettext as _
from le_utils.constants import content_kinds
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.shapes import MSO_SHAPE
from pptx.enum.text import MSO_AUTO_SIZE
from pptx.enum.text import PP_ALIGN
from pptx.text.fonts import FontFiles
from pptx.util import Inches
from pptx.util import Pt
from pressurecooker.encodings import encode_file_to_base64
from pressurecooker.encodings import write_base64_to_file
from wordcloud import WordCloud
from contentcuration.models import Channel
from contentcuration.models import ContentKind
from contentcuration.utils.files import generate_thumbnail_from_channel
from contentcuration.utils.format import format_size
AUDIO_COLOR = "#F06292"
DOCUMENT_COLOR = "#FF3D00"
EXERCISE_COLOR = "#4DB6AC"
HTML_COLOR = "#FF8F00"
VIDEO_COLOR = "#283593"
plt.switch_backend('agg') # Avoid using tkinter as it causes server to stall (https://discuss.erpnext.com/t/wkhtmltopdf-error-erpnext-v7/14673/10)
os.environ['QT_QPA_PLATFORM'] = 'offscreen' # Must be set for tests to run (https://github.com/ipython/ipython/issues/10627)
logmodule.basicConfig()
logging = logmodule.getLogger(__name__)
def _monkeypatch_font_directories():
# python-pptx automatically fails on linux systems, so patch it
# https://github.com/scanny/python-pptx/blob/master/pptx/text/fonts.py#L57
def _can_i_haz_linux(cls):
if sys.platform.startswith("linux"):
return {
# python-pptx fails if Calibri isn't found, so reroute it to a local font file
('Calibri', False, False): '/usr/share/fonts/truetype/freefont/FreeSans.ttf',
}
else:
return FontFiles._old_installed_fonts()
FontFiles._old_installed_fonts = FontFiles._installed_fonts
FontFiles._installed_fonts = classmethod(_can_i_haz_linux)
_monkeypatch_font_directories()
class PDFMixin(object):
def write_pdf(self, template, context, filepath, extra_options=None):
template = get_template(template)
html = template.render(context)
options = {
"encoding": "utf-8-sig",
"quiet": "",
'page-size': 'Letter',
'margin-top': '0.5in',
'margin-right': '0.5in',
'margin-bottom': '0.5in',
'margin-left': '0.5in',
}
if extra_options:
options.update(extra_options)
pdfkit.from_string(html, filepath, options=options)
return filepath
class PPTMixin(object):
slide = None
width = float(10)
height = float(5.6)
def get_next_slide(self):
self.ppt.slide_width = Inches(self.width)
self.ppt.slide_height = Inches(self.height)
slide_layout = self.ppt.slide_layouts[6] # Get a blank slide
self.slide = self.ppt.slides.add_slide(slide_layout)
def get_rgb_from_hex(self, hexval):
hexval = hexval.upper()
mapping = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15}
red = mapping[hexval[1]] * 16 + mapping[hexval[2]]
green = mapping[hexval[3]] * 16 + mapping[hexval[4]]
blue = mapping[hexval[5]] * 16 + mapping[hexval[6]]
return RGBColor(red, green, blue)
def generate_textbox(self, left=0, top=0, width=12, height=1, word_wrap=True):
left = Inches(left)
top = Inches(top)
width = Inches(width)
height = Inches(height)
textbox = self.slide.shapes.add_textbox(left, top, width, height)
textframe = textbox.text_frame
textframe.word_wrap = word_wrap
return textframe
def add_line(self, textframe, text, fontsize=12, bold=False, color=None, italic=False, space_after=0.5, space_before=0, append=True):
p = textframe.add_paragraph() if append else textframe.paragraphs[0]
p.space_after = Pt(space_after)
p.space_before = Pt(space_before)
self.add_run(p, text, fontsize=fontsize, bold=bold, color=color, italic=italic)
return p
def add_run(self, paragraph, text, fontsize=12, bold=False, color=None, italic=False):
run = paragraph.add_run()
run.font.size = Pt(fontsize)
run.font.name = 'Calibri'
run.font.bold = bold
run.font.italic = italic
run.font.color.rgb = color or RGBColor(0, 0, 0)
run.text = text
return run
def get_thumbnail_from_encoding(self, encoding):
filepath = self.get_write_to_path(ext="png")
write_base64_to_file(encoding, filepath)
return filepath
def add_picture(self, encoding, left=0, top=0, width=2, height=2):
filepath = self.get_write_to_path(ext="png")
write_base64_to_file(encoding, filepath)
return self.slide.shapes.add_picture(filepath, Inches(left), Inches(top), width=Inches(width), height=Inches(height))
def add_shape(self, shape=MSO_SHAPE.RECTANGLE, left=0, top=0, width=1, height=1, color=None):
shape = self.slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Inches(left), Inches(top), Inches(width), Inches(height))
shape.fill.solid()
shape.fill.fore_color.rgb = color or RGBColor(0, 0, 0)
shape.line.color.rgb = color or RGBColor(0, 0, 0)
shape.shadow.inherit = False
return shape
class CSVMixin(object):
def write_csv(self, filepath, rows, header=None):
with open(filepath, 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
if header:
writer.writerow(header)
for row in rows:
writer.writerow(row)
return filepath
class ExportWriter(object):
tempfiles = None
ext = None
messages = {
content_kinds.TOPIC: _("Topic"),
content_kinds.VIDEO: _("Video"),
content_kinds.AUDIO: _("Audio"),
content_kinds.EXERCISE: _("Exercise"),
content_kinds.DOCUMENT: _("Document"),
content_kinds.HTML5: _("Html App"),
content_kinds.TOPIC + "_plural": _("Topics"),
content_kinds.VIDEO + "_plural": _("Videos"),
content_kinds.AUDIO + "_plural": _("Audios"),
content_kinds.EXERCISE + "_plural": _("Exercises"),
content_kinds.DOCUMENT + "_plural": _("Documents"),
content_kinds.HTML5 + "_plural": _("Html Apps"),
"resource": _("Total Resource"),
"resource_plural": _("Total Resources")
}
def __init__(self, *args, **kwargs):
self.tempfiles = []
def pluralize_constant(self, count, constant, sep=' '):
return ngettext(
'%(count)d%(sep)s%(singular)s',
'%(count)d%(sep)s%(plural)s',
count
) % {
'count': count,
'singular': self.messages.get(constant),
'plural': self.messages.get(constant + "_plural"),
'sep': sep
}
def get_write_to_path(self, ext=None):
ext = ext or self.ext
tempf = tempfile.NamedTemporaryFile(suffix=".{}".format(ext), delete=False)
self.tempfiles.append(tempf.name)
return tempf.name
def write(self, *args, **kwargs):
raise NotImplementedError("Must implement a write method for this class")
def delete_tempfiles(self):
for tempf in self.tempfiles:
os.unlink(tempf)
self.tempfiles = []
class ChannelDetailsWriter(ExportWriter):
color_selection = [AUDIO_COLOR, DOCUMENT_COLOR, EXERCISE_COLOR, HTML_COLOR, VIDEO_COLOR]
condensed_tag_limit = 10
size_divisor = 100000000
scale_text = [_("Very Small")] * 2 + [_("Small")] * 2 + [_("Average")] * 3 + [_("Large")] * 2 + [_("Very Large")] * 2
tagcloud_width = 600
tagcloud_height = None
def __init__(self, channel_ids, site=None, condensed=False, filename=None):
super(ChannelDetailsWriter, self).__init__()
self.channels = Channel.objects.filter(pk__in=channel_ids) # Implementing as a list so we can easily make this apply to bundles
self.filename = filename
if self.channels.count() == 1 and not filename:
self.filename = self.channels[0].pk
elif not filename:
raise ValueError("Must specify a filename if channel count is greater than 1")
self.site = site or Site.objects.get(id=1)
self.condensed = condensed
def write(self, *args, **kwargs):
try:
filepath = self.get_write_to_path()
self._write_details(filepath)
saved_filename = "{}.{}".format(self.filename, self.ext)
save_to_path = os.path.sep.join([settings.EXPORT_ROOT, saved_filename])
# Write file to default storage
with open(filepath, 'rb') as fobj:
default_storage.save(save_to_path, fobj)
return save_to_path
finally:
self.delete_tempfiles()
def _write_details(self, *args, **kwargs):
raise NotImplementedError("Must implement a write_export_file method for ChannelDetailsWriter subclasses")
def get_channel_data(self, channel):
data = channel.main_tree.get_details()
primarytoken = channel.secret_tokens.filter(is_primary=True).first()
data.update({
"channel": channel,
"site": 'https://' + self.site.domain,
"thumbnail": generate_thumbnail_from_channel(channel, dimension=300) or self.get_default_thumbnail_encoding(),
"tokens": [str(t) for t in channel.secret_tokens.exclude(token=channel.pk).filter(is_primary=True)],
"primarytoken": primarytoken and str(primarytoken),
"storage": self.get_storage_bar(data['resource_size']),
"size": self.get_size_bar(data['resource_count']),
"piechart": self.get_pie_chart(data['kind_count'], small_layout=self.condensed),
"tagcloud": data['tags'] and self.get_tagcloud(data['tags'], tag_limit=self.condensed and self.condensed_tag_limit),
})
return data
def get_default_thumbnail_encoding(self):
try:
filepath = os.path.join(settings.STATIC_ROOT, 'img', 'kolibri_placeholder.png')
return encode_file_to_base64(filepath, "data:image/png;base64,")
except IOError:
logging.warning("Could not find {}".format(filepath))
def get_storage_bar(self, size):
try:
size_index = int(max(1, min(math.ceil(math.log(size/self.size_divisor, 2)), 10)))
except ValueError:
size_index = 1
return {
"filled": range(size_index),
"text": self.scale_text[size_index],
"storage": "{} {}".format(*format_size(size)),
}
def get_size_bar(self, count):
try:
size_index = int(max(1, min(math.floor(math.log(count, 2.8)), 10)))
except ValueError:
size_index = 1
return {
"filled": size_index,
"scale": range(len(self.scale_text)),
"text": self.scale_text[size_index]
}
def get_pie_chart(self, counts, small_layout=False):
# Put kind counts in a usable format
kinds = list(ContentKind.objects.exclude(kind=content_kinds.TOPIC)
.order_by('kind')
.values_list('kind', flat=True))
kind_vals = {k: next((c['count'] for c in counts if c['kind_id'] == k), 0) for k in kinds}
kind_vals = OrderedDict(sorted(kind_vals.items()))
sizes = [v for k, v in kind_vals.items()]
total = max(sum(sizes), 1)
labels = [{
"text": ' {text} \n{p:.1f}%'.format(
text=self.pluralize_constant(v, k),
p=float(v)/total * 100.0
),
"count": v
} for k, v in kind_vals.items()]
# Create pie chart
fig, ax = plt.subplots(subplot_kw=dict(aspect="equal"))
wedgeprops = {"edgecolor": "white", 'linewidth': 1, 'linestyle': 'solid', 'antialiased': True}
wedges, texts = ax.pie(sizes, colors=self.color_selection, wedgeprops=wedgeprops)
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(xycoords='data', textcoords='data', arrowprops=dict(arrowstyle="-"),
bbox=bbox_props, zorder=0, va="center")
# Add popout labels for the larger layout
if not small_layout:
for i, p in enumerate(wedges):
if not labels[i]['count']:
continue
ang = (p.theta2 - p.theta1)/2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle, "facecolor": "gray"})
ax.annotate(labels[i]['text'], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
ha="center", fontsize=10, **kw)
# Add legend for the smaller layout
else:
plt.legend(
loc='center left',
labels=[l['text'].split('\n')[0] for l in labels],
prop={'size': 20},
bbox_to_anchor=(0.7, 0.5),
bbox_transform=plt.gcf().transFigure
)
# Set up size variables for center circle
center_text_size = 25 if small_layout else 20 # Renders smaller, so text needs to be bigger
center_text_ratio = 0.75 if small_layout else 0.6
# Add center circle
circle = plt.Circle((0, 0), center_text_ratio, fc='white')
centertext = self.pluralize_constant(sum(sizes), "resource", sep='\n').split('\n')
plt.annotate(centertext[0], xy=(0, 0.1), fontsize=center_text_size, ha="center")
plt.annotate(centertext[1], xy=(0, -0.15), fontsize=center_text_size - 5, ha="center")
fig = plt.gcf()
fig.gca().add_artist(circle)
plt.tight_layout()
# Write chart to image and get encoding
filepath = self.get_write_to_path(ext="png")
plt.savefig(filepath, bbox_inches='tight')
plt.clf()
plt.close()
return encode_file_to_base64(filepath, "data:image/png;base64,")
def get_tagcloud(self, tags, tag_limit=None):
tag_limit = tag_limit or len(tags)
tags = sorted(tags, key=lambda kv: -kv['count'])[:tag_limit] # Get top X tags
tag_dict = {t['tag_name']: t['count'] for t in tags}
# Generate a word cloud image
wordcloud = WordCloud(
background_color='white',
min_font_size=10,
max_font_size=60,
width=self.tagcloud_width,
height=self.tagcloud_height or 30 * len(tags) / 2 + 10,
font_path=os.path.sep.join([settings.STATIC_ROOT, 'fonts', 'OpenSans-Regular.ttf'])
).generate_from_frequencies(tag_dict)
tag_counts = [t['count'] for t in tags]
step = (float(max(tag_counts))) / len(self.color_selection)
thresholds = list(reversed([int(round(i * step)) for i in range(len(self.color_selection))]))
def get_color(word, font_size, position, orientation, random_state=None, **kwargs):
index = next((i for i, t in enumerate(thresholds) if tag_dict[word] >= t), 0)
return self.color_selection[index]
wordcloud.recolor(color_func=get_color)
image = wordcloud.to_image()
filepath = self.get_write_to_path(ext="png")
image.save(filepath)
return encode_file_to_base64(filepath, "data:image/png;base64,")
class ChannelDetailsPDFWriter(ChannelDetailsWriter, PDFMixin):
ext = "pdf"
def __init__(self, channel_ids, condensed=False, **kwargs):
super(ChannelDetailsPDFWriter, self).__init__(channel_ids, condensed=condensed, **kwargs)
self.filename = "{} (condensed)".format(self.filename) if condensed else self.filename
self.template = "export/channel_detail_pdf_condensed.html" if condensed else "export/channel_detail_pdf.html"
def _write_details(self, filepath):
if self.channels.count() == 1:
footer_text = _("Page %(page)s of %(pagecount)s - %(channel)s can be found on Kolibri Studio, a product of Learning Equality") \
% {"page": "[page]", "pagecount": "[topage]", "channel": self.channels[0].name[:40]}
else:
footer_text = _("Page %(page)s of %(pagecount)s - These channels can be found on Kolibri Studio, a product of Learning Equality") \
% {"page": "[page]", "pagecount": "[topage]"}
data = {
"channels": [self.get_channel_data(channel) for channel in self.channels],
"colors": {
"audio": AUDIO_COLOR,
"document": DOCUMENT_COLOR,
"exercise": EXERCISE_COLOR,
"html": HTML_COLOR,
"video": VIDEO_COLOR,
}
}
try:
self.write_pdf(self.template, data, filepath, extra_options={"footer-center": footer_text, "footer-font-size": "9"})
except IOError as e:
logging.error("Unable to generate PDF, attempting without footer: {}".format(str(e)))
self.write_pdf(self.template, data, filepath)
class ChannelDetailsPPTWriter(ChannelDetailsWriter, PPTMixin):
ext = "pptx"
tagcloud_width = 430
tagcloud_height = 210
condensed_tag_limit = 20
gray = RGBColor(170, 170, 170)
def __init__(self, channel_ids, **kwargs):
super(ChannelDetailsPPTWriter, self).__init__(channel_ids, condensed=True, **kwargs)
def _write_details(self, filepath):
self.ppt = Presentation()
for channel in self.channels:
self.write_slide(channel)
# Save the file
self.ppt.save(filepath)
def write_slide(self, channel):
self.get_next_slide()
data = self.get_channel_data(channel)
next_line = 0.1 # Keeps track of last line (useful for setting the top location of shapes)
# Add thumbnail
padding = 0.2
thumbnail_width = 1.1
if data['thumbnail']:
thumbnail = self.add_picture(data['thumbnail'], padding, padding, thumbnail_width, thumbnail_width)
thumbnail.line.color.rgb = self.gray
thumbnail.line.width = Inches(0.01)
# Add title/description
title_left = thumbnail_width + padding * 2
title_height = 0.5
title_tf = self.generate_textbox(title_left, next_line, self.width - title_left, title_height)
title_tf.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE
self.add_line(title_tf, channel.name, fontsize=24, bold=True, append=False)
next_line += title_height
# Variables for section under title
includes_width = 2
size_height = 0.5
description_height = 1.25
size_width = self.width - title_left - includes_width - padding * 2
# Add language information
icon_width = 0.2
language_left = size_width + title_left + padding
language_icon_path = os.path.join(settings.STATIC_ROOT, 'img', 'export', 'language.png')
encoding = encode_file_to_base64(language_icon_path, 'data:image/png;base64,')
self.add_picture(encoding, language_left, next_line + 0.04, icon_width, icon_width)
includes_tf = self.generate_textbox(language_left + icon_width - 0.08, next_line, includes_width, size_height + description_height)
language = channel.language.native_name if channel.language else _("No language set")
self.add_line(includes_tf, " {}".format(language), append=False, bold=True)
if data['accessible_languages']:
self.add_line(includes_tf, _(" * Subtitles included"), fontsize=10, space_before=2)
# Add For Educators: Coach Content
if data['includes'].get('coach_content'):
coach_content = self.add_line(includes_tf, "✔", bold=True, color=self.get_rgb_from_hex(EXERCISE_COLOR), space_before=4)
self.add_run(coach_content, _(" Coach Content"))
# Add For Educators: Assessments
if data['includes'].get('exercises'):
assessments = self.add_line(includes_tf, "✔", bold=True, color=self.get_rgb_from_hex(EXERCISE_COLOR), space_before=4)
self.add_run(assessments, _(" Assessments"))
# Add size information
size_tf = self.generate_textbox(title_left, next_line, size_width, size_height)
size_bar = self.add_line(size_tf, "", append=False)
for i in data['size']['scale']:
self.add_run(size_bar, "▮", color=self.get_rgb_from_hex(EXERCISE_COLOR) if i < data['size']['filled'] else self.gray, fontsize=14)
self.add_line(size_tf, _("Channel size: %(size)s") % {"size": data['size']['text'].lower()}, fontsize=8, italic=True, color=self.gray)
next_line += size_height
# Add description
description_tf = self.generate_textbox(title_left, next_line, size_width, description_height)
self.add_line(description_tf, channel.description, color=self.gray, append=False)
description_tf.fit_text()
next_line += description_height + 0.1
# Add separator with headers
separator_height = 0.3
self.add_shape(left=0, top=next_line, width=self.width/2, height=separator_height, color=self.get_rgb_from_hex(EXERCISE_COLOR))
resource_header = self.generate_textbox(padding, next_line, self.width / 2 - padding, separator_height)
self.add_line(resource_header, _("Resource Breakdown"), bold=True, color=self.get_rgb_from_hex("#FFFFFF"), append=False)
self.add_shape(left=self.width/2, top=next_line, width=self.width/2, height=separator_height, color=self.get_rgb_from_hex("#595959"))
tag_header = self.generate_textbox(padding + self.width / 2 - padding, next_line, self.width / 2 - padding, separator_height)
self.add_line(tag_header, _("Most Common Tags"), bold=True, color=self.get_rgb_from_hex("#FFFFFF"), append=False)
next_line += separator_height + 0.05
# Add piechart
chart_height = 2.3
if data['resource_count']:
self.add_picture(data['piechart'], 0, next_line, self.width / 2 - 1, height=chart_height)
else:
empty_tf = self.generate_textbox(0, next_line, self.width / 2, chart_height)
empty_line = self.add_line(empty_tf, _("No Resources Found"), color=self.gray, fontsize=14, italic=True)
empty_line.alignment = PP_ALIGN.CENTER
# Add tagcloud
if data['tags']:
self.add_picture(data['tagcloud'], self.width/2 + padding, next_line + 0.1, self.width / 2 - 1, chart_height - padding * 2)
else:
empty_tf = self.generate_textbox(self.width / 2, next_line, self.width / 2, chart_height)
empty_line = self.add_line(empty_tf, _("No Tags Found"), color=self.gray, fontsize=14, italic=True)
empty_line.alignment = PP_ALIGN.CENTER
next_line += chart_height + 0.01
# Add logo
logo_width = 0.9
logo_height = 0.25
logo_left = Inches(self.width / 2 - logo_width / 2)
try:
logo_url = os.path.join(settings.STATIC_ROOT, 'img', 'le_login.png')
self.slide.shapes.add_picture(logo_url, logo_left, Inches(next_line), width=Inches(logo_width), height=Inches(logo_height))
except IOError:
logging.warning("Unable to add LE logo")
next_line += logo_height
# Add disclaimer
disclaimer_tf = self.generate_textbox(0, next_line, self.width, 0.2)
disclaimer_line = self.add_line(disclaimer_tf, _("This slide was automatically generated by Kolibri Studio, a product of Learning Equality"),
fontsize=7, color=self.gray, append=False)
disclaimer_line.alignment = PP_ALIGN.CENTER
class ChannelDetailsCSVWriter(ChannelDetailsWriter, CSVMixin):
ext = "csv"
def _write_details(self, filepath):
header = [_("Name"), _("Description"), _("Language"), _("Token"), _("Size"), _("Storage"), _("Resources"),
_("Languages"), _("Subtitles"), _("Coach Content?"), _("Assessments?"), _("Tags"), _("Authors"),
_("Providers"), _("Aggregators"), _("Licenses"), _("Copyright Holders")]
rows = []
for channel in self.channels:
data = self.get_channel_data(channel)
language = channel.language.native_name if channel.language else _("No language set")
token = data['primarytoken'] if data['primarytoken'] else _("Publish channel to get token")
size = "{} - {}".format(self.pluralize_constant(data['resource_count'], "resource"), data['size']['text'])
storage = "{} - {}".format(data['storage']['storage'], data['storage']['text'])
resources = " | ".join([self.pluralize_constant(k['count'], k['kind_id']) for k in data['kind_count']])
languages = " | ".join(data['languages'])
subtitles = " | ".join(data['accessible_languages'])
coach_content = _("Yes") if data['includes']['coach_content'] else _("No")
assessments = _("Yes") if data['includes']['exercises'] else _("No")
tags = " | ".join([t['tag_name'] for t in data['tags']])
authors = " | ".join(data['authors'])
providers = " | ".join(data['providers'])
aggregators = " | ".join(data['aggregators'])
licenses = " | ".join(data['licenses']).encode('utf-8')
copyright_holders = " | ".join(data['copyright_holders'])
rows.append([channel.name, channel.description, language, token, size, storage, resources,
languages, subtitles, coach_content, assessments, tags, authors, providers,
aggregators, licenses, copyright_holders])
return self.write_csv(filepath, rows, header=header)
| [
"logging.getLogger",
"contentcuration.utils.format.format_size",
"pdfkit.from_string",
"sys.platform.startswith",
"pptx.Presentation",
"math.log",
"matplotlib.pyplot.annotate",
"os.path.sep.join",
"matplotlib.pyplot.switch_backend",
"pressurecooker.encodings.encode_file_to_base64",
"pptx.dml.col... | [((359, 392), 'sys.platform.startswith', 'sys.platform.startswith', (['"""darwin"""'], {}), "('darwin')\n", (382, 392), False, 'import sys\n'), ((1653, 1678), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (1671, 1678), True, 'import matplotlib.pyplot as plt\n'), ((1927, 1950), 'logging.basicConfig', 'logmodule.basicConfig', ([], {}), '()\n', (1948, 1950), True, 'import logging as logmodule\n'), ((1961, 1990), 'logging.getLogger', 'logmodule.getLogger', (['__name__'], {}), '(__name__)\n', (1980, 1990), True, 'import logging as logmodule\n'), ((18342, 18365), 'pptx.dml.color.RGBColor', 'RGBColor', (['(170)', '(170)', '(170)'], {}), '(170, 170, 170)\n', (18350, 18365), False, 'from pptx.dml.color import RGBColor\n'), ((477, 497), 'matplotlib.use', 'matplotlib.use', (['"""PS"""'], {}), "('PS')\n", (491, 497), False, 'import matplotlib\n'), ((2220, 2252), 'sys.platform.startswith', 'sys.platform.startswith', (['"""linux"""'], {}), "('linux')\n", (2243, 2252), False, 'import sys\n'), ((2824, 2846), 'django.template.loader.get_template', 'get_template', (['template'], {}), '(template)\n', (2836, 2846), False, 'from django.template.loader import get_template\n'), ((3236, 3287), 'pdfkit.from_string', 'pdfkit.from_string', (['html', 'filepath'], {'options': 'options'}), '(html, filepath, options=options)\n', (3254, 3287), False, 'import pdfkit\n'), ((3463, 3481), 'pptx.util.Inches', 'Inches', (['self.width'], {}), '(self.width)\n', (3469, 3481), False, 'from pptx.util import Inches\n'), ((3514, 3533), 'pptx.util.Inches', 'Inches', (['self.height'], {}), '(self.height)\n', (3520, 3533), False, 'from pptx.util import Inches\n'), ((4086, 4112), 'pptx.dml.color.RGBColor', 'RGBColor', (['red', 'green', 'blue'], {}), '(red, green, blue)\n', (4094, 4112), False, 'from pptx.dml.color import RGBColor\n'), ((4212, 4224), 'pptx.util.Inches', 'Inches', (['left'], {}), '(left)\n', (4218, 4224), False, 'from pptx.util import Inches\n'), ((4239, 4250), 'pptx.util.Inches', 'Inches', (['top'], {}), '(top)\n', (4245, 4250), False, 'from pptx.util import Inches\n'), ((4267, 4280), 'pptx.util.Inches', 'Inches', (['width'], {}), '(width)\n', (4273, 4280), False, 'from pptx.util import Inches\n'), ((4298, 4312), 'pptx.util.Inches', 'Inches', (['height'], {}), '(height)\n', (4304, 4312), False, 'from pptx.util import Inches\n'), ((4731, 4746), 'pptx.util.Pt', 'Pt', (['space_after'], {}), '(space_after)\n', (4733, 4746), False, 'from pptx.util import Pt\n'), ((4772, 4788), 'pptx.util.Pt', 'Pt', (['space_before'], {}), '(space_before)\n', (4774, 4788), False, 'from pptx.util import Pt\n'), ((5044, 5056), 'pptx.util.Pt', 'Pt', (['fontsize'], {}), '(fontsize)\n', (5046, 5056), False, 'from pptx.util import Pt\n'), ((5367, 5407), 'pressurecooker.encodings.write_base64_to_file', 'write_base64_to_file', (['encoding', 'filepath'], {}), '(encoding, filepath)\n', (5387, 5407), False, 'from pressurecooker.encodings import write_base64_to_file\n'), ((5565, 5605), 'pressurecooker.encodings.write_base64_to_file', 'write_base64_to_file', (['encoding', 'filepath'], {}), '(encoding, filepath)\n', (5585, 5605), False, 'from pressurecooker.encodings import write_base64_to_file\n'), ((6635, 6645), 'django.utils.translation.ugettext', '_', (['"""Topic"""'], {}), "('Topic')\n", (6636, 6645), True, 'from django.utils.translation import ugettext as _\n'), ((6676, 6686), 'django.utils.translation.ugettext', '_', (['"""Video"""'], {}), "('Video')\n", (6677, 6686), True, 'from django.utils.translation import ugettext as _\n'), ((6717, 6727), 'django.utils.translation.ugettext', '_', (['"""Audio"""'], {}), "('Audio')\n", (6718, 6727), True, 'from django.utils.translation import ugettext as _\n'), ((6761, 6774), 'django.utils.translation.ugettext', '_', (['"""Exercise"""'], {}), "('Exercise')\n", (6762, 6774), True, 'from django.utils.translation import ugettext as _\n'), ((6808, 6821), 'django.utils.translation.ugettext', '_', (['"""Document"""'], {}), "('Document')\n", (6809, 6821), True, 'from django.utils.translation import ugettext as _\n'), ((6852, 6865), 'django.utils.translation.ugettext', '_', (['"""Html App"""'], {}), "('Html App')\n", (6853, 6865), True, 'from django.utils.translation import ugettext as _\n'), ((6908, 6919), 'django.utils.translation.ugettext', '_', (['"""Topics"""'], {}), "('Topics')\n", (6909, 6919), True, 'from django.utils.translation import ugettext as _\n'), ((6962, 6973), 'django.utils.translation.ugettext', '_', (['"""Videos"""'], {}), "('Videos')\n", (6963, 6973), True, 'from django.utils.translation import ugettext as _\n'), ((7016, 7027), 'django.utils.translation.ugettext', '_', (['"""Audios"""'], {}), "('Audios')\n", (7017, 7027), True, 'from django.utils.translation import ugettext as _\n'), ((7073, 7087), 'django.utils.translation.ugettext', '_', (['"""Exercises"""'], {}), "('Exercises')\n", (7074, 7087), True, 'from django.utils.translation import ugettext as _\n'), ((7133, 7147), 'django.utils.translation.ugettext', '_', (['"""Documents"""'], {}), "('Documents')\n", (7134, 7147), True, 'from django.utils.translation import ugettext as _\n'), ((7190, 7204), 'django.utils.translation.ugettext', '_', (['"""Html Apps"""'], {}), "('Html Apps')\n", (7191, 7204), True, 'from django.utils.translation import ugettext as _\n'), ((7226, 7245), 'django.utils.translation.ugettext', '_', (['"""Total Resource"""'], {}), "('Total Resource')\n", (7227, 7245), True, 'from django.utils.translation import ugettext as _\n'), ((7274, 7294), 'django.utils.translation.ugettext', '_', (['"""Total Resources"""'], {}), "('Total Resources')\n", (7275, 7294), True, 'from django.utils.translation import ugettext as _\n'), ((8753, 8795), 'contentcuration.models.Channel.objects.filter', 'Channel.objects.filter', ([], {'pk__in': 'channel_ids'}), '(pk__in=channel_ids)\n', (8775, 8795), False, 'from contentcuration.models import Channel\n'), ((14440, 14489), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(0, 0)', 'center_text_ratio'], {'fc': '"""white"""'}), "((0, 0), center_text_ratio, fc='white')\n", (14450, 14489), True, 'import matplotlib.pyplot as plt\n'), ((14589, 14674), 'matplotlib.pyplot.annotate', 'plt.annotate', (['centertext[0]'], {'xy': '(0, 0.1)', 'fontsize': 'center_text_size', 'ha': '"""center"""'}), "(centertext[0], xy=(0, 0.1), fontsize=center_text_size, ha='center'\n )\n", (14601, 14674), True, 'import matplotlib.pyplot as plt\n'), ((14678, 14768), 'matplotlib.pyplot.annotate', 'plt.annotate', (['centertext[1]'], {'xy': '(0, -0.15)', 'fontsize': '(center_text_size - 5)', 'ha': '"""center"""'}), "(centertext[1], xy=(0, -0.15), fontsize=center_text_size - 5,\n ha='center')\n", (14690, 14768), True, 'import matplotlib.pyplot as plt\n'), ((14779, 14788), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (14786, 14788), True, 'import matplotlib.pyplot as plt\n'), ((14834, 14852), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (14850, 14852), True, 'import matplotlib.pyplot as plt\n'), ((14963, 15005), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filepath'], {'bbox_inches': '"""tight"""'}), "(filepath, bbox_inches='tight')\n", (14974, 15005), True, 'import matplotlib.pyplot as plt\n'), ((15014, 15023), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (15021, 15023), True, 'import matplotlib.pyplot as plt\n'), ((15032, 15043), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15041, 15043), True, 'import matplotlib.pyplot as plt\n'), ((15059, 15116), 'pressurecooker.encodings.encode_file_to_base64', 'encode_file_to_base64', (['filepath', '"""data:image/png;base64,"""'], {}), "(filepath, 'data:image/png;base64,')\n", (15080, 15116), False, 'from pressurecooker.encodings import encode_file_to_base64\n'), ((16408, 16465), 'pressurecooker.encodings.encode_file_to_base64', 'encode_file_to_base64', (['filepath', '"""data:image/png;base64,"""'], {}), "(filepath, 'data:image/png;base64,')\n", (16429, 16465), False, 'from pressurecooker.encodings import encode_file_to_base64\n'), ((18567, 18581), 'pptx.Presentation', 'Presentation', ([], {}), '()\n', (18579, 18581), False, 'from pptx import Presentation\n'), ((19997, 20064), 'os.path.join', 'os.path.join', (['settings.STATIC_ROOT', '"""img"""', '"""export"""', '"""language.png"""'], {}), "(settings.STATIC_ROOT, 'img', 'export', 'language.png')\n", (20009, 20064), False, 'import os\n'), ((20084, 20151), 'pressurecooker.encodings.encode_file_to_base64', 'encode_file_to_base64', (['language_icon_path', '"""data:image/png;base64,"""'], {}), "(language_icon_path, 'data:image/png;base64,')\n", (20105, 20151), False, 'from pressurecooker.encodings import encode_file_to_base64\n'), ((24056, 24095), 'pptx.util.Inches', 'Inches', (['(self.width / 2 - logo_width / 2)'], {}), '(self.width / 2 - logo_width / 2)\n', (24062, 24095), False, 'from pptx.util import Inches\n'), ((2511, 2543), 'pptx.text.fonts.FontFiles._old_installed_fonts', 'FontFiles._old_installed_fonts', ([], {}), '()\n', (2541, 2543), False, 'from pptx.text.fonts import FontFiles\n'), ((5191, 5208), 'pptx.dml.color.RGBColor', 'RGBColor', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (5199, 5208), False, 'from pptx.dml.color import RGBColor\n'), ((5661, 5673), 'pptx.util.Inches', 'Inches', (['left'], {}), '(left)\n', (5667, 5673), False, 'from pptx.util import Inches\n'), ((5675, 5686), 'pptx.util.Inches', 'Inches', (['top'], {}), '(top)\n', (5681, 5686), False, 'from pptx.util import Inches\n'), ((5896, 5908), 'pptx.util.Inches', 'Inches', (['left'], {}), '(left)\n', (5902, 5908), False, 'from pptx.util import Inches\n'), ((5910, 5921), 'pptx.util.Inches', 'Inches', (['top'], {}), '(top)\n', (5916, 5921), False, 'from pptx.util import Inches\n'), ((5923, 5936), 'pptx.util.Inches', 'Inches', (['width'], {}), '(width)\n', (5929, 5936), False, 'from pptx.util import Inches\n'), ((5938, 5952), 'pptx.util.Inches', 'Inches', (['height'], {}), '(height)\n', (5944, 5952), False, 'from pptx.util import Inches\n'), ((6026, 6043), 'pptx.dml.color.RGBColor', 'RGBColor', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (6034, 6043), False, 'from pptx.dml.color import RGBColor\n'), ((6084, 6101), 'pptx.dml.color.RGBColor', 'RGBColor', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (6092, 6101), False, 'from pptx.dml.color import RGBColor\n'), ((6307, 6368), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n", (6317, 6368), False, 'import csv\n'), ((7447, 7524), 'django.utils.translation.ngettext', 'ngettext', (['"""%(count)d%(sep)s%(singular)s"""', '"""%(count)d%(sep)s%(plural)s"""', 'count'], {}), "('%(count)d%(sep)s%(singular)s', '%(count)d%(sep)s%(plural)s', count)\n", (7455, 7524), False, 'from django.utils.translation import ngettext\n'), ((8181, 8197), 'os.unlink', 'os.unlink', (['tempf'], {}), '(tempf)\n', (8190, 8197), False, 'import os\n'), ((9149, 9171), 'django.contrib.sites.models.Site.objects.get', 'Site.objects.get', ([], {'id': '(1)'}), '(id=1)\n', (9165, 9171), False, 'from django.contrib.sites.models import Site\n'), ((9446, 9502), 'os.path.sep.join', 'os.path.sep.join', (['[settings.EXPORT_ROOT, saved_filename]'], {}), '([settings.EXPORT_ROOT, saved_filename])\n', (9462, 9502), False, 'import os\n'), ((10940, 11008), 'os.path.join', 'os.path.join', (['settings.STATIC_ROOT', '"""img"""', '"""kolibri_placeholder.png"""'], {}), "(settings.STATIC_ROOT, 'img', 'kolibri_placeholder.png')\n", (10952, 11008), False, 'import os\n'), ((11028, 11085), 'pressurecooker.encodings.encode_file_to_base64', 'encode_file_to_base64', (['filepath', '"""data:image/png;base64,"""'], {}), "(filepath, 'data:image/png;base64,')\n", (11049, 11085), False, 'from pressurecooker.encodings import encode_file_to_base64\n'), ((19232, 19244), 'pptx.util.Inches', 'Inches', (['(0.01)'], {}), '(0.01)\n', (19238, 19244), False, 'from pptx.util import Inches\n'), ((20460, 20480), 'django.utils.translation.ugettext', '_', (['"""No language set"""'], {}), "('No language set')\n", (20461, 20480), True, 'from django.utils.translation import ugettext as _\n'), ((22464, 22487), 'django.utils.translation.ugettext', '_', (['"""Resource Breakdown"""'], {}), "('Resource Breakdown')\n", (22465, 22487), True, 'from django.utils.translation import ugettext as _\n'), ((22865, 22886), 'django.utils.translation.ugettext', '_', (['"""Most Common Tags"""'], {}), "('Most Common Tags')\n", (22866, 22886), True, 'from django.utils.translation import ugettext as _\n'), ((24132, 24189), 'os.path.join', 'os.path.join', (['settings.STATIC_ROOT', '"""img"""', '"""le_login.png"""'], {}), "(settings.STATIC_ROOT, 'img', 'le_login.png')\n", (24144, 24189), False, 'import os\n'), ((24595, 24693), 'django.utils.translation.ugettext', '_', (['"""This slide was automatically generated by Kolibri Studio, a product of Learning Equality"""'], {}), "('This slide was automatically generated by Kolibri Studio, a product of Learning Equality'\n )\n", (24596, 24693), True, 'from django.utils.translation import ugettext as _\n'), ((24965, 24974), 'django.utils.translation.ugettext', '_', (['"""Name"""'], {}), "('Name')\n", (24966, 24974), True, 'from django.utils.translation import ugettext as _\n'), ((24976, 24992), 'django.utils.translation.ugettext', '_', (['"""Description"""'], {}), "('Description')\n", (24977, 24992), True, 'from django.utils.translation import ugettext as _\n'), ((24994, 25007), 'django.utils.translation.ugettext', '_', (['"""Language"""'], {}), "('Language')\n", (24995, 25007), True, 'from django.utils.translation import ugettext as _\n'), ((25009, 25019), 'django.utils.translation.ugettext', '_', (['"""Token"""'], {}), "('Token')\n", (25010, 25019), True, 'from django.utils.translation import ugettext as _\n'), ((25021, 25030), 'django.utils.translation.ugettext', '_', (['"""Size"""'], {}), "('Size')\n", (25022, 25030), True, 'from django.utils.translation import ugettext as _\n'), ((25032, 25044), 'django.utils.translation.ugettext', '_', (['"""Storage"""'], {}), "('Storage')\n", (25033, 25044), True, 'from django.utils.translation import ugettext as _\n'), ((25046, 25060), 'django.utils.translation.ugettext', '_', (['"""Resources"""'], {}), "('Resources')\n", (25047, 25060), True, 'from django.utils.translation import ugettext as _\n'), ((25080, 25094), 'django.utils.translation.ugettext', '_', (['"""Languages"""'], {}), "('Languages')\n", (25081, 25094), True, 'from django.utils.translation import ugettext as _\n'), ((25096, 25110), 'django.utils.translation.ugettext', '_', (['"""Subtitles"""'], {}), "('Subtitles')\n", (25097, 25110), True, 'from django.utils.translation import ugettext as _\n'), ((25112, 25131), 'django.utils.translation.ugettext', '_', (['"""Coach Content?"""'], {}), "('Coach Content?')\n", (25113, 25131), True, 'from django.utils.translation import ugettext as _\n'), ((25133, 25150), 'django.utils.translation.ugettext', '_', (['"""Assessments?"""'], {}), "('Assessments?')\n", (25134, 25150), True, 'from django.utils.translation import ugettext as _\n'), ((25152, 25161), 'django.utils.translation.ugettext', '_', (['"""Tags"""'], {}), "('Tags')\n", (25153, 25161), True, 'from django.utils.translation import ugettext as _\n'), ((25163, 25175), 'django.utils.translation.ugettext', '_', (['"""Authors"""'], {}), "('Authors')\n", (25164, 25175), True, 'from django.utils.translation import ugettext as _\n'), ((25195, 25209), 'django.utils.translation.ugettext', '_', (['"""Providers"""'], {}), "('Providers')\n", (25196, 25209), True, 'from django.utils.translation import ugettext as _\n'), ((25211, 25227), 'django.utils.translation.ugettext', '_', (['"""Aggregators"""'], {}), "('Aggregators')\n", (25212, 25227), True, 'from django.utils.translation import ugettext as _\n'), ((25229, 25242), 'django.utils.translation.ugettext', '_', (['"""Licenses"""'], {}), "('Licenses')\n", (25230, 25242), True, 'from django.utils.translation import ugettext as _\n'), ((25244, 25266), 'django.utils.translation.ugettext', '_', (['"""Copyright Holders"""'], {}), "('Copyright Holders')\n", (25245, 25266), True, 'from django.utils.translation import ugettext as _\n'), ((423, 447), 'matplotlib.get_backend', 'matplotlib.get_backend', ([], {}), '()\n', (445, 447), False, 'import matplotlib\n'), ((5694, 5707), 'pptx.util.Inches', 'Inches', (['width'], {}), '(width)\n', (5700, 5707), False, 'from pptx.util import Inches\n'), ((5716, 5730), 'pptx.util.Inches', 'Inches', (['height'], {}), '(height)\n', (5722, 5730), False, 'from pptx.util import Inches\n'), ((8522, 8537), 'django.utils.translation.ugettext', '_', (['"""Very Large"""'], {}), "('Very Large')\n", (8523, 8537), True, 'from django.utils.translation import ugettext as _\n'), ((9611, 9651), 'django.core.files.storage.default_storage.save', 'default_storage.save', (['save_to_path', 'fobj'], {}), '(save_to_path, fobj)\n', (9631, 9651), False, 'from django.core.files.storage import default_storage\n'), ((17029, 17146), 'django.utils.translation.ugettext', '_', (['"""Page %(page)s of %(pagecount)s - %(channel)s can be found on Kolibri Studio, a product of Learning Equality"""'], {}), "('Page %(page)s of %(pagecount)s - %(channel)s can be found on Kolibri Studio, a product of Learning Equality'\n )\n", (17030, 17146), True, 'from django.utils.translation import ugettext as _\n'), ((17297, 17417), 'django.utils.translation.ugettext', '_', (['"""Page %(page)s of %(pagecount)s - These channels can be found on Kolibri Studio, a product of Learning Equality"""'], {}), "('Page %(page)s of %(pagecount)s - These channels can be found on Kolibri Studio, a product of Learning Equality'\n )\n", (17298, 17417), True, 'from django.utils.translation import ugettext as _\n'), ((20645, 20674), 'django.utils.translation.ugettext', '_', (['""" * Subtitles included"""'], {}), "(' * Subtitles included')\n", (20646, 20674), True, 'from django.utils.translation import ugettext as _\n'), ((20971, 20990), 'django.utils.translation.ugettext', '_', (['""" Coach Content"""'], {}), "(' Coach Content')\n", (20972, 20990), True, 'from django.utils.translation import ugettext as _\n'), ((21248, 21265), 'django.utils.translation.ugettext', '_', (['""" Assessments"""'], {}), "(' Assessments')\n", (21249, 21265), True, 'from django.utils.translation import ugettext as _\n'), ((21663, 21690), 'django.utils.translation.ugettext', '_', (['"""Channel size: %(size)s"""'], {}), "('Channel size: %(size)s')\n", (21664, 21690), True, 'from django.utils.translation import ugettext as _\n'), ((23339, 23362), 'django.utils.translation.ugettext', '_', (['"""No Resources Found"""'], {}), "('No Resources Found')\n", (23340, 23362), True, 'from django.utils.translation import ugettext as _\n'), ((23809, 23827), 'django.utils.translation.ugettext', '_', (['"""No Tags Found"""'], {}), "('No Tags Found')\n", (23810, 23827), True, 'from django.utils.translation import ugettext as _\n'), ((24253, 24270), 'pptx.util.Inches', 'Inches', (['next_line'], {}), '(next_line)\n', (24259, 24270), False, 'from pptx.util import Inches\n'), ((25452, 25472), 'django.utils.translation.ugettext', '_', (['"""No language set"""'], {}), "('No language set')\n", (25453, 25472), True, 'from django.utils.translation import ugettext as _\n'), ((25543, 25576), 'django.utils.translation.ugettext', '_', (['"""Publish channel to get token"""'], {}), "('Publish channel to get token')\n", (25544, 25576), True, 'from django.utils.translation import ugettext as _\n'), ((26051, 26059), 'django.utils.translation.ugettext', '_', (['"""Yes"""'], {}), "('Yes')\n", (26052, 26059), True, 'from django.utils.translation import ugettext as _\n'), ((26102, 26109), 'django.utils.translation.ugettext', '_', (['"""No"""'], {}), "('No')\n", (26103, 26109), True, 'from django.utils.translation import ugettext as _\n'), ((26136, 26144), 'django.utils.translation.ugettext', '_', (['"""Yes"""'], {}), "('Yes')\n", (26137, 26144), True, 'from django.utils.translation import ugettext as _\n'), ((26183, 26190), 'django.utils.translation.ugettext', '_', (['"""No"""'], {}), "('No')\n", (26184, 26190), True, 'from django.utils.translation import ugettext as _\n'), ((8503, 8513), 'django.utils.translation.ugettext', '_', (['"""Large"""'], {}), "('Large')\n", (8504, 8513), True, 'from django.utils.translation import ugettext as _\n'), ((10198, 10253), 'contentcuration.utils.files.generate_thumbnail_from_channel', 'generate_thumbnail_from_channel', (['channel'], {'dimension': '(300)'}), '(channel, dimension=300)\n', (10229, 10253), False, 'from contentcuration.utils.files import generate_thumbnail_from_channel\n'), ((11521, 11538), 'contentcuration.utils.format.format_size', 'format_size', (['size'], {}), '(size)\n', (11532, 11538), False, 'from contentcuration.utils.format import format_size\n'), ((13470, 13485), 'numpy.deg2rad', 'np.deg2rad', (['ang'], {}), '(ang)\n', (13480, 13485), True, 'import numpy as np\n'), ((13514, 13529), 'numpy.deg2rad', 'np.deg2rad', (['ang'], {}), '(ang)\n', (13524, 13529), True, 'import numpy as np\n'), ((24278, 24296), 'pptx.util.Inches', 'Inches', (['logo_width'], {}), '(logo_width)\n', (24284, 24296), False, 'from pptx.util import Inches\n'), ((24305, 24324), 'pptx.util.Inches', 'Inches', (['logo_height'], {}), '(logo_height)\n', (24311, 24324), False, 'from pptx.util import Inches\n'), ((8482, 8494), 'django.utils.translation.ugettext', '_', (['"""Average"""'], {}), "('Average')\n", (8483, 8494), True, 'from django.utils.translation import ugettext as _\n'), ((14148, 14157), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (14155, 14157), True, 'import matplotlib.pyplot as plt\n'), ((15656, 15729), 'os.path.sep.join', 'os.path.sep.join', (["[settings.STATIC_ROOT, 'fonts', 'OpenSans-Regular.ttf']"], {}), "([settings.STATIC_ROOT, 'fonts', 'OpenSans-Regular.ttf'])\n", (15672, 15729), False, 'import os\n'), ((8439, 8454), 'django.utils.translation.ugettext', '_', (['"""Very Small"""'], {}), "('Very Small')\n", (8440, 8454), True, 'from django.utils.translation import ugettext as _\n'), ((8463, 8473), 'django.utils.translation.ugettext', '_', (['"""Small"""'], {}), "('Small')\n", (8464, 8473), True, 'from django.utils.translation import ugettext as _\n'), ((11277, 11314), 'math.log', 'math.log', (['(size / self.size_divisor)', '(2)'], {}), '(size / self.size_divisor, 2)\n', (11285, 11314), False, 'import math\n'), ((11651, 11671), 'math.log', 'math.log', (['count', '(2.8)'], {}), '(count, 2.8)\n', (11659, 11671), False, 'import math\n'), ((12018, 12071), 'contentcuration.models.ContentKind.objects.exclude', 'ContentKind.objects.exclude', ([], {'kind': 'content_kinds.TOPIC'}), '(kind=content_kinds.TOPIC)\n', (12045, 12071), False, 'from contentcuration.models import ContentKind\n'), ((13774, 13784), 'numpy.sign', 'np.sign', (['x'], {}), '(x)\n', (13781, 13784), True, 'import numpy as np\n')] |
import os
import numpy
from pydub import AudioSegment
from scipy.fftpack import fft
class AudioSignal(object):
def __init__(self, sample_rate, signal=None, filename=None):
# Set sample rate
self._sample_rate = sample_rate
if signal is None:
# Get file name and file extension
file, file_extension = os.path.splitext(filename)
# Check if file extension if audio format
if file_extension in ['.mp3', '.wav']:
# Read audio file
self._signal = self.read_audio_file(filename)
# Check if file extension if video format
elif file_extension in ['.mp4', '.mkv', 'avi']:
# Extract audio from video
new_filename = self.extract_audio_from_video(filename)
# read audio file from extracted audio file
self._signal = self.read_audio_file(new_filename)
# Case file extension is not supported
else:
print("Error: file not found or file extension not supported.")
elif filename is None:
# Cast signal to array
self._signal = signal
else:
print("Error : argument missing in AudioSignal() constructor.")
'''
Function to extract audio from a video
'''
def extract_audio_from_video(self, filename):
# Get video file name and extension
file, file_extension = os.path.splitext(filename)
# Extract audio (.wav) from video
os.system('ffmpeg -i ' + file + file_extension + ' ' + '-ar ' + str(self._sample_rate) + ' ' + file + '.wav')
print("Sucessfully converted {} into audio!".format(filename))
# Return audio file name created
return file + '.wav'
'''
Function to read audio file and to return audio samples of a specified WAV file
'''
def read_audio_file(self, filename):
# Get audio signal
audio_file = AudioSegment.from_file(filename)
# Resample audio signal
audio_file = audio_file.set_frame_rate(self._sample_rate)
# Cast to integer
if audio_file.sample_width == 2:
data = numpy.fromstring(audio_file._data, numpy.int16)
elif audio_file.sample_width == 4:
data = numpy.fromstring(audio_file._data, numpy.int32)
# Merge audio channels
audio_signal = []
for chn in list(range(audio_file.channels)):
audio_signal.append(data[chn::audio_file.channels])
audio_signal = numpy.array(audio_signal).T
# Flat signals
if audio_signal.ndim == 2:
if audio_signal.shape[1] == 1:
audio_signal = audio_signal.flatten()
# Convert stereo to mono
audio_signal = self.stereo_to_mono(audio_signal)
# Return sample rate and audio signal
return audio_signal
'''
Function to convert an input signal from stereo to mono
'''
@staticmethod
def stereo_to_mono(audio_signal):
# Check if signal is stereo and convert to mono
if isinstance(audio_signal, int):
return -1
if audio_signal.ndim == 1:
return audio_signal
elif audio_signal.ndim == 2:
if audio_signal.shape[1] == 1:
return audio_signal.flatten()
else:
if audio_signal.shape[1] == 2:
return (audio_signal[:, 1] / 2) + (audio_signal[:, 0] / 2)
else:
return -1
'''
Function to split the input signal into windows of same size
'''
def framing(self, size, step, hamming=False):
# Rescale windows step and size
win_size = int(size * self._sample_rate)
win_step = int(step * self._sample_rate)
# Number of frames
nb_frames = 1 + int((len(self._signal) - win_size) / win_step)
# Build Hamming function
if hamming is True:
ham = numpy.hamming(win_size)
else:
ham = numpy.ones(win_size)
# Split signals (and multiply each windows signals by Hamming functions)
frames = []
for t in range(nb_frames):
sub_signal = AudioSignal(self._sample_rate, signal=self._signal[(t * win_step): (t * win_step + win_size)] * ham)
frames.append(sub_signal)
return frames
'''
Function to compute the magnitude of the Discrete Fourier Transform coefficient
'''
def dft(self, norm=False):
# Commpute the magnitude of the spectrum (and normalize by the number of sample)
if norm is True:
dft = abs(fft(self._signal)) / len(self._signal)
else:
dft = abs(fft(self._signal))
return dft
'''
Function to apply pre-emphasis filter on signal
'''
def pre_emphasis(self, alpha =0.97):
# Emphasized signal
emphasized_signal = numpy.append(self._signal[0], self._signal[1:] - alpha * self._signal[:-1])
return emphasized_signal
| [
"numpy.ones",
"os.path.splitext",
"numpy.hamming",
"numpy.append",
"numpy.array",
"pydub.AudioSegment.from_file",
"scipy.fftpack.fft",
"numpy.fromstring"
] | [((1474, 1500), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (1490, 1500), False, 'import os\n'), ((1995, 2027), 'pydub.AudioSegment.from_file', 'AudioSegment.from_file', (['filename'], {}), '(filename)\n', (2017, 2027), False, 'from pydub import AudioSegment\n'), ((4962, 5037), 'numpy.append', 'numpy.append', (['self._signal[0]', '(self._signal[1:] - alpha * self._signal[:-1])'], {}), '(self._signal[0], self._signal[1:] - alpha * self._signal[:-1])\n', (4974, 5037), False, 'import numpy\n'), ((357, 383), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (373, 383), False, 'import os\n'), ((2214, 2261), 'numpy.fromstring', 'numpy.fromstring', (['audio_file._data', 'numpy.int16'], {}), '(audio_file._data, numpy.int16)\n', (2230, 2261), False, 'import numpy\n'), ((2570, 2595), 'numpy.array', 'numpy.array', (['audio_signal'], {}), '(audio_signal)\n', (2581, 2595), False, 'import numpy\n'), ((4013, 4036), 'numpy.hamming', 'numpy.hamming', (['win_size'], {}), '(win_size)\n', (4026, 4036), False, 'import numpy\n'), ((4069, 4089), 'numpy.ones', 'numpy.ones', (['win_size'], {}), '(win_size)\n', (4079, 4089), False, 'import numpy\n'), ((2324, 2371), 'numpy.fromstring', 'numpy.fromstring', (['audio_file._data', 'numpy.int32'], {}), '(audio_file._data, numpy.int32)\n', (2340, 2371), False, 'import numpy\n'), ((4757, 4774), 'scipy.fftpack.fft', 'fft', (['self._signal'], {}), '(self._signal)\n', (4760, 4774), False, 'from scipy.fftpack import fft\n'), ((4682, 4699), 'scipy.fftpack.fft', 'fft', (['self._signal'], {}), '(self._signal)\n', (4685, 4699), False, 'from scipy.fftpack import fft\n')] |
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2020 The Pybricks Authors
# Expose method and class written in C
from _pybricks.tools import wait, StopWatch
# Imports for DataLog implementation
from utime import localtime, ticks_us
class DataLog:
def __init__(self, *headers, name="log", timestamp=True, extension="csv", append=False):
# Make timestamp of the form yyyy_mm_dd_hh_mm_ss_uuuuuu
if timestamp:
y, mo, d, h, mi, s = localtime()[0:6]
u = ticks_us() % 1000000
stamp = "_{0}_{1:02d}_{2:02d}_{3:02d}_{4:02d}_{5:02d}_{6:06d}".format(
y, mo, d, h, mi, s, u
)
else:
stamp = ""
# File write mode
mode = "a+" if append else "w+"
# Append extension and open
self.file = open("{0}{1}.{2}".format(name, stamp, extension), mode)
# Get length of existing contents
self.file.seek(0, 2)
length = self.file.tell()
# If column headers were given and we are at the start of the file, print headers as first line
if len(headers) > 0 and length == 0:
print(*headers, sep=", ", file=self.file)
def log(self, *values):
print(*values, sep=", ", file=self.file)
def __repr__(self):
self.file.seek(0, 0)
return self.file.read()
| [
"utime.ticks_us",
"utime.localtime"
] | [((468, 479), 'utime.localtime', 'localtime', ([], {}), '()\n', (477, 479), False, 'from utime import localtime, ticks_us\n'), ((501, 511), 'utime.ticks_us', 'ticks_us', ([], {}), '()\n', (509, 511), False, 'from utime import localtime, ticks_us\n')] |
# -*- coding: utf-8 -*-
"""
#The following formula is used
#Adjusted Volume = Raw Volume - Regression Slope * (TIV - Cohort Mean TIV)
#Reference Literature: Voevodskaya et al, 2014: The effects of intracranial volume adjustment approaches on multiple regional MRI volumes in healthy aging and Alzheimer's disease
"""
import os
import pandas as pd
import re
import shutil
import glob
import numpy as np
from sklearn.linear_model import LinearRegression
from nipype import logging
from nipype.utils.filemanip import fname_presuffix, split_filename
from nipype import logging, LooseVersion
from nipype.utils.filemanip import fname_presuffix, check_depends
from nipype.interfaces.io import FreeSurferSource
from nipype.interfaces.base import (
TraitedSpec,
File,
traits,
Directory,
InputMultiPath,
OutputMultiPath,
CommandLine,
CommandLineInputSpec,
isdefined,
BaseInterfaceInputSpec,
BaseInterface
)
from nipype.interfaces.freesurfer.base import FSCommand, FSTraitedSpec, FSTraitedSpecOpenMP, FSCommandOpenMP, Info
from nipype.interfaces.freesurfer.utils import copy2subjdir
__docformat__ = "restructuredtext"
iflogger = logging.getLogger("nipype.interface")
# Keeping this to avoid breaking external programs that depend on it, but
# this should not be used internally
FSVersion = Info.looseversion().vstring
class AdjustVolumeInputSpec(BaseInterfaceInputSpec):
stats_directory = Directory(desc="stat_tables directory", mandatory=True, exists=True)
diag_csv = File(desc='CSV with diagnosis', exists=True, mandatory=True)
class AdjustVolumeOutputSpec(TraitedSpec):
adjusted_stats = File(desc="a list of files with adjusted volumes")
class AdjustVolume(BaseInterface):
"""
ToDo: Example Usage:
"""
input_spec = AdjustVolumeInputSpec
output_spec = AdjustVolumeOutputSpec
def __get_sub_nr(self, sub):
"""
given a subject IDs like PROJECT_000_T1 return the number i.e. 000
it matches the first group of three numers
:param sub: subject ID
:return: subject number
"""
p = re.compile(r'\d{3}')
m = p.search(sub)
return m.group(0)
def get_vol_files(self):
"""
:return: a list with all the .dat files in the stat directory
"""
return glob.glob(self.inputs.stats_directory + '/*volume*.dat') + glob.glob(self.inputs.stats_directory + '/*quantification*.dat')
def get_merged_df(self):
df_list = [ i for i in self.get_vol_files() if not i.endswith('aseg.volume.stats.dat')]
aseg = [ i for i in self.get_vol_files() if i.endswith('aseg.volume.stats.dat')][0]
df = pd.read_csv(aseg, sep='\t|;', header=0)
df.columns = [i.lstrip().rstrip() for i in df.columns]
for f in df_list:
tmp_df = pd.read_csv(f, sep='\t', header=0)
tmp_df.columns = [i.lstrip().rstrip() for i in tmp_df.columns]
fst_col = tmp_df.columns[0] # The subjects' columns can have different names
#print(df.columns)
df = df.join(tmp_df.set_index(fst_col), on='Measure:volume', rsuffix=f.split('/')[-1])
# Diagnosis
df['nums'] = df['Measure:volume'].apply(lambda x: self.__get_sub_nr(x))
diag_df = pd.read_csv(self.inputs.diag_csv, sep=',', header=0)
#print(diag_df)
diag_df['nums'] = diag_df.Pseudonym.apply(lambda x: self.__get_sub_nr(x))
df = df.join(diag_df.set_index('nums'), on='nums')
return df
def __get_slope_list(self, df):
l = list()
etiv = df.EstimatedTotalIntraCranialVol.values
rois = [ i for i in df.columns if not ('IntraCranial' in i or 'Diagnosen' in i or 'eTIV' in i or 'Measure' in i or 'num' in i or 'Pseudonym' in i)]
for i in rois:
lm = LinearRegression()
X= etiv.reshape(-1, 1)
lm.fit(X,df[i].values)
l.append((i,lm.coef_[0]))
#print((i,lm.coef_[0]))
return l
def __get_hem_means(self, df):
"""
calculate average volume for the same roi in l and r hemisphear
"""
lh_rois = [i for i in df.columns if i.startswith('lh')]
for lh_roi in lh_rois:
rh_roi = 'rh' + lh_roi[2:]
mean_roi = 'mean' + lh_roi[2:]
df[mean_roi] = (df[lh_roi].values + df[rh_roi].values)/2
return df
def __rename_hp_amyg_columns(self, df):
"""
columns in Hp and Amygdala quantification begin with right_ or left_ instead of lh_ or rh_
This function rename those fields
"""
for i in df.columns:
if i.startswith('left_'):
df.rename(columns={i: 'lh_' + i[5:]})
if i.startswith('right_'):
df.rename(columns={i: 'rh_' + i[5:]})
return df
def __correct_volumes(self):
df = self.get_merged_df()
etiv = df.EstimatedTotalIntraCranialVol.values
mean_etiv = etiv.mean() # average estimated total intracranial volume
df_hc = df[(df.DiagnoseSCD_BL) == 0]
slope_list = self.__get_slope_list(df_hc)
#print(slope_list)
adj_df = df[['Measure:volume', 'EstimatedTotalIntraCranialVol']]
for i in slope_list:
#print('{0}, slope: {1}, mean_etiv: {2}'.format(i[0], i[1], mean_etiv))
adj_df[i[0]] = df[i[0]].values - i[1]*(df.EstimatedTotalIntraCranialVol.values - mean_etiv)
adj_df = self.__rename_hp_amyg_columns(adj_df)
adj_df = self.__get_hem_means(adj_df)
return adj_df
def _run_interface(self, runtime, correct_return_codes=(0,)):
adj_vol_file = 'adjusted_volumes.csv'
adj_df = self.__correct_volumes()
adj_df.to_csv(adj_vol_file)
setattr(self, '_adj_vol_file', adj_vol_file)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["adjusted_stats"] = getattr(self, '_adj_vol_file')
return outputs
| [
"nipype.interfaces.base.Directory",
"pandas.read_csv",
"re.compile",
"nipype.interfaces.base.File",
"nipype.interfaces.freesurfer.base.Info.looseversion",
"nipype.logging.getLogger",
"sklearn.linear_model.LinearRegression",
"glob.glob"
] | [((1168, 1205), 'nipype.logging.getLogger', 'logging.getLogger', (['"""nipype.interface"""'], {}), "('nipype.interface')\n", (1185, 1205), False, 'from nipype import logging, LooseVersion\n'), ((1330, 1349), 'nipype.interfaces.freesurfer.base.Info.looseversion', 'Info.looseversion', ([], {}), '()\n', (1347, 1349), False, 'from nipype.interfaces.freesurfer.base import FSCommand, FSTraitedSpec, FSTraitedSpecOpenMP, FSCommandOpenMP, Info\n'), ((1436, 1504), 'nipype.interfaces.base.Directory', 'Directory', ([], {'desc': '"""stat_tables directory"""', 'mandatory': '(True)', 'exists': '(True)'}), "(desc='stat_tables directory', mandatory=True, exists=True)\n", (1445, 1504), False, 'from nipype.interfaces.base import TraitedSpec, File, traits, Directory, InputMultiPath, OutputMultiPath, CommandLine, CommandLineInputSpec, isdefined, BaseInterfaceInputSpec, BaseInterface\n'), ((1520, 1580), 'nipype.interfaces.base.File', 'File', ([], {'desc': '"""CSV with diagnosis"""', 'exists': '(True)', 'mandatory': '(True)'}), "(desc='CSV with diagnosis', exists=True, mandatory=True)\n", (1524, 1580), False, 'from nipype.interfaces.base import TraitedSpec, File, traits, Directory, InputMultiPath, OutputMultiPath, CommandLine, CommandLineInputSpec, isdefined, BaseInterfaceInputSpec, BaseInterface\n'), ((1648, 1698), 'nipype.interfaces.base.File', 'File', ([], {'desc': '"""a list of files with adjusted volumes"""'}), "(desc='a list of files with adjusted volumes')\n", (1652, 1698), False, 'from nipype.interfaces.base import TraitedSpec, File, traits, Directory, InputMultiPath, OutputMultiPath, CommandLine, CommandLineInputSpec, isdefined, BaseInterfaceInputSpec, BaseInterface\n'), ((2118, 2138), 're.compile', 're.compile', (['"""\\\\d{3}"""'], {}), "('\\\\d{3}')\n", (2128, 2138), False, 'import re\n'), ((2687, 2726), 'pandas.read_csv', 'pd.read_csv', (['aseg'], {'sep': '"""\t|;"""', 'header': '(0)'}), "(aseg, sep='\\t|;', header=0)\n", (2698, 2726), True, 'import pandas as pd\n'), ((3286, 3338), 'pandas.read_csv', 'pd.read_csv', (['self.inputs.diag_csv'], {'sep': '""","""', 'header': '(0)'}), "(self.inputs.diag_csv, sep=',', header=0)\n", (3297, 3338), True, 'import pandas as pd\n'), ((2330, 2386), 'glob.glob', 'glob.glob', (["(self.inputs.stats_directory + '/*volume*.dat')"], {}), "(self.inputs.stats_directory + '/*volume*.dat')\n", (2339, 2386), False, 'import glob\n'), ((2389, 2453), 'glob.glob', 'glob.glob', (["(self.inputs.stats_directory + '/*quantification*.dat')"], {}), "(self.inputs.stats_directory + '/*quantification*.dat')\n", (2398, 2453), False, 'import glob\n'), ((2837, 2871), 'pandas.read_csv', 'pd.read_csv', (['f'], {'sep': '"""\t"""', 'header': '(0)'}), "(f, sep='\\t', header=0)\n", (2848, 2871), True, 'import pandas as pd\n'), ((3831, 3849), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (3847, 3849), False, 'from sklearn.linear_model import LinearRegression\n')] |
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from flask import Flask, request, Response, jsonify
from slackclient import SlackClient
import datetime
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
SLACK_WEBHOOK_TOKEN=os.environ['SLACK_WEBHOOK_TOKEN']
SLACK_DEV_TOKEN=os.environ['SLACK_DEV_TOKEN']
slack_client = SlackClient(SLACK_DEV_TOKEN)
app = Flask(__name__)
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def check_user():
""" This is a half-assed way of checking if the username exists by checking all the slackusers on the slack directory.
Returns list of slack users by firstname + last initial.
"""
emailnameList = list()
users_call = slack_client.api_call("users.list")
if users_call.get("ok"):
users = users_call['members']
for u in users:
if u.get('deleted') == False:
if len(str(u.get('profile').get('last_name'))) > 0:
nickname = str(
u.get('profile').get('first_name') +
u.get('profile').get('last_name')[0]).lower()
emailnameList.append(nickname)
return emailnameList
def check_calendar(username):
"""Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object, checks the first scheduled event near current time and returns it
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
eventsResult = service.events().list(
calendarId=username +
'@markmedia.co',
timeMin=now,
maxResults=2,
singleEvents=True,
orderBy='startTime').execute()
events = eventsResult.get('items', [])
if not events:
statement = "%s should be at their desk." % username
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime')
if now > start:
statement = username + " is in a meeting. \n" + \
start[11:19] + "-" + end[11:19] + " " + event['summary']
else:
statement = "%s should be at their desk" % username
return statement
@app.route("/", methods=['POST'])
def main():
if request.form.get('token') == SLACK_WEBHOOK_TOKEN:
channel_id = request.form.get('channel_id')
username = request.form.get('text').lower()
if username not in check_user():
return "%s is an invalid User. Please type `/whereis first name and last initial. E.g. yvanp`" % username
else:
json_statement = jsonify({
'response_type': 'in_channel',
'text': check_calendar(username)
})
return json_statement
return "i just don't know. I wish I understood all error messages. So if you see this, you found an error. Hurray."
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| [
"os.path.exists",
"os.makedirs",
"flask.Flask",
"argparse.ArgumentParser",
"datetime.datetime.utcnow",
"os.path.join",
"oauth2client.client.flow_from_clientsecrets",
"os.environ.get",
"flask.request.form.get",
"slackclient.SlackClient",
"oauth2client.tools.run",
"oauth2client.file.Storage",
... | [((841, 869), 'slackclient.SlackClient', 'SlackClient', (['SLACK_DEV_TOKEN'], {}), '(SLACK_DEV_TOKEN)\n', (852, 869), False, 'from slackclient import SlackClient\n'), ((876, 891), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (881, 891), False, 'from flask import Flask, request, Response, jsonify\n'), ((1188, 1211), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (1206, 1211), False, 'import os\n'), ((1233, 1271), 'os.path.join', 'os.path.join', (['home_dir', '""".credentials"""'], {}), "(home_dir, '.credentials')\n", (1245, 1271), False, 'import os\n'), ((1373, 1436), 'os.path.join', 'os.path.join', (['credential_dir', '"""calendar-python-quickstart.json"""'], {}), "(credential_dir, 'calendar-python-quickstart.json')\n", (1385, 1436), False, 'import os\n'), ((1485, 1509), 'oauth2client.file.Storage', 'Storage', (['credential_path'], {}), '(credential_path)\n', (1492, 1509), False, 'from oauth2client.file import Storage\n'), ((2997, 3041), 'apiclient.discovery.build', 'discovery.build', (['"""calendar"""', '"""v3"""'], {'http': 'http'}), "('calendar', 'v3', http=http)\n", (3012, 3041), False, 'from apiclient import discovery\n'), ((1283, 1313), 'os.path.exists', 'os.path.exists', (['credential_dir'], {}), '(credential_dir)\n', (1297, 1313), False, 'import os\n'), ((1323, 1350), 'os.makedirs', 'os.makedirs', (['credential_dir'], {}), '(credential_dir)\n', (1334, 1350), False, 'import os\n'), ((1602, 1660), 'oauth2client.client.flow_from_clientsecrets', 'client.flow_from_clientsecrets', (['CLIENT_SECRET_FILE', 'SCOPES'], {}), '(CLIENT_SECRET_FILE, SCOPES)\n', (1632, 1660), False, 'from oauth2client import client\n'), ((2966, 2981), 'httplib2.Http', 'httplib2.Http', ([], {}), '()\n', (2979, 2981), False, 'import httplib2\n'), ((3908, 3933), 'flask.request.form.get', 'request.form.get', (['"""token"""'], {}), "('token')\n", (3924, 3933), False, 'from flask import Flask, request, Response, jsonify\n'), ((3979, 4009), 'flask.request.form.get', 'request.form.get', (['"""channel_id"""'], {}), "('channel_id')\n", (3995, 4009), False, 'from flask import Flask, request, Response, jsonify\n'), ((4582, 4610), 'os.environ.get', 'os.environ.get', (['"""PORT"""', '(5000)'], {}), "('PORT', 5000)\n", (4596, 4610), False, 'import os\n'), ((340, 390), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'parents': '[tools.argparser]'}), '(parents=[tools.argparser])\n', (363, 390), False, 'import argparse\n'), ((1748, 1782), 'oauth2client.tools.run_flow', 'tools.run_flow', (['flow', 'store', 'flags'], {}), '(flow, store, flags)\n', (1762, 1782), False, 'from oauth2client import tools\n'), ((1872, 1894), 'oauth2client.tools.run', 'tools.run', (['flow', 'store'], {}), '(flow, store)\n', (1881, 1894), False, 'from oauth2client import tools\n'), ((3052, 3078), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (3076, 3078), False, 'import datetime\n'), ((4029, 4053), 'flask.request.form.get', 'request.form.get', (['"""text"""'], {}), "('text')\n", (4045, 4053), False, 'from flask import Flask, request, Response, jsonify\n')] |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
__author__ = "<EMAIL>"
from test_auth_app.backend import test_auth_app_db
from test_auth_app.backend.db_models import User, Role, Application
from test_auth_app.backend.db_models import get_default_roles
from uuid import uuid1
def clear_database():
users = User.query.all()
for u in users:
test_auth_app_db.session.delete(u)
roles = Role.query.all()
for r in roles:
test_auth_app_db.session.delete(r)
apps = Application.query.all()
for a in apps:
test_auth_app_db.session.delete(a)
test_auth_app_db.session.commit()
def list_users():
users = User.query.all()
for u in users:
print('\n{}:\n\t{}\n\t{}\n{}\n{}\n{}\nvalid = {}'.format(u.id, u.email, u.user_uid, u.roles, u.applications, u.password_hash, u.validated))
def list_roles():
roles = Role.query.all()
for r in roles:
print('{}:\n\t{}\n\t{}\n'.format(r.id, r.role, r.description))
def list_applications():
apps = Application.query.all()
for a in apps:
print('{}:\n\t{}\n\t{}\n'.format(a.id, a.name, a.description))
def init_prod_database():
user_1 = User(email='<EMAIL>', user_uid=str(uuid1()))
role_read = Role(role='read', description='Can list, view and download cases related to a user')
role_read_all = Role(role='read_all', description='Can list, view and download all cases related to all user (as admin)')
role_edit = Role(role='edit', description='Can add new case, run case processing, clear processing results and case delete. Case is relevant to a particular user')
role_edit_all = Role(role='edit_all', description='Can run case processing, clear processing results and case delete. Case may be relevant to any user (as admin)')
app_lungs = Application(name='lungs', description='Lungs segmentation on CT images using CNNs')
app_lesions = Application(name='lesions', description='Lesions segmentation in lungs on CT images using CNNs')
# Default Anonymous user has access only to the example cases, to list them, preview and download.
# All apps are available
user_1.set_password('<PASSWORD>')
user_1.roles.append(role_read)
user_1.roles.append(role_edit)
user_1.set_validated(True)
user_1.applications.append(app_lungs)
user_1.applications.append(app_lesions)
test_auth_app_db.session.add(user_1)
test_auth_app_db.session.commit()
if __name__ == '__main__':
# clear_database()
# init_prod_database()
# list_users()
pass
| [
"test_auth_app.backend.test_auth_app_db.session.add",
"test_auth_app.backend.test_auth_app_db.session.commit",
"test_auth_app.backend.db_models.Application.query.all",
"test_auth_app.backend.db_models.Application",
"test_auth_app.backend.test_auth_app_db.session.delete",
"uuid.uuid1",
"test_auth_app.bac... | [((69, 131), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (90, 131), False, 'import warnings\n'), ((397, 413), 'test_auth_app.backend.db_models.User.query.all', 'User.query.all', ([], {}), '()\n', (411, 413), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((489, 505), 'test_auth_app.backend.db_models.Role.query.all', 'Role.query.all', ([], {}), '()\n', (503, 505), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((580, 603), 'test_auth_app.backend.db_models.Application.query.all', 'Application.query.all', ([], {}), '()\n', (601, 603), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((670, 703), 'test_auth_app.backend.test_auth_app_db.session.commit', 'test_auth_app_db.session.commit', ([], {}), '()\n', (701, 703), False, 'from test_auth_app.backend import test_auth_app_db\n'), ((736, 752), 'test_auth_app.backend.db_models.User.query.all', 'User.query.all', ([], {}), '()\n', (750, 752), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((953, 969), 'test_auth_app.backend.db_models.Role.query.all', 'Role.query.all', ([], {}), '()\n', (967, 969), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((1099, 1122), 'test_auth_app.backend.db_models.Application.query.all', 'Application.query.all', ([], {}), '()\n', (1120, 1122), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((1316, 1405), 'test_auth_app.backend.db_models.Role', 'Role', ([], {'role': '"""read"""', 'description': '"""Can list, view and download cases related to a user"""'}), "(role='read', description=\n 'Can list, view and download cases related to a user')\n", (1320, 1405), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((1421, 1531), 'test_auth_app.backend.db_models.Role', 'Role', ([], {'role': '"""read_all"""', 'description': '"""Can list, view and download all cases related to all user (as admin)"""'}), "(role='read_all', description=\n 'Can list, view and download all cases related to all user (as admin)')\n", (1425, 1531), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((1543, 1704), 'test_auth_app.backend.db_models.Role', 'Role', ([], {'role': '"""edit"""', 'description': '"""Can add new case, run case processing, clear processing results and case delete. Case is relevant to a particular user"""'}), "(role='edit', description=\n 'Can add new case, run case processing, clear processing results and case delete. Case is relevant to a particular user'\n )\n", (1547, 1704), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((1715, 1872), 'test_auth_app.backend.db_models.Role', 'Role', ([], {'role': '"""edit_all"""', 'description': '"""Can run case processing, clear processing results and case delete. Case may be relevant to any user (as admin)"""'}), "(role='edit_all', description=\n 'Can run case processing, clear processing results and case delete. Case may be relevant to any user (as admin)'\n )\n", (1719, 1872), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((1880, 1968), 'test_auth_app.backend.db_models.Application', 'Application', ([], {'name': '"""lungs"""', 'description': '"""Lungs segmentation on CT images using CNNs"""'}), "(name='lungs', description=\n 'Lungs segmentation on CT images using CNNs')\n", (1891, 1968), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((1982, 2083), 'test_auth_app.backend.db_models.Application', 'Application', ([], {'name': '"""lesions"""', 'description': '"""Lesions segmentation in lungs on CT images using CNNs"""'}), "(name='lesions', description=\n 'Lesions segmentation in lungs on CT images using CNNs')\n", (1993, 2083), False, 'from test_auth_app.backend.db_models import User, Role, Application\n'), ((2442, 2478), 'test_auth_app.backend.test_auth_app_db.session.add', 'test_auth_app_db.session.add', (['user_1'], {}), '(user_1)\n', (2470, 2478), False, 'from test_auth_app.backend import test_auth_app_db\n'), ((2483, 2516), 'test_auth_app.backend.test_auth_app_db.session.commit', 'test_auth_app_db.session.commit', ([], {}), '()\n', (2514, 2516), False, 'from test_auth_app.backend import test_auth_app_db\n'), ((442, 476), 'test_auth_app.backend.test_auth_app_db.session.delete', 'test_auth_app_db.session.delete', (['u'], {}), '(u)\n', (473, 476), False, 'from test_auth_app.backend import test_auth_app_db\n'), ((534, 568), 'test_auth_app.backend.test_auth_app_db.session.delete', 'test_auth_app_db.session.delete', (['r'], {}), '(r)\n', (565, 568), False, 'from test_auth_app.backend import test_auth_app_db\n'), ((631, 665), 'test_auth_app.backend.test_auth_app_db.session.delete', 'test_auth_app_db.session.delete', (['a'], {}), '(a)\n', (662, 665), False, 'from test_auth_app.backend import test_auth_app_db\n'), ((1289, 1296), 'uuid.uuid1', 'uuid1', ([], {}), '()\n', (1294, 1296), False, 'from uuid import uuid1\n')] |
import sys
from cos_backend import COSBackend
import json
import re
import pika
class ReduceCallback(object):
def __init__ (self, cb, target_bucket, nthreads):
self.cb = cb
self.target_bucket = target_bucket
self.nthreads = nthreads
self.result = {} # where we will be accumulating results
def __call__ (self, ch, method, properties, body):
file_tag = body.decode('utf-8') # decode file from queue message
target_segment = self.cb.get_object(self.target_bucket, file_tag) # fetch results chunk
chunk = json.loads(target_segment.decode('utf-8')) # parse results chunk
# merge dictionary with the whole result dictionary
for word in chunk:
if word in self.result:
self.result[word] += chunk[word]
else:
self.result[word] = chunk[word]
ch.basic_ack(delivery_tag=method.delivery_tag) # delete message from the queue
self.cb.delete_object(self.target_bucket, file_tag) # delete mapper result after merging
# decrease and check counter
self.nthreads -= 1
if not self.nthreads:
ch.stop_consuming()
def main(args):
# initialize cos wrapper
cb = COSBackend(args['cos']['service_endpoint'], args['cos']['secret_key'], args['cos']['access_key'])
# initialize queue system for the mappers' queue
pika_params = pika.URLParameters(args['rabbitamqp_url'])
connection = pika.BlockingConnection(pika_params)
channel = connection.channel()
channel.queue_declare(queue=args['mapper_qid'])
# check what we are reducing
if 'reduce_WordCount' in args and args['reduce_WordCount'] == 'yes':
callback = ReduceCallback(cb, args['target_bucket'], args['nthreads']) # create a callback
channel.basic_consume(callback, queue=args['mapper_qid']) # set a callback
channel.start_consuming()
cb.put_object(args['target_bucket'], '{}/WC-result'.format(args['target_fname']), json.dumps(callback.result)) # commit result
if 'reduce_CountingWords' in args and args['reduce_CountingWords'] == 'yes':
callback = ReduceCallback(cb, args['target_bucket'], args['nthreads'])
channel.basic_consume(callback, queue=args['mapper_qid'])
channel.start_consuming()
cb.put_object(args['target_bucket'], '{}/CW-result'.format(args['target_fname']), json.dumps(callback.result))
# tell the orchestrator job is done
channel.basic_publish(exchange='', routing_key=args['reducer_qid'], body='OK')
connection.close()
if __name__ == "__main__":
main(sys.argv[1]) | [
"json.dumps",
"pika.URLParameters",
"pika.BlockingConnection",
"cos_backend.COSBackend"
] | [((1370, 1472), 'cos_backend.COSBackend', 'COSBackend', (["args['cos']['service_endpoint']", "args['cos']['secret_key']", "args['cos']['access_key']"], {}), "(args['cos']['service_endpoint'], args['cos']['secret_key'], args\n ['cos']['access_key'])\n", (1380, 1472), False, 'from cos_backend import COSBackend\n'), ((1540, 1582), 'pika.URLParameters', 'pika.URLParameters', (["args['rabbitamqp_url']"], {}), "(args['rabbitamqp_url'])\n", (1558, 1582), False, 'import pika\n'), ((1600, 1636), 'pika.BlockingConnection', 'pika.BlockingConnection', (['pika_params'], {}), '(pika_params)\n', (1623, 1636), False, 'import pika\n'), ((2143, 2170), 'json.dumps', 'json.dumps', (['callback.result'], {}), '(callback.result)\n', (2153, 2170), False, 'import json\n'), ((2540, 2567), 'json.dumps', 'json.dumps', (['callback.result'], {}), '(callback.result)\n', (2550, 2567), False, 'import json\n')] |
from tensorflow import keras
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
model = keras.models.load_model("Saved models/2layerNet.h5")
x = np.load("data/preprocessedInputs.npy")
y = np.load("data/outputs.npy")
oosx = np.load("data/testx.npy")
oosy = np.load("data/testy.npy")
def evaluate(x, y):
c = 0
tp = 0
tn = 0
fp = 0
fn = 0
for pred in model.predict(x):
yHat = round(float(pred))
gtLabel = int(y[c])
if yHat == gtLabel and yHat == 1:
tp += 1
elif yHat == gtLabel and yHat == 0:
tn += 1
elif yHat == 1 and gtLabel == 0:
fp += 1
else:
fn += 1
c += 1
confMatrix = [[tp, fn], [fp, tn]]
sens = float(tp) / (tp + fn)
spec = float(tn) / (tn + fp)
perc = float(tp) / (tp + fp)
npv = float(tn) / (tn + fn)
acc = float((tp) + tn) / (fn+fp+tn+tp)
f1 = 2 * ((perc * sens) / (perc + sens))
return [[sens, spec, perc, npv, acc, f1], confMatrix]
print("------------Insample------------")
results = evaluate(x, y)
sens, spec, perc, npv, acc, f1 = results[0]
confMatrix = results[1]
print(f"Confusion matrix: {confMatrix}")
print(
f"sensitivity: {sens}\nspecificity: {spec}\nprecision: {perc}\nNegative Predictive Value: {npv}\nAccuracy: {acc}\nF1 Score: {f1}")
print("------------Out of Sample------------")
results2 = evaluate(oosx, oosy)
sens, spec, perc, npv, acc, f1 = results2[0]
confMatrix = results2[1]
print(f"Confusion matrix: {confMatrix}")
print(
f"sensitivity: {sens}\nspecificity: {spec}\nprecision: {perc}\nNegative Predictive Value: {npv}\nAccuracy: {acc}\nF1 Score: {f1}")
| [
"numpy.load",
"tensorflow.keras.models.load_model"
] | [((115, 167), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""Saved models/2layerNet.h5"""'], {}), "('Saved models/2layerNet.h5')\n", (138, 167), False, 'from tensorflow import keras\n'), ((173, 211), 'numpy.load', 'np.load', (['"""data/preprocessedInputs.npy"""'], {}), "('data/preprocessedInputs.npy')\n", (180, 211), True, 'import numpy as np\n'), ((217, 244), 'numpy.load', 'np.load', (['"""data/outputs.npy"""'], {}), "('data/outputs.npy')\n", (224, 244), True, 'import numpy as np\n'), ((255, 280), 'numpy.load', 'np.load', (['"""data/testx.npy"""'], {}), "('data/testx.npy')\n", (262, 280), True, 'import numpy as np\n'), ((289, 314), 'numpy.load', 'np.load', (['"""data/testy.npy"""'], {}), "('data/testy.npy')\n", (296, 314), True, 'import numpy as np\n')] |
import mock
import pytest
from iocage.cli.activate import\
(get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment)
@mock.patch('iocage.cli.activate.Popen.communicate')
def test_get_zfs_pools_multiple_pools(mock_communicate):
""" Fake the expected output from zpool list -H -o name
on a system with 3 ZFS pools
"""
mock_communicate.return_value = (b'tank0\ntank1\ntank2\n', None)
zpools = get_zfs_pools()
mock_communicate.assert_called()
assert zpools == ['tank0', 'tank1', 'tank2']
@mock.patch('iocage.cli.activate.Popen.communicate')
def test_get_zfs_pools_one_pool(mock_communicate):
""" Fake the expected output from zpool list -H -o name
on a system with 1 ZFS pool
"""
mock_communicate.return_value = (b'tank0\n', None)
zpools = get_zfs_pools()
mock_communicate.assert_called()
assert zpools == ['tank0']
@mock.patch('iocage.cli.activate.Popen.communicate')
def test_get_zfs_pools_no_pool(mock_communicate):
""" Fake the expected output from zpool list -H -o name
on a system with zero ZFS pool
"""
mock_communicate.return_value = (b'', None)
zpools = get_zfs_pools()
mock_communicate.assert_called()
assert zpools == []
@mock.patch('iocage.cli.activate.Popen.communicate')
def test_get_zfs_pools_bad_parameter(mock_communicate):
""" Fake zpool called with an incorrect parameter
(there is something in stderr), can save us when
updating the code
"""
mock_communicate.return_value = (b'',
b"""cannot open 'nope-parameter': no such pool\ncannot open '-o':
name must begin with a letter\ncannot open 'name': no such pool\n""")
with pytest.raises(RuntimeError):
zpools = get_zfs_pools()
mock_communicate.assert_called()
def test_set_zfs_pool_active_property_bad_param_zpool_name():
with pytest.raises(ValueError):
set_zfs_pool_active_property(None, True)
with pytest.raises(ValueError):
set_zfs_pool_active_property("", True)
with pytest.raises(ValueError):
set_zfs_pool_active_property(1, True)
with pytest.raises(ValueError):
set_zfs_pool_active_property([], True)
def test_set_zfs_pool_active_property_bad_param_activate():
with pytest.raises(ValueError):
set_zfs_pool_active_property("pool_name", None)
with pytest.raises(ValueError):
set_zfs_pool_active_property("pool_name", [])
with pytest.raises(ValueError):
set_zfs_pool_active_property("pool_name", 1)
@mock.patch('iocage.cli.activate.Popen.communicate')
def test_set_zfs_pool_active_property_ok(mock_communicate):
mock_communicate.return_value = (b'', b'')
set_zfs_pool_active_property("pool_name", True)
assert mock_communicate.called
@mock.patch('iocage.cli.activate.Popen.communicate')
def test_set_zfs_pool_active_property_fail(mock_communicate):
mock_communicate.return_value = (b'', b"cannot set property for 'tank0': invalid property 'foo'\n")
with pytest.raises(RuntimeError):
set_zfs_pool_active_property("pool_name", True)
with pytest.raises(RuntimeError):
set_zfs_pool_active_property("pool_name", False)
def test_set_zfs_pool_comment_bad_param ():
with pytest.raises(ValueError):
set_zfs_pool_comment(None, "comment")
with pytest.raises(ValueError):
set_zfs_pool_comment("", "comment")
with pytest.raises(ValueError):
set_zfs_pool_comment("pool", None)
with pytest.raises(ValueError):
set_zfs_pool_comment("pool", "")
@mock.patch('iocage.cli.activate.Popen.communicate')
def test_set_zfs_pool_comment_fail(mock_communicate):
mock_communicate.return_value = (b'', b"cannot set property for 'tank0': permission denied\n")
with pytest.raises(RuntimeError):
set_zfs_pool_comment("pool", "comment") | [
"mock.patch",
"iocage.cli.activate.get_zfs_pools",
"iocage.cli.activate.set_zfs_pool_comment",
"pytest.raises",
"iocage.cli.activate.set_zfs_pool_active_property"
] | [((134, 185), 'mock.patch', 'mock.patch', (['"""iocage.cli.activate.Popen.communicate"""'], {}), "('iocage.cli.activate.Popen.communicate')\n", (144, 185), False, 'import mock\n'), ((537, 588), 'mock.patch', 'mock.patch', (['"""iocage.cli.activate.Popen.communicate"""'], {}), "('iocage.cli.activate.Popen.communicate')\n", (547, 588), False, 'import mock\n'), ((902, 953), 'mock.patch', 'mock.patch', (['"""iocage.cli.activate.Popen.communicate"""'], {}), "('iocage.cli.activate.Popen.communicate')\n", (912, 953), False, 'import mock\n'), ((1255, 1306), 'mock.patch', 'mock.patch', (['"""iocage.cli.activate.Popen.communicate"""'], {}), "('iocage.cli.activate.Popen.communicate')\n", (1265, 1306), False, 'import mock\n'), ((2604, 2655), 'mock.patch', 'mock.patch', (['"""iocage.cli.activate.Popen.communicate"""'], {}), "('iocage.cli.activate.Popen.communicate')\n", (2614, 2655), False, 'import mock\n'), ((2853, 2904), 'mock.patch', 'mock.patch', (['"""iocage.cli.activate.Popen.communicate"""'], {}), "('iocage.cli.activate.Popen.communicate')\n", (2863, 2904), False, 'import mock\n'), ((3631, 3682), 'mock.patch', 'mock.patch', (['"""iocage.cli.activate.Popen.communicate"""'], {}), "('iocage.cli.activate.Popen.communicate')\n", (3641, 3682), False, 'import mock\n'), ((431, 446), 'iocage.cli.activate.get_zfs_pools', 'get_zfs_pools', ([], {}), '()\n', (444, 446), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((814, 829), 'iocage.cli.activate.get_zfs_pools', 'get_zfs_pools', ([], {}), '()\n', (827, 829), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((1174, 1189), 'iocage.cli.activate.get_zfs_pools', 'get_zfs_pools', ([], {}), '()\n', (1187, 1189), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((2767, 2814), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['"""pool_name"""', '(True)'], {}), "('pool_name', True)\n", (2795, 2814), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((1763, 1790), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (1776, 1790), False, 'import pytest\n'), ((1809, 1824), 'iocage.cli.activate.get_zfs_pools', 'get_zfs_pools', ([], {}), '()\n', (1822, 1824), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((1939, 1964), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1952, 1964), False, 'import pytest\n'), ((1974, 2014), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['None', '(True)'], {}), '(None, True)\n', (2002, 2014), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((2025, 2050), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2038, 2050), False, 'import pytest\n'), ((2060, 2098), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['""""""', '(True)'], {}), "('', True)\n", (2088, 2098), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((2109, 2134), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2122, 2134), False, 'import pytest\n'), ((2144, 2181), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['(1)', '(True)'], {}), '(1, True)\n', (2172, 2181), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((2192, 2217), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2205, 2217), False, 'import pytest\n'), ((2227, 2265), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['[]', '(True)'], {}), '([], True)\n', (2255, 2265), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((2337, 2362), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2350, 2362), False, 'import pytest\n'), ((2372, 2419), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['"""pool_name"""', 'None'], {}), "('pool_name', None)\n", (2400, 2419), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((2430, 2455), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2443, 2455), False, 'import pytest\n'), ((2465, 2510), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['"""pool_name"""', '[]'], {}), "('pool_name', [])\n", (2493, 2510), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((2521, 2546), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2534, 2546), False, 'import pytest\n'), ((2556, 2600), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['"""pool_name"""', '(1)'], {}), "('pool_name', 1)\n", (2584, 2600), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((3080, 3107), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (3093, 3107), False, 'import pytest\n'), ((3117, 3164), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['"""pool_name"""', '(True)'], {}), "('pool_name', True)\n", (3145, 3164), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((3175, 3202), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (3188, 3202), False, 'import pytest\n'), ((3212, 3260), 'iocage.cli.activate.set_zfs_pool_active_property', 'set_zfs_pool_active_property', (['"""pool_name"""', '(False)'], {}), "('pool_name', False)\n", (3240, 3260), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((3316, 3341), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3329, 3341), False, 'import pytest\n'), ((3351, 3388), 'iocage.cli.activate.set_zfs_pool_comment', 'set_zfs_pool_comment', (['None', '"""comment"""'], {}), "(None, 'comment')\n", (3371, 3388), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((3399, 3424), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3412, 3424), False, 'import pytest\n'), ((3434, 3469), 'iocage.cli.activate.set_zfs_pool_comment', 'set_zfs_pool_comment', (['""""""', '"""comment"""'], {}), "('', 'comment')\n", (3454, 3469), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((3480, 3505), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3493, 3505), False, 'import pytest\n'), ((3515, 3549), 'iocage.cli.activate.set_zfs_pool_comment', 'set_zfs_pool_comment', (['"""pool"""', 'None'], {}), "('pool', None)\n", (3535, 3549), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((3560, 3585), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3573, 3585), False, 'import pytest\n'), ((3595, 3627), 'iocage.cli.activate.set_zfs_pool_comment', 'set_zfs_pool_comment', (['"""pool"""', '""""""'], {}), "('pool', '')\n", (3615, 3627), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n'), ((3845, 3872), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (3858, 3872), False, 'import pytest\n'), ((3882, 3921), 'iocage.cli.activate.set_zfs_pool_comment', 'set_zfs_pool_comment', (['"""pool"""', '"""comment"""'], {}), "('pool', 'comment')\n", (3902, 3921), False, 'from iocage.cli.activate import get_zfs_pools, set_zfs_pool_active_property, set_zfs_pool_comment\n')] |
from treeNode import TreeNode
from collections import defaultdict
from treeNodeTravelThrewTreeNodes import TravelThrewTreeNodes
# In positionEncoding wird die Zugehörigkeit der Ecodierung zu ihrem Wert festgelegt.
# Dieser Wert entspricht der Position des Buchstabens der nächsten Zeile.
positionEncoding = defaultdict(list, {
'0': ['1000001', '1011111'],
'1': ['1000010', '1100000'],
'2': ['1000011', '1100001'],
'3': ['1000100', '1100010'],
'4': ['1000101', '1100011'],
'5': ['1000110', '1100100'],
'6': ['1000111', '1100101'],
'7': ['1001000', '1100110'],
'8': ['1001001', '1100111'],
'9': ['1001010', '1101000'],
'10': ['1001011', '1101001'],
'11': ['1001100', '1101010'],
'12': ['1001101', '1101011'],
'13': ['1001110', '1101100'],
'14': ['1001111', '1101101'],
'15': ['1010000', '1101110'],
'16': ['1010001', '1101111'],
'17': ['1010010', '1110000'],
'18': ['1010011', '1110001'],
'19': ['1010100', '1110010'],
'20': ['1010101', '1110011'],
'21': ['1010110', '1110100'],
'22': ['1010111', '1110101'],
'23': ['1011000', '1110110'],
'24': ['1011001', '1110111'],
'25': ['1011010', '1111000'],
'26': ['1011011', '1111001'],
'27': ['1011100', '1111010'],
'28': ['1011101', '1111011'],
'29': ['1011110', '1111100']
})
# Erstellung des Ursprungsobjektes des Baums
rootTreeNode = TreeNode()
# Hinzufügen aller Äste des Baums, um am Ende dieser die Position zu speichern.
for position, possibleEncodings in positionEncoding.items():
# Iteration über jede Kodierungsmöglichkeit
for encoding in possibleEncodings:
TravelThrewTreeNodes(rootTreeNode, encoding, position)
def GetRootTreeNode():
global rootTreeNode
return rootTreeNode
| [
"treeNode.TreeNode",
"treeNodeTravelThrewTreeNodes.TravelThrewTreeNodes",
"collections.defaultdict"
] | [((316, 1277), 'collections.defaultdict', 'defaultdict', (['list', "{'0': ['1000001', '1011111'], '1': ['1000010', '1100000'], '2': ['1000011',\n '1100001'], '3': ['1000100', '1100010'], '4': ['1000101', '1100011'],\n '5': ['1000110', '1100100'], '6': ['1000111', '1100101'], '7': [\n '1001000', '1100110'], '8': ['1001001', '1100111'], '9': ['1001010',\n '1101000'], '10': ['1001011', '1101001'], '11': ['1001100', '1101010'],\n '12': ['1001101', '1101011'], '13': ['1001110', '1101100'], '14': [\n '1001111', '1101101'], '15': ['1010000', '1101110'], '16': ['1010001',\n '1101111'], '17': ['1010010', '1110000'], '18': ['1010011', '1110001'],\n '19': ['1010100', '1110010'], '20': ['1010101', '1110011'], '21': [\n '1010110', '1110100'], '22': ['1010111', '1110101'], '23': ['1011000',\n '1110110'], '24': ['1011001', '1110111'], '25': ['1011010', '1111000'],\n '26': ['1011011', '1111001'], '27': ['1011100', '1111010'], '28': [\n '1011101', '1111011'], '29': ['1011110', '1111100']}"], {}), "(list, {'0': ['1000001', '1011111'], '1': ['1000010', '1100000'],\n '2': ['1000011', '1100001'], '3': ['1000100', '1100010'], '4': [\n '1000101', '1100011'], '5': ['1000110', '1100100'], '6': ['1000111',\n '1100101'], '7': ['1001000', '1100110'], '8': ['1001001', '1100111'],\n '9': ['1001010', '1101000'], '10': ['1001011', '1101001'], '11': [\n '1001100', '1101010'], '12': ['1001101', '1101011'], '13': ['1001110',\n '1101100'], '14': ['1001111', '1101101'], '15': ['1010000', '1101110'],\n '16': ['1010001', '1101111'], '17': ['1010010', '1110000'], '18': [\n '1010011', '1110001'], '19': ['1010100', '1110010'], '20': ['1010101',\n '1110011'], '21': ['1010110', '1110100'], '22': ['1010111', '1110101'],\n '23': ['1011000', '1110110'], '24': ['1011001', '1110111'], '25': [\n '1011010', '1111000'], '26': ['1011011', '1111001'], '27': ['1011100',\n '1111010'], '28': ['1011101', '1111011'], '29': ['1011110', '1111100']})\n", (327, 1277), False, 'from collections import defaultdict\n'), ((1445, 1455), 'treeNode.TreeNode', 'TreeNode', ([], {}), '()\n', (1453, 1455), False, 'from treeNode import TreeNode\n'), ((1701, 1755), 'treeNodeTravelThrewTreeNodes.TravelThrewTreeNodes', 'TravelThrewTreeNodes', (['rootTreeNode', 'encoding', 'position'], {}), '(rootTreeNode, encoding, position)\n', (1721, 1755), False, 'from treeNodeTravelThrewTreeNodes import TravelThrewTreeNodes\n')] |
from actor import Actor, Location, Passage, Switch, Ghost
from json import load
class Pool(dict):
""" Contains ingame objects. """
def fill(self):
with open('data/actors.json', 'r') as data:
actors = load(data)
for name, properties in actors.items():
self._build(properties, name)
with open('data/space.json', 'r') as data:
self.space = load(data)
def get_rooms(self):
return self.space
def _build(self, properties, name):
actor = Actor()
actor.load(properties)
if 'io' not in properties:
self[name] = actor
return
if 'labyrinth' in properties:
actor = Location(actor)
if 'labyrinth' in properties and 'right' in properties['labyrinth']:
actor = Passage(actor)
if 'access' in properties and 'used' in properties['access']:
actor = Switch(actor)
elif 'access' in properties:
actor = Ghost(actor)
self[name] = actor | [
"json.load",
"actor.Switch",
"actor.Location",
"actor.Passage",
"actor.Ghost",
"actor.Actor"
] | [((482, 489), 'actor.Actor', 'Actor', ([], {}), '()\n', (487, 489), False, 'from actor import Actor, Location, Passage, Switch, Ghost\n'), ((215, 225), 'json.load', 'load', (['data'], {}), '(data)\n', (219, 225), False, 'from json import load\n'), ((374, 384), 'json.load', 'load', (['data'], {}), '(data)\n', (378, 384), False, 'from json import load\n'), ((636, 651), 'actor.Location', 'Location', (['actor'], {}), '(actor)\n', (644, 651), False, 'from actor import Actor, Location, Passage, Switch, Ghost\n'), ((740, 754), 'actor.Passage', 'Passage', (['actor'], {}), '(actor)\n', (747, 754), False, 'from actor import Actor, Location, Passage, Switch, Ghost\n'), ((836, 849), 'actor.Switch', 'Switch', (['actor'], {}), '(actor)\n', (842, 849), False, 'from actor import Actor, Location, Passage, Switch, Ghost\n'), ((897, 909), 'actor.Ghost', 'Ghost', (['actor'], {}), '(actor)\n', (902, 909), False, 'from actor import Actor, Location, Passage, Switch, Ghost\n')] |
from api.models.config import Config
from api.tests.utils.test_objects import TestObjects
class TestConfigs(TestObjects):
MODEL = Config
POSTPAID_LIMIT: MODEL
POSTPAID_LIMIT_PATCHED: MODEL
@classmethod
def init(cls):
# These models are created in the initial Django signal, not from this data. These are just for easy handling.
cls.POSTPAID_LIMIT = cls.MODEL(id=10010, key='postpaid_limit', value='0.00')
cls.SAVED = [cls.POSTPAID_LIMIT]
cls.POSTPAID_LIMIT_PATCHED = cls.MODEL(id=10011, key='postpaid_limit', value='-10.00')
cls.UNSAVED = [cls.POSTPAID_LIMIT_PATCHED]
@classmethod
def create(cls):
TestConfigs.POSTPAID_LIMIT.id = Config.objects.get(key=TestConfigs.POSTPAID_LIMIT.key).id
| [
"api.models.config.Config.objects.get"
] | [((713, 767), 'api.models.config.Config.objects.get', 'Config.objects.get', ([], {'key': 'TestConfigs.POSTPAID_LIMIT.key'}), '(key=TestConfigs.POSTPAID_LIMIT.key)\n', (731, 767), False, 'from api.models.config import Config\n')] |
import numpy as np
import scipy as sp
from scipy.sparse.linalg import LinearOperator, lgmres, gmres
import tensornetwork as tn
import jax_vumps.numpy_backend.contractions as ct
# import jax_vumps.numpy_backend.mps_linalg as mps_linalg
def LH_linear_operator(A_L, lR):
"""
Return, as a LinearOperator, the LHS of the equation found by
summing the geometric series for
the left environment Hamiltonian.
"""
chi = A_L.shape[1]
Id = np.eye(chi, dtype=A_L.dtype)
def matvec(v):
v = v.reshape((chi, chi))
Th_v = ct.XopL(A_L, X=v)
vR = ct.proj(v, lR)*Id
v = v - Th_v + vR
v = v.flatten()
return v
op = LinearOperator((chi**2, chi**2), matvec=matvec, dtype=A_L.dtype)
return op
def call_solver(op, hI, params, x0, tol):
"""
Code used by both solve_for_RH and solve_for_LH to call the
sparse solver.
"""
if x0 is not None:
x0 = x0.flatten()
if params["solver"] == "gmres":
x, info = gmres(op,
hI.flatten(),
tol=tol,
restart=params["n_krylov"],
maxiter=params["max_restarts"],
x0=x0)
elif params["solver"] == "lgmres":
x, info = lgmres(op,
hI.flatten(),
tol=tol,
maxiter=params["maxiter"],
inner_m=params["inner_m"],
outer_k=params["outer_k"],
x0=x0)
new_hI = x.reshape(hI.shape)
return (new_hI, info)
def outermat(A, B):
chi = A.shape[0]
contract = [A, B]
idxs = [[-2, -1], [-3, -4]]
return tn.ncon(contract, idxs, backend="numpy").reshape((chi**2, chi**2))
def dense_LH_op(A_L, lR):
chi = A_L.shape[1]
eye = np.eye(chi, dtype=A_L.dtype)
term1 = outermat(eye, eye)
term2 = ct.tmdense(A_L).reshape((chi**2, chi**2))
term3 = outermat(eye, lR)
mat = term1-term2+term3
mat = mat.T
return mat
def prepare_for_LH_solve(A_L, H, lR):
hL_bare = ct.compute_hL(A_L, H)
hL_div = ct.proj(hL_bare, lR)*np.eye(hL_bare.shape[0])
hL = hL_bare - hL_div
return hL
def solve_for_LH(A_L, H, lR, params, delta, oldLH=None,
dense=False):
"""
Find the renormalized left environment Hamiltonian using a sparse
solver.
"""
hL = prepare_for_LH_solve(A_L, H, lR)
chi = hL.shape[0]
tol = params["tol_coef"]*delta
if dense:
mat = dense_LH_op(A_L, lR)
op = LH_linear_operator(A_L, lR)
LH = sp.linalg.solve(mat.T, hL.reshape((chi**2)))
LH = LH.reshape((chi, chi))
else:
op = LH_linear_operator(A_L, lR)
LH, info = call_solver(op, hL, params, oldLH, tol)
if info != 0:
print("Warning: Hleft solution failed with code: "+str(info))
return LH
def RH_linear_operator(A_R, rL):
chi = A_R.shape[1]
"""
Return, as a LinearOperator, the LHS of the equation found by
summing the geometric series for
the right environment Hamiltonian.
"""
Id = np.eye(chi, dtype=A_R.dtype)
def matvec(v):
v = v.reshape((chi, chi))
Th_v = ct.XopR(A_R, X=v)
Lv = ct.proj(rL, v)*Id
v = v - Th_v + Lv
v = v.flatten()
return v
op = LinearOperator((chi**2, chi**2), matvec=matvec, dtype=A_R.dtype)
return op
def solve_for_RH(A_R, H, rL, params, delta,
oldRH=None):
"""
Find the renormalized right environment Hamiltonian using a sparse
solver.
"""
hR_bare = ct.compute_hR(A_R, H)
hR_div = ct.proj(rL, hR_bare)*np.eye(hR_bare.shape[0])
hR = hR_bare - hR_div
op = RH_linear_operator(A_R, rL)
tol = params["tol_coef"]*delta
RH, info = call_solver(op, hR, params, oldRH, tol)
if info != 0:
print("Warning: RH solution failed with code: "+str(info))
# RHL = np.abs(ct.proj(rL, RH))
# if RHL > 1E-6:
# print("Warning: large <L|RH> = ", str(RHL))
return RH
| [
"scipy.sparse.linalg.LinearOperator",
"numpy.eye",
"jax_vumps.numpy_backend.contractions.proj",
"jax_vumps.numpy_backend.contractions.tmdense",
"tensornetwork.ncon",
"jax_vumps.numpy_backend.contractions.compute_hR",
"jax_vumps.numpy_backend.contractions.XopR",
"jax_vumps.numpy_backend.contractions.co... | [((462, 490), 'numpy.eye', 'np.eye', (['chi'], {'dtype': 'A_L.dtype'}), '(chi, dtype=A_L.dtype)\n', (468, 490), True, 'import numpy as np\n'), ((686, 754), 'scipy.sparse.linalg.LinearOperator', 'LinearOperator', (['(chi ** 2, chi ** 2)'], {'matvec': 'matvec', 'dtype': 'A_L.dtype'}), '((chi ** 2, chi ** 2), matvec=matvec, dtype=A_L.dtype)\n', (700, 754), False, 'from scipy.sparse.linalg import LinearOperator, lgmres, gmres\n'), ((1855, 1883), 'numpy.eye', 'np.eye', (['chi'], {'dtype': 'A_L.dtype'}), '(chi, dtype=A_L.dtype)\n', (1861, 1883), True, 'import numpy as np\n'), ((2112, 2133), 'jax_vumps.numpy_backend.contractions.compute_hL', 'ct.compute_hL', (['A_L', 'H'], {}), '(A_L, H)\n', (2125, 2133), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((3151, 3179), 'numpy.eye', 'np.eye', (['chi'], {'dtype': 'A_R.dtype'}), '(chi, dtype=A_R.dtype)\n', (3157, 3179), True, 'import numpy as np\n'), ((3374, 3442), 'scipy.sparse.linalg.LinearOperator', 'LinearOperator', (['(chi ** 2, chi ** 2)'], {'matvec': 'matvec', 'dtype': 'A_R.dtype'}), '((chi ** 2, chi ** 2), matvec=matvec, dtype=A_R.dtype)\n', (3388, 3442), False, 'from scipy.sparse.linalg import LinearOperator, lgmres, gmres\n'), ((3642, 3663), 'jax_vumps.numpy_backend.contractions.compute_hR', 'ct.compute_hR', (['A_R', 'H'], {}), '(A_R, H)\n', (3655, 3663), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((560, 577), 'jax_vumps.numpy_backend.contractions.XopL', 'ct.XopL', (['A_L'], {'X': 'v'}), '(A_L, X=v)\n', (567, 577), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((2147, 2167), 'jax_vumps.numpy_backend.contractions.proj', 'ct.proj', (['hL_bare', 'lR'], {}), '(hL_bare, lR)\n', (2154, 2167), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((2168, 2192), 'numpy.eye', 'np.eye', (['hL_bare.shape[0]'], {}), '(hL_bare.shape[0])\n', (2174, 2192), True, 'import numpy as np\n'), ((3249, 3266), 'jax_vumps.numpy_backend.contractions.XopR', 'ct.XopR', (['A_R'], {'X': 'v'}), '(A_R, X=v)\n', (3256, 3266), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((3677, 3697), 'jax_vumps.numpy_backend.contractions.proj', 'ct.proj', (['rL', 'hR_bare'], {}), '(rL, hR_bare)\n', (3684, 3697), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((3698, 3722), 'numpy.eye', 'np.eye', (['hR_bare.shape[0]'], {}), '(hR_bare.shape[0])\n', (3704, 3722), True, 'import numpy as np\n'), ((591, 605), 'jax_vumps.numpy_backend.contractions.proj', 'ct.proj', (['v', 'lR'], {}), '(v, lR)\n', (598, 605), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((1727, 1767), 'tensornetwork.ncon', 'tn.ncon', (['contract', 'idxs'], {'backend': '"""numpy"""'}), "(contract, idxs, backend='numpy')\n", (1734, 1767), True, 'import tensornetwork as tn\n'), ((1927, 1942), 'jax_vumps.numpy_backend.contractions.tmdense', 'ct.tmdense', (['A_L'], {}), '(A_L)\n', (1937, 1942), True, 'import jax_vumps.numpy_backend.contractions as ct\n'), ((3280, 3294), 'jax_vumps.numpy_backend.contractions.proj', 'ct.proj', (['rL', 'v'], {}), '(rL, v)\n', (3287, 3294), True, 'import jax_vumps.numpy_backend.contractions as ct\n')] |
# -*- coding: utf-8 -*-
"""
File Name: utils
Description :
Author : mick.yi
date: 2019/1/4
"""
import numpy as np
def enqueue(np_array, elem):
"""
入队列,新增元素放到队首,队尾元素丢弃
:param np_array: 原始队列
:param elem: 增加元素
:return:
"""
np_array[1:] = np_array[:-1]
np_array[0] = elem
return np_array
def random_select(ids):
"""
随机选择一个id
:param ids: id列表,(N,)
:return:
"""
idx = np.random.choice(len(ids))
return ids[idx]
# def to_train_label(train_label):
def update_weights(h5_file, h5_dataset, weights, labels):
"""
更新保存在hdf5中的原型权重
:param h5_file: 原型权重的hdf5文件
:param h5_dataset: 原型权重在hdf5中的dataset
:param weights: 待更新的权重,numpy数组 (Batch,Dim)
:param labels: 待更新的权重对应的类别标签
:return:
备注:TypeError: Indexing elements must be in increasing order; idx要排序
TypeError: PointSelection __getitem__ only works with bool arrays; labels[idx]改为list(labels[idx])
"""
# for idx, label in enumerate(labels):
# h5_dataset[label] = weights[idx]
idx = np.argsort(labels)
h5_dataset[list(labels[idx])] = weights[idx]
h5_file.flush()
def get_weights(h5_dataset, labels):
weights = [h5_dataset[label] for label in labels]
return np.asarray(weights)
def update_queue(dominant_queue, candidate_queue, predict, current_labels):
"""
更新支配队列
:param dominant_queue: 支配队列
:param candidate_queue: 候选队列
:param predict: 预测的类别,numpy数组 (Batch,train_num_class)
:param current_labels: 实际的当前类别(Batch,)
:return:
"""
predict_label = np.argmax(predict, axis=-1)
for i in range(len(predict_label)):
d_label_queue = dominant_queue[current_labels[i]]
c_label_queue = candidate_queue[current_labels[i]]
real_predict_label = current_labels[predict_label[i]]
# 预测结果不是正确标签,不在正确标签的支配队列中,但在正确标签的候选队列中
# 更新支配队列
if predict_label[i] != i and \
real_predict_label not in d_label_queue and \
real_predict_label in c_label_queue:
dominant_queue[current_labels[i]] = enqueue(d_label_queue, real_predict_label)
| [
"numpy.argsort",
"numpy.asarray",
"numpy.argmax"
] | [((1123, 1141), 'numpy.argsort', 'np.argsort', (['labels'], {}), '(labels)\n', (1133, 1141), True, 'import numpy as np\n'), ((1322, 1341), 'numpy.asarray', 'np.asarray', (['weights'], {}), '(weights)\n', (1332, 1341), True, 'import numpy as np\n'), ((1658, 1685), 'numpy.argmax', 'np.argmax', (['predict'], {'axis': '(-1)'}), '(predict, axis=-1)\n', (1667, 1685), True, 'import numpy as np\n')] |
import random
import pandas as pd
import pronouncing
from collections import defaultdict
import re
import pkg_resources
def load_data():
stream = pkg_resources.resource_stream(__name__, 'data.pkl.compress')
return pd.read_pickle(stream, compression="gzip")
def define_structure():
length = random.randint(4, 10)
line_breaks = random.randint(1, length-1)
# define rhyming structure
rhyme_scheme = random.choice(["ABAB", "AABB", "random"])
return length, line_breaks, rhyme_scheme
def get_last_word(line):
match = re.search(r'(\b\w+\b)\W*$', line)
if match:
last_word = match.group()
last_word = re.sub(r'[^\w\s]', '', last_word)
return last_word
def pick_first_line(df):
last_word = ""
while last_word == "":
index = random.randint(1, len(df))
first_line = df.text[index]
last_word = get_last_word(first_line)
return (index, df.text[index], last_word)
def thinking_messages():
messages = ['I\'m thinking...', 'Eureka! I have the line now.', "Bother me not, darling, I am composing.",
"I'm almost there... I'm getting there...", "Pass me the opium, I need to concentrate.",
"What is the difference between metonymy and synecdoche again, darling?", "AHA!", "Egad!", "Alas!",
"Where is my favorite quill?", "I shall soon tire of this labor and go to fight a war in Greece.",
"I may go on a stroll among the daffodils later to clear my head.", "Poetry is a nasty business.",
"Why yes, I AM *the* Lord Frankenbot. Pleased to meet your acquaintance indeed.",
"I am utterly baffled by this line!", "Where shall I place this break, this pause.",
"Dear me! The emotions are getting out of hand.", "I must climb to a grassy windy hill and rumninate",
"Perhaps one day I, too, will be buried at Westminster.", "Give me time. I strive towards God, you cretin.",
"Just a moment, now. A few more moments.", "Hmm...", "Wonderful, just a few moments more.",
"Whoever said composing such Godly lines would be easy?", "I am a Poet. And Poetry takes time."]
choice = random.choice(messages)
return choice
def get_rhyme_dict(pruned_df):
# this data structure is ripped almost exactly from https://github.com/aparrish/pronouncingpy
by_rhyming_part = defaultdict(lambda: defaultdict(list))
for i, line in enumerate(pruned_df.text):
if (i%500000 == 0):
print(thinking_messages())
match = re.search(r'(\b\w+\b)\W*$', line)
if match:
last_word = match.group()
pronunciations = pronouncing.phones_for_word(last_word)
if len(pronunciations) > 0:
rhyming_part = pronouncing.rhyming_part(pronunciations[0])
# group by rhyming phones (for rhymes) and words (to avoid duplicate words)
by_rhyming_part[rhyming_part][last_word.lower()].append(line)
return by_rhyming_part
def print_poem(poem):
for i in range(len(poem)):
print(i)
def write_poem():
df = load_data()
print("Here I go! \n")
length, line_breaks, rhyme_scheme = define_structure()
# pick the first line and get the last word of that first line
index, first_line, last_word = pick_first_line(df)
# prune the dataframe so that we restrict the number of syllables and the meter
pruned_df = df[df.meter == df.meter[index]]
pruned_df = df[(df.syllables > df.syllables[index]-3) & (df.syllables < df.syllables[index]+2)]
# get the rhyme_dict for the pruned df so we can rhyme lines
rhyme_dict = get_rhyme_dict(pruned_df)
# Frankenbot's done
print("\n VOILA!! \n")
print("*********************************************************")
print("\n")
# print the first line
print(first_line)
# set break variable False so we don't line break before the first line
break_here = False
# now make the rest of the poem
line = first_line
while(length > 0):
if break_here and line_breaks > 0:
print("\n")
line_breaks -= 1
break_here = False
# the random number will determine what we do...
x = random.randint(1, 6)
y = random.randint(1, 6)
magic_number = x + y
# line break on the next line
if (magic_number < 6):
break_here = True
# if the rhyme scheme is random, print a rhyming line by getting the rhyming part of the last word,
# then choosing a random rhyming line from the rhyme_dict
# if we roll greater than or equal to 7 all hell breaks loose - no more rhyming
if (magic_number >= 8 and rhyme_scheme == "random"):
line = random.choice(list(pruned_df.text))
print(line)
length -= 1
continue
if (rhyme_scheme == "random"):
last_word = get_last_word(line)
try:
p = pronouncing.phones_for_word(last_word)
rp = pronouncing.rhyming_part(p[0])
random_key = random.choice(list(rhyme_dict[rp].keys()))
new_line = random.choice(rhyme_dict[rp][random_key])
except:
new_line = random.choice(list(pruned_df.text))
print(line)
line = new_line
length -= 1
if (rhyme_scheme == "AABB"):
last_word = get_last_word(line)
# get line which rhymes with last line
try:
p = pronouncing.phones_for_word(last_word)
rp = pronouncing.rhyming_part(p[0])
random_key = random.choice(list(rhyme_dict[rp].keys()))
new_line = random.choice(rhyme_dict[rp][random_key])
except:
new_line = random.choice(list(pruned_df.text))
print(new_line)
# new couplet starting
new_line = random.choice(list(pruned_df.text))
print(new_line)
line = new_line
length -= 2
if (rhyme_scheme == "ABAB"):
word_a = get_last_word(line)
try:
p = pronouncing.phones_for_word(word_a)
rp = pronouncing.rhyming_part(p[0])
random_key = random.choice(list(rhyme_dict[rp].keys()))
new_line_a = random.choice(rhyme_dict[rp][random_key])
except:
new_line_a = random.choice(list(pruned_df.text))
line_b = random.choice(list(pruned_df.text))
word_b = get_last_word(line_b)
try:
p = pronouncing.phones_for_word(word_b)
rp = pronouncing.rhyming_part(p[0])
random_key = random.choice(list(rhyme_dict[rp].keys()))
new_line_b = random.choice(rhyme_dict[rp][random_key])
except:
new_line_b = random.choice(list(pruned_df.text))
print(line_b)
print(new_line_a)
print(new_line_b)
line = random.choice(list(pruned_df.text))
length -= 3
print("\n") | [
"pandas.read_pickle",
"random.choice",
"pronouncing.rhyming_part",
"collections.defaultdict",
"re.sub",
"pronouncing.phones_for_word",
"random.randint",
"pkg_resources.resource_stream",
"re.search"
] | [((151, 211), 'pkg_resources.resource_stream', 'pkg_resources.resource_stream', (['__name__', '"""data.pkl.compress"""'], {}), "(__name__, 'data.pkl.compress')\n", (180, 211), False, 'import pkg_resources\n'), ((223, 265), 'pandas.read_pickle', 'pd.read_pickle', (['stream'], {'compression': '"""gzip"""'}), "(stream, compression='gzip')\n", (237, 265), True, 'import pandas as pd\n'), ((304, 325), 'random.randint', 'random.randint', (['(4)', '(10)'], {}), '(4, 10)\n', (318, 325), False, 'import random\n'), ((344, 373), 'random.randint', 'random.randint', (['(1)', '(length - 1)'], {}), '(1, length - 1)\n', (358, 373), False, 'import random\n'), ((427, 468), 'random.choice', 'random.choice', (["['ABAB', 'AABB', 'random']"], {}), "(['ABAB', 'AABB', 'random'])\n", (440, 468), False, 'import random\n'), ((557, 593), 're.search', 're.search', (['"""(\\\\b\\\\w+\\\\b)\\\\W*$"""', 'line'], {}), "('(\\\\b\\\\w+\\\\b)\\\\W*$', line)\n", (566, 593), False, 'import re\n'), ((655, 689), 're.sub', 're.sub', (['"""[^\\\\w\\\\s]"""', '""""""', 'last_word'], {}), "('[^\\\\w\\\\s]', '', last_word)\n", (661, 689), False, 'import re\n'), ((2210, 2233), 'random.choice', 'random.choice', (['messages'], {}), '(messages)\n', (2223, 2233), False, 'import random\n'), ((2577, 2613), 're.search', 're.search', (['"""(\\\\b\\\\w+\\\\b)\\\\W*$"""', 'line'], {}), "('(\\\\b\\\\w+\\\\b)\\\\W*$', line)\n", (2586, 2613), False, 'import re\n'), ((4347, 4367), 'random.randint', 'random.randint', (['(1)', '(6)'], {}), '(1, 6)\n', (4361, 4367), False, 'import random\n'), ((4380, 4400), 'random.randint', 'random.randint', (['(1)', '(6)'], {}), '(1, 6)\n', (4394, 4400), False, 'import random\n'), ((2429, 2446), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2440, 2446), False, 'from collections import defaultdict\n'), ((2696, 2734), 'pronouncing.phones_for_word', 'pronouncing.phones_for_word', (['last_word'], {}), '(last_word)\n', (2723, 2734), False, 'import pronouncing\n'), ((2806, 2849), 'pronouncing.rhyming_part', 'pronouncing.rhyming_part', (['pronunciations[0]'], {}), '(pronunciations[0])\n', (2830, 2849), False, 'import pronouncing\n'), ((5143, 5181), 'pronouncing.phones_for_word', 'pronouncing.phones_for_word', (['last_word'], {}), '(last_word)\n', (5170, 5181), False, 'import pronouncing\n'), ((5203, 5233), 'pronouncing.rhyming_part', 'pronouncing.rhyming_part', (['p[0]'], {}), '(p[0])\n', (5227, 5233), False, 'import pronouncing\n'), ((5333, 5374), 'random.choice', 'random.choice', (['rhyme_dict[rp][random_key]'], {}), '(rhyme_dict[rp][random_key])\n', (5346, 5374), False, 'import random\n'), ((5725, 5763), 'pronouncing.phones_for_word', 'pronouncing.phones_for_word', (['last_word'], {}), '(last_word)\n', (5752, 5763), False, 'import pronouncing\n'), ((5785, 5815), 'pronouncing.rhyming_part', 'pronouncing.rhyming_part', (['p[0]'], {}), '(p[0])\n', (5809, 5815), False, 'import pronouncing\n'), ((5915, 5956), 'random.choice', 'random.choice', (['rhyme_dict[rp][random_key]'], {}), '(rhyme_dict[rp][random_key])\n', (5928, 5956), False, 'import random\n'), ((6389, 6424), 'pronouncing.phones_for_word', 'pronouncing.phones_for_word', (['word_a'], {}), '(word_a)\n', (6416, 6424), False, 'import pronouncing\n'), ((6446, 6476), 'pronouncing.rhyming_part', 'pronouncing.rhyming_part', (['p[0]'], {}), '(p[0])\n', (6470, 6476), False, 'import pronouncing\n'), ((6578, 6619), 'random.choice', 'random.choice', (['rhyme_dict[rp][random_key]'], {}), '(rhyme_dict[rp][random_key])\n', (6591, 6619), False, 'import random\n'), ((6855, 6890), 'pronouncing.phones_for_word', 'pronouncing.phones_for_word', (['word_b'], {}), '(word_b)\n', (6882, 6890), False, 'import pronouncing\n'), ((6912, 6942), 'pronouncing.rhyming_part', 'pronouncing.rhyming_part', (['p[0]'], {}), '(p[0])\n', (6936, 6942), False, 'import pronouncing\n'), ((7044, 7085), 'random.choice', 'random.choice', (['rhyme_dict[rp][random_key]'], {}), '(rhyme_dict[rp][random_key])\n', (7057, 7085), False, 'import random\n')] |
# pylint: disable=line-too-long
from django.conf.urls import url
from django.contrib.auth.views import LogoutView
from django.conf import settings
from .views import pdk_add_data_point, pdk_add_data_bundle, pdk_app_config, pdk_issues, \
pdk_issues_json, pdk_fetch_metadata_json
urlpatterns = [
url(r'^add-point.json$', pdk_add_data_point, name='pdk_add_data_point'),
url(r'^add-bundle.json$', pdk_add_data_bundle, name='pdk_add_data_bundle'),
url(r'^app-config.json$', pdk_app_config, name='pdk_app_config'),
]
try:
from .withings_views import pdk_withings_start, pdk_withings_auth
if settings.PDK_WITHINGS_CLIENT_ID and settings.PDK_WITHINGS_SECRET:
urlpatterns.append(url(r'^withings/start/(?P<source_id>.+)$', pdk_withings_start, name='pdk_withings_start'))
urlpatterns.append(url(r'^withings/auth$', pdk_withings_auth, name='pdk_withings_auth'))
except AttributeError:
pass
try:
if settings.PDK_DASHBOARD_ENABLED:
from .views import pdk_home, pdk_unmatched_sources, pdk_source, pdk_source_generator, \
pdk_visualization_data, pdk_export, pdk_download_report, \
pdk_system_health, pdk_profile
urlpatterns.append(url(r'^visualization/(?P<source_id>.+)/(?P<generator_id>.+)/(?P<page>\d+).json$', \
pdk_visualization_data, name='pdk_visualization_data'))
urlpatterns.append(url(r'^report/(?P<report_id>\d+)/download$', pdk_download_report, name='pdk_download_report'))
urlpatterns.append(url(r'^source/(?P<source_id>.+)/(?P<generator_id>.+)$', pdk_source_generator, name='pdk_source_generator'))
urlpatterns.append(url(r'^source/(?P<source_id>.+)$', pdk_source, name='pdk_source'))
urlpatterns.append(url(r'^export$', pdk_export, name='pdk_export'))
urlpatterns.append(url(r'^system-health$', pdk_system_health, name='pdk_system_health'))
urlpatterns.append(url(r'^profile$', pdk_profile, name='pdk_profile'))
urlpatterns.append(url(r'^fetch-metadata.json$', pdk_fetch_metadata_json, name='pdk_fetch_metadata_json'))
urlpatterns.append(url(r'^issues.json$', pdk_issues_json, name='pdk_issues_json'))
urlpatterns.append(url(r'^issues$', pdk_issues, name='pdk_issues'))
urlpatterns.append(url(r'^unmatched-sources.json$', pdk_unmatched_sources, name='pdk_unmatched_sources'))
urlpatterns.append(url(r'^logout$', LogoutView.as_view(), name='pdk_logout'))
urlpatterns.append(url(r'^$', pdk_home, name='pdk_home'))
except AttributeError:
pass
try:
if settings.PDK_API_ENABLED:
from .api_views import pdk_request_token, pdk_data_point_query, pdk_data_source_query
urlpatterns.append(url(r'^api/request-token.json$', pdk_request_token, name='pdk_request_token'))
urlpatterns.append(url(r'^api/data-points.json$', pdk_data_point_query, name='pdk_data_point_query'))
urlpatterns.append(url(r'^api/data-sources.json$', pdk_data_source_query, name='pdk_data_source_query'))
except AttributeError:
pass
| [
"django.conf.urls.url",
"django.contrib.auth.views.LogoutView.as_view"
] | [((320, 390), 'django.conf.urls.url', 'url', (['"""^add-point.json$"""', 'pdk_add_data_point'], {'name': '"""pdk_add_data_point"""'}), "('^add-point.json$', pdk_add_data_point, name='pdk_add_data_point')\n", (323, 390), False, 'from django.conf.urls import url\n'), ((397, 470), 'django.conf.urls.url', 'url', (['"""^add-bundle.json$"""', 'pdk_add_data_bundle'], {'name': '"""pdk_add_data_bundle"""'}), "('^add-bundle.json$', pdk_add_data_bundle, name='pdk_add_data_bundle')\n", (400, 470), False, 'from django.conf.urls import url\n'), ((477, 540), 'django.conf.urls.url', 'url', (['"""^app-config.json$"""', 'pdk_app_config'], {'name': '"""pdk_app_config"""'}), "('^app-config.json$', pdk_app_config, name='pdk_app_config')\n", (480, 540), False, 'from django.conf.urls import url\n'), ((722, 815), 'django.conf.urls.url', 'url', (['"""^withings/start/(?P<source_id>.+)$"""', 'pdk_withings_start'], {'name': '"""pdk_withings_start"""'}), "('^withings/start/(?P<source_id>.+)$', pdk_withings_start, name=\n 'pdk_withings_start')\n", (725, 815), False, 'from django.conf.urls import url\n'), ((840, 907), 'django.conf.urls.url', 'url', (['"""^withings/auth$"""', 'pdk_withings_auth'], {'name': '"""pdk_withings_auth"""'}), "('^withings/auth$', pdk_withings_auth, name='pdk_withings_auth')\n", (843, 907), False, 'from django.conf.urls import url\n'), ((1255, 1396), 'django.conf.urls.url', 'url', (['"""^visualization/(?P<source_id>.+)/(?P<generator_id>.+)/(?P<page>\\\\d+).json$"""', 'pdk_visualization_data'], {'name': '"""pdk_visualization_data"""'}), "('^visualization/(?P<source_id>.+)/(?P<generator_id>.+)/(?P<page>\\\\d+).json$'\n , pdk_visualization_data, name='pdk_visualization_data')\n", (1258, 1396), False, 'from django.conf.urls import url\n'), ((1453, 1551), 'django.conf.urls.url', 'url', (['"""^report/(?P<report_id>\\\\d+)/download$"""', 'pdk_download_report'], {'name': '"""pdk_download_report"""'}), "('^report/(?P<report_id>\\\\d+)/download$', pdk_download_report, name=\n 'pdk_download_report')\n", (1456, 1551), False, 'from django.conf.urls import url\n'), ((1575, 1684), 'django.conf.urls.url', 'url', (['"""^source/(?P<source_id>.+)/(?P<generator_id>.+)$"""', 'pdk_source_generator'], {'name': '"""pdk_source_generator"""'}), "('^source/(?P<source_id>.+)/(?P<generator_id>.+)$', pdk_source_generator,\n name='pdk_source_generator')\n", (1578, 1684), False, 'from django.conf.urls import url\n'), ((1710, 1774), 'django.conf.urls.url', 'url', (['"""^source/(?P<source_id>.+)$"""', 'pdk_source'], {'name': '"""pdk_source"""'}), "('^source/(?P<source_id>.+)$', pdk_source, name='pdk_source')\n", (1713, 1774), False, 'from django.conf.urls import url\n'), ((1804, 1850), 'django.conf.urls.url', 'url', (['"""^export$"""', 'pdk_export'], {'name': '"""pdk_export"""'}), "('^export$', pdk_export, name='pdk_export')\n", (1807, 1850), False, 'from django.conf.urls import url\n'), ((1880, 1947), 'django.conf.urls.url', 'url', (['"""^system-health$"""', 'pdk_system_health'], {'name': '"""pdk_system_health"""'}), "('^system-health$', pdk_system_health, name='pdk_system_health')\n", (1883, 1947), False, 'from django.conf.urls import url\n'), ((1977, 2026), 'django.conf.urls.url', 'url', (['"""^profile$"""', 'pdk_profile'], {'name': '"""pdk_profile"""'}), "('^profile$', pdk_profile, name='pdk_profile')\n", (1980, 2026), False, 'from django.conf.urls import url\n'), ((2056, 2146), 'django.conf.urls.url', 'url', (['"""^fetch-metadata.json$"""', 'pdk_fetch_metadata_json'], {'name': '"""pdk_fetch_metadata_json"""'}), "('^fetch-metadata.json$', pdk_fetch_metadata_json, name=\n 'pdk_fetch_metadata_json')\n", (2059, 2146), False, 'from django.conf.urls import url\n'), ((2171, 2232), 'django.conf.urls.url', 'url', (['"""^issues.json$"""', 'pdk_issues_json'], {'name': '"""pdk_issues_json"""'}), "('^issues.json$', pdk_issues_json, name='pdk_issues_json')\n", (2174, 2232), False, 'from django.conf.urls import url\n'), ((2262, 2308), 'django.conf.urls.url', 'url', (['"""^issues$"""', 'pdk_issues'], {'name': '"""pdk_issues"""'}), "('^issues$', pdk_issues, name='pdk_issues')\n", (2265, 2308), False, 'from django.conf.urls import url\n'), ((2338, 2427), 'django.conf.urls.url', 'url', (['"""^unmatched-sources.json$"""', 'pdk_unmatched_sources'], {'name': '"""pdk_unmatched_sources"""'}), "('^unmatched-sources.json$', pdk_unmatched_sources, name=\n 'pdk_unmatched_sources')\n", (2341, 2427), False, 'from django.conf.urls import url\n'), ((2538, 2574), 'django.conf.urls.url', 'url', (['"""^$"""', 'pdk_home'], {'name': '"""pdk_home"""'}), "('^$', pdk_home, name='pdk_home')\n", (2541, 2574), False, 'from django.conf.urls import url\n'), ((2769, 2845), 'django.conf.urls.url', 'url', (['"""^api/request-token.json$"""', 'pdk_request_token'], {'name': '"""pdk_request_token"""'}), "('^api/request-token.json$', pdk_request_token, name='pdk_request_token')\n", (2772, 2845), False, 'from django.conf.urls import url\n'), ((2875, 2960), 'django.conf.urls.url', 'url', (['"""^api/data-points.json$"""', 'pdk_data_point_query'], {'name': '"""pdk_data_point_query"""'}), "('^api/data-points.json$', pdk_data_point_query, name='pdk_data_point_query'\n )\n", (2878, 2960), False, 'from django.conf.urls import url\n'), ((2985, 3073), 'django.conf.urls.url', 'url', (['"""^api/data-sources.json$"""', 'pdk_data_source_query'], {'name': '"""pdk_data_source_query"""'}), "('^api/data-sources.json$', pdk_data_source_query, name=\n 'pdk_data_source_query')\n", (2988, 3073), False, 'from django.conf.urls import url\n'), ((2469, 2489), 'django.contrib.auth.views.LogoutView.as_view', 'LogoutView.as_view', ([], {}), '()\n', (2487, 2489), False, 'from django.contrib.auth.views import LogoutView\n')] |
import unittest
from nose.tools import *
from footy.test_data.test_data_paths import premier_league_2015_2016_path
from footy.src.clubs.club_gateway import ClubGateway
class ClubGatewayTest(unittest.TestCase):
def setUp(self):
self.gateway = ClubGateway(premier_league_2015_2016_path)
def test_get_all_clubs(self):
clubs = self.gateway.get_all()
self.assertEquals(20, len(clubs))
def test_get_all_clubs_includes_club_name(self):
clubs = self.gateway.get_all()
self.assertEquals("Arsenal", clubs[0].name)
self.assertEquals("<NAME>", clubs[1].name)
self.assertEquals("Bournemouth", clubs[2].name)
| [
"footy.src.clubs.club_gateway.ClubGateway"
] | [((257, 299), 'footy.src.clubs.club_gateway.ClubGateway', 'ClubGateway', (['premier_league_2015_2016_path'], {}), '(premier_league_2015_2016_path)\n', (268, 299), False, 'from footy.src.clubs.club_gateway import ClubGateway\n')] |
"""
Module with reading functionalities of color and magnitude data from photometric and
spectral libraries.
"""
import os
import configparser
from typing import Optional, Tuple
import h5py
import numpy as np
from typeguard import typechecked
from species.core import box
from species.read import read_spectrum
from species.util import phot_util
class ReadColorMagnitude:
"""
Class for reading color-magnitude data from the database.
"""
@typechecked
def __init__(self,
library: str,
filters_color: Tuple[str, str],
filter_mag: str) -> None:
"""
Parameters
----------
library : str
Photometric ('vlm-plx' or 'leggett') or spectral ('irtf' or 'spex') library.
filters_color : tuple(str, str)
Filter names for the color. For a photometric library, these have to be present in
the database (typically in the MKO, 2MASS, or WISE system). For a spectral library,
any filter names can be provided as long as they overlap with the wavelength range
of the spectra.
filter_mag : str
Filter name for the absolute magnitudes (see also description of ``filters_color``).
Returns
-------
NoneType
None
"""
self.library = library
self.filters_color = filters_color
self.filter_mag = filter_mag
config_file = os.path.join(os.getcwd(), 'species_config.ini')
config = configparser.ConfigParser()
config.read_file(open(config_file))
self.database = config['species']['database']
with h5py.File(self.database, 'r') as hdf_file:
if 'photometry' in hdf_file and self.library in hdf_file['photometry']:
self.lib_type = 'phot_lib'
elif 'spectra' in hdf_file and self.library in hdf_file['spectra']:
self.lib_type = 'spec_lib'
else:
raise ValueError(f'The \'{self.library}\' library is not present in the database.')
@typechecked
def get_color_magnitude(self,
object_type: Optional[str] = None) -> box.ColorMagBox:
"""
Function for extracting color-magnitude data from the selected library.
Parameters
----------
object_type : str, None
Object type for which the colors and magnitudes are extracted. Either field dwarfs
('field') or young/low-gravity objects ('young'). All objects are selected if set
to ``None``.
Returns
-------
species.core.box.ColorMagBox
Box with the colors and magnitudes.
"""
if self.lib_type == 'phot_lib':
with h5py.File(self.database, 'r') as h5_file:
sptype = np.asarray(h5_file[f'photometry/{self.library}/sptype'])
dist = np.asarray(h5_file[f'photometry/{self.library}/distance'])
dist_error = np.asarray(h5_file[f'photometry/{self.library}/distance_error'])
flag = np.asarray(h5_file[f'photometry/{self.library}/flag'])
obj_names = np.asarray(h5_file[f'photometry/{self.library}/name'])
if object_type is None:
indices = np.arange(0, np.size(sptype), 1)
elif object_type == 'field':
indices = np.where(flag == 'null')[0]
elif object_type == 'young':
indices = []
for j, object_flag in enumerate(flag):
if 'young' in object_flag:
indices.append(j)
elif 'lowg' in object_flag:
indices.append(j)
indices = np.array(indices)
if indices.size > 0:
with h5py.File(self.database, 'r') as h5_file:
mag1 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_color[0]}'])
mag2 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_color[1]}'])
else:
raise ValueError(f'There is not data available from \'{self.library}\' for '
f'\'{object_type}\' type objects with the chosen filters.')
color = mag1 - mag2
if self.filter_mag == self.filters_color[0]:
mag, _ = phot_util.apparent_to_absolute((mag1, None), (dist, dist_error))
elif self.filter_mag == self.filters_color[1]:
mag, _ = phot_util.apparent_to_absolute((mag2, None), (dist, dist_error))
color = color[indices]
mag = mag[indices]
sptype = sptype[indices]
obj_names = obj_names[indices]
indices = []
for i in range(color.size):
if not np.isnan(color[i]) and not np.isnan(mag[i]):
indices.append(i)
colormag_box = box.create_box(boxtype='colormag',
library=self.library,
object_type=object_type,
filters_color=self.filters_color,
filter_mag=self.filter_mag,
color=color[indices],
magnitude=mag[indices],
sptype=sptype[indices],
names=obj_names[indices])
elif self.lib_type == 'spec_lib':
read_spec_0 = read_spectrum.ReadSpectrum(spec_library=self.library,
filter_name=self.filters_color[0])
read_spec_1 = read_spectrum.ReadSpectrum(spec_library=self.library,
filter_name=self.filters_color[1])
read_spec_2 = read_spectrum.ReadSpectrum(spec_library=self.library,
filter_name=self.filter_mag)
phot_box_0 = read_spec_0.get_magnitude(sptypes=None)
phot_box_1 = read_spec_1.get_magnitude(sptypes=None)
phot_box_2 = read_spec_2.get_magnitude(sptypes=None)
colormag_box = box.create_box(boxtype='colormag',
library=self.library,
object_type=object_type,
filters_color=self.filters_color,
filter_mag=self.filter_mag,
color=phot_box_0.app_mag[:, 0]-phot_box_1.app_mag[:, 0],
magnitude=phot_box_2.abs_mag[:, 0],
sptype=phot_box_0.sptype,
names=None)
return colormag_box
class ReadColorColor:
"""
Class for reading color-color data from the database.
"""
@typechecked
def __init__(self,
library: str,
filters_colors: Tuple[Tuple[str, str], Tuple[str, str]]) -> None:
"""
Parameters
----------
library : str
Photometric ('vlm-plx' or 'leggett') or spectral ('irtf' or 'spex') library.
filters_colors : tuple(tuple(str, str), tuple(str, str))
Filter names for the colors. For a photometric library, these have to be present in
the database (typically in the MKO, 2MASS, or WISE system). For a spectral library,
any filter names can be provided as long as they overlap with the wavelength range
of the spectra.
Returns
-------
NoneType
None
"""
self.library = library
self.filters_colors = filters_colors
config_file = os.path.join(os.getcwd(), 'species_config.ini')
config = configparser.ConfigParser()
config.read_file(open(config_file))
self.database = config['species']['database']
with h5py.File(self.database, 'r') as hdf_file:
if 'photometry' in hdf_file and self.library in hdf_file['photometry']:
self.lib_type = 'phot_lib'
elif 'spectra' in hdf_file and self.library in hdf_file['spectra']:
self.lib_type = 'spec_lib'
else:
raise ValueError(f'The \'{self.library}\' library is not present in the database.')
@typechecked
def get_color_color(self,
object_type: Optional[str] = None) -> box.ColorColorBox:
"""
Function for extracting color-color data from the selected library.
Parameters
----------
object_type : str, None
Object type for which the colors and magnitudes are extracted. Either field dwarfs
('field') or young/low-gravity objects ('young'). All objects are selected if set
to ``None``.
Returns
-------
species.core.box.ColorColorBox
Box with the colors.
"""
if self.lib_type == 'phot_lib':
h5_file = h5py.File(self.database, 'r')
sptype = np.asarray(h5_file[f'photometry/{self.library}/sptype'])
flag = np.asarray(h5_file[f'photometry/{self.library}/flag'])
obj_names = np.asarray(h5_file[f'photometry/{self.library}/name'])
if object_type is None:
indices = np.arange(0, np.size(sptype), 1)
elif object_type == 'field':
indices = np.where(flag == 'null')[0]
elif object_type == 'young':
indices = []
for j, object_flag in enumerate(flag):
if 'young' in object_flag:
indices.append(j)
elif 'lowg' in object_flag:
indices.append(j)
indices = np.array(indices)
mag1 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_colors[0][0]}'])
mag2 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_colors[0][1]}'])
mag3 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_colors[1][0]}'])
mag4 = np.asarray(h5_file[f'photometry/{self.library}/{self.filters_colors[1][1]}'])
color1 = mag1 - mag2
color2 = mag3 - mag4
color1 = color1[indices]
color2 = color2[indices]
sptype = sptype[indices]
obj_names = obj_names[indices]
indices = []
for i in range(color1.size):
if not np.isnan(color1[i]) and not np.isnan(color2[i]):
indices.append(i)
colorbox = box.create_box(boxtype='colorcolor',
library=self.library,
object_type=object_type,
filters=self.filters_colors,
color1=color1[indices],
color2=color2[indices],
sptype=sptype[indices],
names=obj_names[indices])
h5_file.close()
elif self.lib_type == 'spec_lib':
read_spec_0 = read_spectrum.ReadSpectrum(spec_library=self.library,
filter_name=self.filters_colors[0][0])
read_spec_1 = read_spectrum.ReadSpectrum(spec_library=self.library,
filter_name=self.filters_colors[0][1])
read_spec_2 = read_spectrum.ReadSpectrum(spec_library=self.library,
filter_name=self.filters_colors[1][0])
read_spec_3 = read_spectrum.ReadSpectrum(spec_library=self.library,
filter_name=self.filters_colors[1][1])
phot_box_0 = read_spec_0.get_magnitude(sptypes=None)
phot_box_1 = read_spec_1.get_magnitude(sptypes=None)
phot_box_2 = read_spec_2.get_magnitude(sptypes=None)
phot_box_3 = read_spec_3.get_magnitude(sptypes=None)
colorbox = box.create_box(boxtype='colorcolor',
library=self.library,
object_type=object_type,
filters=self.filters_colors,
color1=phot_box_0.app_mag[:, 0]-phot_box_1.app_mag[:, 0],
color2=phot_box_2.app_mag[:, 0]-phot_box_3.app_mag[:, 0],
sptype=phot_box_0.sptype,
names=None)
return colorbox
| [
"configparser.ConfigParser",
"species.util.phot_util.apparent_to_absolute",
"numpy.where",
"numpy.size",
"numpy.asarray",
"species.core.box.create_box",
"h5py.File",
"os.getcwd",
"numpy.array",
"numpy.isnan",
"species.read.read_spectrum.ReadSpectrum"
] | [((1538, 1565), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1563, 1565), False, 'import configparser\n'), ((8001, 8028), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (8026, 8028), False, 'import configparser\n'), ((1485, 1496), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1494, 1496), False, 'import os\n'), ((1679, 1708), 'h5py.File', 'h5py.File', (['self.database', '"""r"""'], {}), "(self.database, 'r')\n", (1688, 1708), False, 'import h5py\n'), ((4979, 5233), 'species.core.box.create_box', 'box.create_box', ([], {'boxtype': '"""colormag"""', 'library': 'self.library', 'object_type': 'object_type', 'filters_color': 'self.filters_color', 'filter_mag': 'self.filter_mag', 'color': 'color[indices]', 'magnitude': 'mag[indices]', 'sptype': 'sptype[indices]', 'names': 'obj_names[indices]'}), "(boxtype='colormag', library=self.library, object_type=\n object_type, filters_color=self.filters_color, filter_mag=self.\n filter_mag, color=color[indices], magnitude=mag[indices], sptype=sptype\n [indices], names=obj_names[indices])\n", (4993, 5233), False, 'from species.core import box\n'), ((7948, 7959), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7957, 7959), False, 'import os\n'), ((8142, 8171), 'h5py.File', 'h5py.File', (['self.database', '"""r"""'], {}), "(self.database, 'r')\n", (8151, 8171), False, 'import h5py\n'), ((9237, 9266), 'h5py.File', 'h5py.File', (['self.database', '"""r"""'], {}), "(self.database, 'r')\n", (9246, 9266), False, 'import h5py\n'), ((9289, 9345), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/sptype']"], {}), "(h5_file[f'photometry/{self.library}/sptype'])\n", (9299, 9345), True, 'import numpy as np\n'), ((9365, 9419), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/flag']"], {}), "(h5_file[f'photometry/{self.library}/flag'])\n", (9375, 9419), True, 'import numpy as np\n'), ((9444, 9498), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/name']"], {}), "(h5_file[f'photometry/{self.library}/name'])\n", (9454, 9498), True, 'import numpy as np\n'), ((10063, 10140), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/{self.filters_colors[0][0]}']"], {}), "(h5_file[f'photometry/{self.library}/{self.filters_colors[0][0]}'])\n", (10073, 10140), True, 'import numpy as np\n'), ((10160, 10237), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/{self.filters_colors[0][1]}']"], {}), "(h5_file[f'photometry/{self.library}/{self.filters_colors[0][1]}'])\n", (10170, 10237), True, 'import numpy as np\n'), ((10257, 10334), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/{self.filters_colors[1][0]}']"], {}), "(h5_file[f'photometry/{self.library}/{self.filters_colors[1][0]}'])\n", (10267, 10334), True, 'import numpy as np\n'), ((10354, 10431), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/{self.filters_colors[1][1]}']"], {}), "(h5_file[f'photometry/{self.library}/{self.filters_colors[1][1]}'])\n", (10364, 10431), True, 'import numpy as np\n'), ((10855, 11074), 'species.core.box.create_box', 'box.create_box', ([], {'boxtype': '"""colorcolor"""', 'library': 'self.library', 'object_type': 'object_type', 'filters': 'self.filters_colors', 'color1': 'color1[indices]', 'color2': 'color2[indices]', 'sptype': 'sptype[indices]', 'names': 'obj_names[indices]'}), "(boxtype='colorcolor', library=self.library, object_type=\n object_type, filters=self.filters_colors, color1=color1[indices],\n color2=color2[indices], sptype=sptype[indices], names=obj_names[indices])\n", (10869, 11074), False, 'from species.core import box\n'), ((2792, 2821), 'h5py.File', 'h5py.File', (['self.database', '"""r"""'], {}), "(self.database, 'r')\n", (2801, 2821), False, 'import h5py\n'), ((2859, 2915), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/sptype']"], {}), "(h5_file[f'photometry/{self.library}/sptype'])\n", (2869, 2915), True, 'import numpy as np\n'), ((2939, 2997), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/distance']"], {}), "(h5_file[f'photometry/{self.library}/distance'])\n", (2949, 2997), True, 'import numpy as np\n'), ((3027, 3091), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/distance_error']"], {}), "(h5_file[f'photometry/{self.library}/distance_error'])\n", (3037, 3091), True, 'import numpy as np\n'), ((3115, 3169), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/flag']"], {}), "(h5_file[f'photometry/{self.library}/flag'])\n", (3125, 3169), True, 'import numpy as np\n'), ((3198, 3252), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/name']"], {}), "(h5_file[f'photometry/{self.library}/name'])\n", (3208, 3252), True, 'import numpy as np\n'), ((4417, 4481), 'species.util.phot_util.apparent_to_absolute', 'phot_util.apparent_to_absolute', (['(mag1, None)', '(dist, dist_error)'], {}), '((mag1, None), (dist, dist_error))\n', (4447, 4481), False, 'from species.util import phot_util\n'), ((5624, 5717), 'species.read.read_spectrum.ReadSpectrum', 'read_spectrum.ReadSpectrum', ([], {'spec_library': 'self.library', 'filter_name': 'self.filters_color[0]'}), '(spec_library=self.library, filter_name=self.\n filters_color[0])\n', (5650, 5717), False, 'from species.read import read_spectrum\n'), ((5793, 5886), 'species.read.read_spectrum.ReadSpectrum', 'read_spectrum.ReadSpectrum', ([], {'spec_library': 'self.library', 'filter_name': 'self.filters_color[1]'}), '(spec_library=self.library, filter_name=self.\n filters_color[1])\n', (5819, 5886), False, 'from species.read import read_spectrum\n'), ((5962, 6049), 'species.read.read_spectrum.ReadSpectrum', 'read_spectrum.ReadSpectrum', ([], {'spec_library': 'self.library', 'filter_name': 'self.filter_mag'}), '(spec_library=self.library, filter_name=self.\n filter_mag)\n', (5988, 6049), False, 'from species.read import read_spectrum\n'), ((6322, 6612), 'species.core.box.create_box', 'box.create_box', ([], {'boxtype': '"""colormag"""', 'library': 'self.library', 'object_type': 'object_type', 'filters_color': 'self.filters_color', 'filter_mag': 'self.filter_mag', 'color': '(phot_box_0.app_mag[:, 0] - phot_box_1.app_mag[:, 0])', 'magnitude': 'phot_box_2.abs_mag[:, 0]', 'sptype': 'phot_box_0.sptype', 'names': 'None'}), "(boxtype='colormag', library=self.library, object_type=\n object_type, filters_color=self.filters_color, filter_mag=self.\n filter_mag, color=phot_box_0.app_mag[:, 0] - phot_box_1.app_mag[:, 0],\n magnitude=phot_box_2.abs_mag[:, 0], sptype=phot_box_0.sptype, names=None)\n", (6336, 6612), False, 'from species.core import box\n'), ((11430, 11527), 'species.read.read_spectrum.ReadSpectrum', 'read_spectrum.ReadSpectrum', ([], {'spec_library': 'self.library', 'filter_name': 'self.filters_colors[0][0]'}), '(spec_library=self.library, filter_name=self.\n filters_colors[0][0])\n', (11456, 11527), False, 'from species.read import read_spectrum\n'), ((11603, 11700), 'species.read.read_spectrum.ReadSpectrum', 'read_spectrum.ReadSpectrum', ([], {'spec_library': 'self.library', 'filter_name': 'self.filters_colors[0][1]'}), '(spec_library=self.library, filter_name=self.\n filters_colors[0][1])\n', (11629, 11700), False, 'from species.read import read_spectrum\n'), ((11776, 11873), 'species.read.read_spectrum.ReadSpectrum', 'read_spectrum.ReadSpectrum', ([], {'spec_library': 'self.library', 'filter_name': 'self.filters_colors[1][0]'}), '(spec_library=self.library, filter_name=self.\n filters_colors[1][0])\n', (11802, 11873), False, 'from species.read import read_spectrum\n'), ((11949, 12046), 'species.read.read_spectrum.ReadSpectrum', 'read_spectrum.ReadSpectrum', ([], {'spec_library': 'self.library', 'filter_name': 'self.filters_colors[1][1]'}), '(spec_library=self.library, filter_name=self.\n filters_colors[1][1])\n', (11975, 12046), False, 'from species.read import read_spectrum\n'), ((12380, 12664), 'species.core.box.create_box', 'box.create_box', ([], {'boxtype': '"""colorcolor"""', 'library': 'self.library', 'object_type': 'object_type', 'filters': 'self.filters_colors', 'color1': '(phot_box_0.app_mag[:, 0] - phot_box_1.app_mag[:, 0])', 'color2': '(phot_box_2.app_mag[:, 0] - phot_box_3.app_mag[:, 0])', 'sptype': 'phot_box_0.sptype', 'names': 'None'}), "(boxtype='colorcolor', library=self.library, object_type=\n object_type, filters=self.filters_colors, color1=phot_box_0.app_mag[:, \n 0] - phot_box_1.app_mag[:, 0], color2=phot_box_2.app_mag[:, 0] -\n phot_box_3.app_mag[:, 0], sptype=phot_box_0.sptype, names=None)\n", (12394, 12664), False, 'from species.core import box\n'), ((3329, 3344), 'numpy.size', 'np.size', (['sptype'], {}), '(sptype)\n', (3336, 3344), True, 'import numpy as np\n'), ((3852, 3881), 'h5py.File', 'h5py.File', (['self.database', '"""r"""'], {}), "(self.database, 'r')\n", (3861, 3881), False, 'import h5py\n'), ((3921, 3994), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/{self.filters_color[0]}']"], {}), "(h5_file[f'photometry/{self.library}/{self.filters_color[0]}'])\n", (3931, 3994), True, 'import numpy as np\n'), ((4022, 4095), 'numpy.asarray', 'np.asarray', (["h5_file[f'photometry/{self.library}/{self.filters_color[1]}']"], {}), "(h5_file[f'photometry/{self.library}/{self.filters_color[1]}'])\n", (4032, 4095), True, 'import numpy as np\n'), ((4567, 4631), 'species.util.phot_util.apparent_to_absolute', 'phot_util.apparent_to_absolute', (['(mag2, None)', '(dist, dist_error)'], {}), '((mag2, None), (dist, dist_error))\n', (4597, 4631), False, 'from species.util import phot_util\n'), ((9575, 9590), 'numpy.size', 'np.size', (['sptype'], {}), '(sptype)\n', (9582, 9590), True, 'import numpy as np\n'), ((3417, 3441), 'numpy.where', 'np.where', (["(flag == 'null')"], {}), "(flag == 'null')\n", (3425, 3441), True, 'import numpy as np\n'), ((3779, 3796), 'numpy.array', 'np.array', (['indices'], {}), '(indices)\n', (3787, 3796), True, 'import numpy as np\n'), ((4868, 4886), 'numpy.isnan', 'np.isnan', (['color[i]'], {}), '(color[i])\n', (4876, 4886), True, 'import numpy as np\n'), ((4895, 4911), 'numpy.isnan', 'np.isnan', (['mag[i]'], {}), '(mag[i])\n', (4903, 4911), True, 'import numpy as np\n'), ((9663, 9687), 'numpy.where', 'np.where', (["(flag == 'null')"], {}), "(flag == 'null')\n", (9671, 9687), True, 'import numpy as np\n'), ((10025, 10042), 'numpy.array', 'np.array', (['indices'], {}), '(indices)\n', (10033, 10042), True, 'import numpy as np\n'), ((10744, 10763), 'numpy.isnan', 'np.isnan', (['color1[i]'], {}), '(color1[i])\n', (10752, 10763), True, 'import numpy as np\n'), ((10772, 10791), 'numpy.isnan', 'np.isnan', (['color2[i]'], {}), '(color2[i])\n', (10780, 10791), True, 'import numpy as np\n')] |
"""
Parses league of legend history from my `lolexport.parse` format
from: https://github.com/seanbreckenridge/lolexport
"""
REQUIRES = ["git+https://github.com/seanbreckenridge/lolexport"]
# see https://github.com/seanbreckenridge/dotfiles/blob/master/.config/my/my/config/__init__.py for an example
from my.config import league_of_legends as user_config # type: ignore[attr-defined]
from my.core import Paths, dataclass
@dataclass
class config(user_config):
# path[s]/glob to the exported data. These are the resulting json file from 'lolexport parse'
export_path: Paths
# leauge of legends username
username: str
import json
from pathlib import Path
from datetime import datetime, timedelta
from typing import NamedTuple, Iterator, Sequence, Dict, Union, List, Optional, Set
from functools import partial
from itertools import chain
from my.core import get_files, Stats, Res, Json, warn_if_empty
from .utils.time import parse_datetime_millis
from .utils.common import InputSource
def inputs() -> Sequence[Path]:
"""
Get the parsed league of legends JSON files
(output of https://github.com/seanbreckenridge/lolexport/blob/master/lolexport/parse.py)
"""
return get_files(config.export_path)
ChampionInfo = Dict[str, Union[str, List[str]]]
Metadata = Optional[str]
Names = List[str]
# represents one League of Legends game
class Game(NamedTuple):
champion_name: str
game_id: int
season: int
game_started: datetime
game_duration: timedelta
players: Names
my_stats: Json # just my characters' stats, though all are in the JSON dump
all_stats: List[Json]
queue: Optional[Dict[str, str]]
role: Metadata
lane: Metadata
map_name: Metadata
game_mode: Metadata
game_type: Metadata
@property
def won(self) -> bool:
return self.my_stats["win"]
@property
def champions(self) -> Names:
return list(map(lambda s: s["champion"]["name"], self.all_stats))
@property
def game_ended(self) -> datetime:
return self.game_started + self.game_duration
Results = Iterator[Res[Game]]
def history(
from_paths: InputSource = inputs, summoner_name: Optional[str] = None
) -> Results:
sname: Optional[str] = summoner_name or config.username
if sname is None:
raise RuntimeError("No league of legends username received!")
_json_for_user = partial(_read_parsed_json, username=sname)
yield from _merge_histories(*map(_json_for_user, from_paths()))
@warn_if_empty
def _merge_histories(*sources: Results) -> Results:
emitted: Set[int] = set()
for g in chain(*sources):
if isinstance(g, Exception):
yield g
else:
if g.game_id in emitted:
continue
emitted.add(g.game_id)
yield g
def _read_parsed_json(p: Path, username: str) -> Results:
items = json.loads(p.read_text())
for game in items:
playerNames: Dict[int, str] = {
int(uid): name for uid, name in game["playerNames"].items()
}
# get my participant_id from the playerNames
try:
participant_id: int = next(
(k for k, v in playerNames.items() if v == username)
)
except StopIteration:
yield RuntimeError(f"Couldn't extract id for {username} from {playerNames}")
continue
# get my stats
try:
my_stats = next(
filter(
lambda ustats: int(ustats["participantId"]) == participant_id,
game["stats"],
)
)
except StopIteration:
yield RuntimeError(f"Couldn't extract stats for game {game['gameId']}")
continue
else:
# if try try block didn't error, use my_stats
# assuming datetime is epoch ms
yield Game(
champion_name=game["champion"]["name"],
game_id=game["gameId"],
queue=game.get("queue"),
season=game.get("season"),
role=_remove_none(game.get("role")),
lane=_remove_none(game.get("lane")),
game_started=parse_datetime_millis(game["gameCreation"]),
game_duration=timedelta(seconds=game["gameDuration"]),
map_name=game["map"],
game_mode=game["gameMode"],
game_type=game["gameType"],
players=list(playerNames.values()),
my_stats=my_stats,
all_stats=game["stats"],
)
# convert the 'NONE' string to a None object
def _remove_none(m: Optional[str]) -> Optional[str]:
if m is not None and m.upper() == "NONE":
return None
return m
def stats() -> Stats:
from my.core import stat
return {**stat(history)}
| [
"itertools.chain",
"my.core.stat",
"my.core.get_files",
"functools.partial",
"datetime.timedelta"
] | [((1211, 1240), 'my.core.get_files', 'get_files', (['config.export_path'], {}), '(config.export_path)\n', (1220, 1240), False, 'from my.core import get_files, Stats, Res, Json, warn_if_empty\n'), ((2398, 2440), 'functools.partial', 'partial', (['_read_parsed_json'], {'username': 'sname'}), '(_read_parsed_json, username=sname)\n', (2405, 2440), False, 'from functools import partial\n'), ((2621, 2636), 'itertools.chain', 'chain', (['*sources'], {}), '(*sources)\n', (2626, 2636), False, 'from itertools import chain\n'), ((4858, 4871), 'my.core.stat', 'stat', (['history'], {}), '(history)\n', (4862, 4871), False, 'from my.core import stat\n'), ((4302, 4341), 'datetime.timedelta', 'timedelta', ([], {'seconds': "game['gameDuration']"}), "(seconds=game['gameDuration'])\n", (4311, 4341), False, 'from datetime import datetime, timedelta\n')] |
# Generated by Django 2.1a1 on 2018-07-30 18:50
import aboutme.models
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Me',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('title', models.CharField(max_length=500)),
('location', models.CharField(max_length=250)),
('bio', models.TextField()),
('tags', models.TextField(default="''")),
('work', models.CharField(max_length=500)),
('education', models.CharField(max_length=500)),
('profileimage', models.ImageField(blank=True, null=True, upload_to=aboutme.models.get_image_path)),
],
),
]
| [
"django.db.models.ImageField",
"django.db.models.TextField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((320, 413), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (336, 413), False, 'from django.db import migrations, models\n'), ((437, 469), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (453, 469), False, 'from django.db import migrations, models\n'), ((498, 530), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (514, 530), False, 'from django.db import migrations, models\n'), ((562, 594), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(250)'}), '(max_length=250)\n', (578, 594), False, 'from django.db import migrations, models\n'), ((621, 639), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (637, 639), False, 'from django.db import migrations, models\n'), ((667, 697), 'django.db.models.TextField', 'models.TextField', ([], {'default': '"""\'\'"""'}), '(default="\'\'")\n', (683, 697), False, 'from django.db import migrations, models\n'), ((725, 757), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (741, 757), False, 'from django.db import migrations, models\n'), ((790, 822), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (806, 822), False, 'from django.db import migrations, models\n'), ((858, 944), 'django.db.models.ImageField', 'models.ImageField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': 'aboutme.models.get_image_path'}), '(blank=True, null=True, upload_to=aboutme.models.\n get_image_path)\n', (875, 944), False, 'from django.db import migrations, models\n')] |
import sys
import re
from pprint import pprint
sample = { 'awesome-cancer-variant-databases':
{ 'Cancer':
{
'Clinically-focused':
[{'CanDL': 'https://candl.osu.edu' }],
'Catalogs':
[{ 'COSMIC':
'http://cancer.sanger.ac.uk/cancergenome/projects/cosmic'}]
}
,
'Germline':
[
{ 'dnSNP': 'http://www.ncbi.nlm.nih.gov/SNP' },
{ 'Exome Aggregation Consortium':
'http://exac.broadinstitute.org'}
]
}
}
sample_meta = { 'awesome-cancer-variant-databases': 'A community-maintained repository of cancer clinical knowledge bases and databases focused on cancer and normal variants. [Contributions welcome](https://github.com/seandavi/awesome-cancer-variant-databases/blob/master/CONTRIBUTE.md]).',
'CanDL': 'an expert-curated database of potentially actionable driver mutations for molecular pathologists and laboratory directors to facilitate literature-based annotation of genomic testing of tumors. [web app, Download]'
}
sample_info = { 'author': '<NAME>',
'gituser': 'seandavi',
'date': '10-16-2016',
'total': 16
}
# Ugly parsing code
def txt2dict(text):
cnt = 0
doc = {}
depth = 0
depth_pointer = {}
pointer = doc
istitle = False
for line in text.split("\n"):
if not len(line):
continue
line_type = find_type(line)
text = line.split(" ")[1:]
text = " ".join(text)
if line_type[0] == "H":
if not pointer: # is empty
if depth <= int(line_type[1:]):
pointer[text] = {}
if not istitle:
istitle = True
depth_pointer[0] = pointer[text]
pointer = pointer[text]
else:
pointer = depth_pointer[int(line_type[1:]) - 1]
pointer[text] = {}
pointer = pointer[text]
depth = int(line_type[1:])
depth_pointer[depth] = pointer
if line_type == "L":
ldict = parsing(text)
if not pointer:
pointer['LIST'] = [{ldict['name']:ldict['url']}]
else:
pointer['LIST'].append({ldict['name']:ldict['url']})
cnt += 1
return doc
def find_type(text):
if text[0] == "#":
header = text.split(" ")[0]
return "H" + str(len(header))
if text[0] == ("-" or "*"):
return "L"
if text[0] == " ":
islist = text.find('-')
if islist:
return "SubL" + str(islist)
return "Else"
def main():
with open(sys.argv[1], "r") as f:
lines = f.read()
new = txt2dict(lines)
pprint (new)
def parsing(inputtext):
# [name](url) description
line = re.compile(r'\[([^\]]*)\]\s*\(([^\)]*)\)([^$]*)')
depth = 0
result = line.match(inputtext)
return { "name": result.group(1), "url": result.group(2), "description":
result.group(3)}
main()
| [
"pprint.pprint",
"re.compile"
] | [((3054, 3109), 're.compile', 're.compile', (['"""\\\\[([^\\\\]]*)\\\\]\\\\s*\\\\(([^\\\\)]*)\\\\)([^$]*)"""'], {}), "('\\\\[([^\\\\]]*)\\\\]\\\\s*\\\\(([^\\\\)]*)\\\\)([^$]*)')\n", (3064, 3109), False, 'import re\n'), ((2974, 2985), 'pprint.pprint', 'pprint', (['new'], {}), '(new)\n', (2980, 2985), False, 'from pprint import pprint\n')] |
from collections import OrderedDict
import logging
import warnings
warnings.filterwarnings("ignore")
logging.basicConfig(filename="runtime.log", \
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', \
datefmt='%d-%b-%y %H:%M:%S', \
level=logging.DEBUG, filemode="a")
import torch
import torch.nn
DEVICE= torch.device("cuda" if torch.cuda.is_available() else "cpu")
def train(model, train_loader, epoch, criterion, optimizer):
### TRAINING LOOP
model.train()
running_loss = 0
accuracy = 0
for batch_idx, (data, target) in enumerate(train_loader):
data = data.to(DEVICE)
target = target.to(DEVICE)
output = model(data)
if torch.argmax(output)==target:
accuracy += 1
loss = criterion(output, target)
running_loss += loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
logging.debug("Epoch: {}\nTrain_loss: {:.4f}, Train Accuracy: {:.2f}%".format(epoch, running_loss/len(train_loader), 100*accuracy/(len(train_loader))))
return OrderedDict([('loss', running_loss/len(train_loader))
('accuracy', (accuracy/len(train_loader))*100)])
def validate(model, test_loader, epoch, criterion, optimizer):
### TRAINING LOOP
model.eval()
running_loss = 0
accuracy = 0
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
data = data.to(DEVICE)
target = target.to(DEVICE)
output = model(data)
if torch.argmax(output)==target:
accuracy += 1
loss = criterion(output, target)
running_loss += loss.item()
logging.debug("Epoch: {}\nVal_loss: {:.4f}, Val Accuracy: {:.2f}%".format(epoch, running_loss/len(test_loader), 100*accuracy/(len(test_loader))))
return OrderedDict([('loss', running_loss/len(test_loader))
('accuracy', (accuracy/len(test_loader))*100)])
| [
"logging.basicConfig",
"torch.cuda.is_available",
"torch.no_grad",
"warnings.filterwarnings",
"torch.argmax"
] | [((67, 100), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (90, 100), False, 'import warnings\n'), ((102, 282), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""runtime.log"""', 'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""', 'datefmt': '"""%d-%b-%y %H:%M:%S"""', 'level': 'logging.DEBUG', 'filemode': '"""a"""'}), "(filename='runtime.log', format=\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt=\n '%d-%b-%y %H:%M:%S', level=logging.DEBUG, filemode='a')\n", (121, 282), False, 'import logging\n'), ((355, 380), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (378, 380), False, 'import torch\n'), ((1242, 1257), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1255, 1257), False, 'import torch\n'), ((663, 683), 'torch.argmax', 'torch.argmax', (['output'], {}), '(output)\n', (675, 683), False, 'import torch\n'), ((1405, 1425), 'torch.argmax', 'torch.argmax', (['output'], {}), '(output)\n', (1417, 1425), False, 'import torch\n')] |
from django import forms
from tablemanager.models import Workspace
from wmsmanager.models import WmsServer,WmsLayer
from borg_utils.form_fields import GeoserverSettingForm,MetaTilingFactorField,GridSetField
from borg_utils.form_fields import GroupedModelChoiceField
class WmsServerForm(forms.ModelForm,GeoserverSettingForm):
"""
A form for WmsServer model
"""
max_connections = forms.IntegerField(label="Max concurrent connections",initial=6,min_value=1,max_value=128)
max_connections.setting_type = "geoserver_setting"
max_connections.key = "max_connections"
connect_timeout = forms.IntegerField(label="Connect timeout in seconds",initial=30,min_value=1,max_value=3600)
connect_timeout.setting_type = "geoserver_setting"
connect_timeout.key = "connect_timeout"
read_timeout = forms.IntegerField(label="Read timeout in seconds",initial=60,min_value=1,max_value=3600)
read_timeout.setting_type = "geoserver_setting"
read_timeout.key = "read_timeout"
workspace = GroupedModelChoiceField('publish_channel',queryset=Workspace.objects.all(),required=True,choice_family="workspace",choice_name="workspace_choices")
def __init__(self, *args, **kwargs):
kwargs['initial']=kwargs.get('initial',{})
self.get_setting_from_model(*args,**kwargs)
super(WmsServerForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs and kwargs['instance'] and kwargs['instance'].pk:
self.fields['name'].widget.attrs['readonly'] = True
self.fields['workspace'] = forms.ModelChoiceField(queryset=Workspace.objects.filter(pk = kwargs["instance"].workspace.pk),required=True)
def _post_clean(self):
if self.errors:
return
self.set_setting_to_model()
super(WmsServerForm,self)._post_clean()
def save(self, commit=True):
self.instance.enable_save_signal()
return super(WmsServerForm, self).save(commit)
class Meta:
model = WmsServer
fields = "__all__"
class WmsLayerForm(forms.ModelForm,GeoserverSettingForm):
"""
A form for WmsLayer model
"""
create_cache_layer = forms.BooleanField(required=False,label="create_cache_layer",initial={"enabled":True})
create_cache_layer.setting_type = "geoserver_setting"
server_cache_expire = forms.IntegerField(label="server_cache_expire",min_value=0,required=False,initial=0,help_text="Expire server cache after n seconds (set to 0 to use source setting)")
server_cache_expire.setting_type = "geoserver_setting"
client_cache_expire = forms.IntegerField(label="client_cache_expire",min_value=0,required=False,initial=0,help_text="Expire client cache after n seconds (set to 0 to use source setting)")
client_cache_expire.setting_type = "geoserver_setting"
def __init__(self, *args, **kwargs):
kwargs['initial']=kwargs.get('initial',{})
self.get_setting_from_model(*args,**kwargs)
super(WmsLayerForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['readonly'] = True
if 'instance' in kwargs and kwargs['instance'] and kwargs['instance'].pk:
if kwargs['instance'].is_published:
self.fields['kmi_name'].widget.attrs['readonly'] = True
else:
if "readonly" in self.fields['kmi_name'].widget.attrs:
del self.fields['kmi_name'].widget.attrs['readonly']
def _post_clean(self):
if self.errors:
return
self.set_setting_to_model()
super(WmsLayerForm,self)._post_clean()
class Meta:
model = WmsLayer
fields = "__all__"
| [
"tablemanager.models.Workspace.objects.filter",
"django.forms.BooleanField",
"django.forms.IntegerField",
"tablemanager.models.Workspace.objects.all"
] | [((396, 494), 'django.forms.IntegerField', 'forms.IntegerField', ([], {'label': '"""Max concurrent connections"""', 'initial': '(6)', 'min_value': '(1)', 'max_value': '(128)'}), "(label='Max concurrent connections', initial=6, min_value\n =1, max_value=128)\n", (414, 494), False, 'from django import forms\n'), ((610, 709), 'django.forms.IntegerField', 'forms.IntegerField', ([], {'label': '"""Connect timeout in seconds"""', 'initial': '(30)', 'min_value': '(1)', 'max_value': '(3600)'}), "(label='Connect timeout in seconds', initial=30,\n min_value=1, max_value=3600)\n", (628, 709), False, 'from django import forms\n'), ((822, 918), 'django.forms.IntegerField', 'forms.IntegerField', ([], {'label': '"""Read timeout in seconds"""', 'initial': '(60)', 'min_value': '(1)', 'max_value': '(3600)'}), "(label='Read timeout in seconds', initial=60, min_value=1,\n max_value=3600)\n", (840, 918), False, 'from django import forms\n'), ((2159, 2253), 'django.forms.BooleanField', 'forms.BooleanField', ([], {'required': '(False)', 'label': '"""create_cache_layer"""', 'initial': "{'enabled': True}"}), "(required=False, label='create_cache_layer', initial={\n 'enabled': True})\n", (2177, 2253), False, 'from django import forms\n'), ((2331, 2509), 'django.forms.IntegerField', 'forms.IntegerField', ([], {'label': '"""server_cache_expire"""', 'min_value': '(0)', 'required': '(False)', 'initial': '(0)', 'help_text': '"""Expire server cache after n seconds (set to 0 to use source setting)"""'}), "(label='server_cache_expire', min_value=0, required=False,\n initial=0, help_text=\n 'Expire server cache after n seconds (set to 0 to use source setting)')\n", (2349, 2509), False, 'from django import forms\n'), ((2583, 2761), 'django.forms.IntegerField', 'forms.IntegerField', ([], {'label': '"""client_cache_expire"""', 'min_value': '(0)', 'required': '(False)', 'initial': '(0)', 'help_text': '"""Expire client cache after n seconds (set to 0 to use source setting)"""'}), "(label='client_cache_expire', min_value=0, required=False,\n initial=0, help_text=\n 'Expire client cache after n seconds (set to 0 to use source setting)')\n", (2601, 2761), False, 'from django import forms\n'), ((1071, 1094), 'tablemanager.models.Workspace.objects.all', 'Workspace.objects.all', ([], {}), '()\n', (1092, 1094), False, 'from tablemanager.models import Workspace\n'), ((1592, 1652), 'tablemanager.models.Workspace.objects.filter', 'Workspace.objects.filter', ([], {'pk': "kwargs['instance'].workspace.pk"}), "(pk=kwargs['instance'].workspace.pk)\n", (1616, 1652), False, 'from tablemanager.models import Workspace\n')] |
import tkinter as tk
from pyprocessing.renderer.tkinter.window import Window
class TkRenderer:
def __init__(self, pyprocessing):
self.pp = pyprocessing
self.root = None
self.window = None
self.this = self
def init(self):
self.root = tk.Tk()
w = self.pp.namespace.width
h = self.pp.namespace.height
x, y = self.pp.namespace.window_offset
geometry = f"{w + 2}x{h + 20}+{x}+{y}"
self.pyprocessing.logger.info(
'Initializing window with geometry %s', geometry
)
self.root.geometry(geometry)
self.root.title(self.pp.namespace.window_title)
self.root.resizable(self.pp.namespace.window_resizable)
self.root.iconphoto(True, self.pp.namespace.window_icon.tk_photo_image)
self.window = Window(self.root, self.pyprocessing)
self.window.pack(expand=True, fill=tk.BOTH)
def start(self):
self.window.redraw()
self.root.mainloop()
def update_location(self):
w = self.pp.namespace.width
h = self.pp.namespace.height
x, y = self.pp.namespace.window_offset
geometry = f"{w + 2}x{h + 20}+{x}+{y}"
self.pyprocessing.logger.info(
'Updating window with geometry %s', geometry
)
self.root.geometry(geometry)
def update_size(self):
self.update_location()
def update_title(self):
self.root.title(self.pp.namespace.window_title)
def update_resizable(self):
self.root.resizable(self.pp.namespace.window_resizable)
def update_icon(self):
self.root.iconphoto(True, self.pp.namespace.window_icon.tk_photo_image)
| [
"pyprocessing.renderer.tkinter.window.Window",
"tkinter.Tk"
] | [((284, 291), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (289, 291), True, 'import tkinter as tk\n'), ((828, 864), 'pyprocessing.renderer.tkinter.window.Window', 'Window', (['self.root', 'self.pyprocessing'], {}), '(self.root, self.pyprocessing)\n', (834, 864), False, 'from pyprocessing.renderer.tkinter.window import Window\n')] |
from uuid import UUID
from fastapi import status, APIRouter
from starlette.requests import Request
from starlette.responses import FileResponse, RedirectResponse
from erica.api.v2.responses.model import response_model_get_tax_number_validity_from_queue, response_model_post_to_queue
from erica.application.JobService.job_service_factory import get_job_service
from erica.application.Shared.service_injector import get_service
from erica.application.tax_number_validation.TaxNumberValidityService import TaxNumberValidityServiceInterface
from erica.application.tax_number_validation.check_tax_number_dto import CheckTaxNumberDto
from erica.domain.Shared.EricaRequest import RequestType
router = APIRouter()
@router.post('/tax_number_validity', status_code=status.HTTP_201_CREATED, responses=response_model_post_to_queue)
async def is_valid_tax_number(tax_validity_client_identifier: CheckTaxNumberDto, request: Request):
"""
Route for validation of a tax number using the job queue.
:param request: API request object.
:param tax_validity_client_identifier: payload with client identifier and the JSON input data for the tax number validity check.
"""
result = get_job_service(RequestType.check_tax_number).add_to_queue(
tax_validity_client_identifier.payload, tax_validity_client_identifier.client_identifier,
RequestType.check_tax_number)
return RedirectResponse(
request.url_for("get_valid_tax_number_job", request_id=str(result.request_id)).removeprefix(str(request.base_url)),
status_code=201)
@router.get('/tax_number_validity/{request_id}', status_code=status.HTTP_200_OK,
responses=response_model_get_tax_number_validity_from_queue)
async def get_valid_tax_number_job(request_id: UUID):
"""
Route for retrieving job status of a tax number validity from the queue.
:param request_id: the id of the job.
"""
tax_number_validity_service: TaxNumberValidityServiceInterface = get_service(RequestType.check_tax_number)
return tax_number_validity_service.get_response_tax_number_validity(request_id)
@router.get('/tax_offices/', status_code=status.HTTP_200_OK)
def get_tax_offices():
"""
The list of tax offices for all states is requested and returned.
"""
return FileResponse("erica/infrastructure/static/tax_offices.json")
| [
"fastapi.APIRouter",
"starlette.responses.FileResponse",
"erica.application.Shared.service_injector.get_service",
"erica.application.JobService.job_service_factory.get_job_service"
] | [((695, 706), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (704, 706), False, 'from fastapi import status, APIRouter\n'), ((1975, 2016), 'erica.application.Shared.service_injector.get_service', 'get_service', (['RequestType.check_tax_number'], {}), '(RequestType.check_tax_number)\n', (1986, 2016), False, 'from erica.application.Shared.service_injector import get_service\n'), ((2284, 2344), 'starlette.responses.FileResponse', 'FileResponse', (['"""erica/infrastructure/static/tax_offices.json"""'], {}), "('erica/infrastructure/static/tax_offices.json')\n", (2296, 2344), False, 'from starlette.responses import FileResponse, RedirectResponse\n'), ((1187, 1232), 'erica.application.JobService.job_service_factory.get_job_service', 'get_job_service', (['RequestType.check_tax_number'], {}), '(RequestType.check_tax_number)\n', (1202, 1232), False, 'from erica.application.JobService.job_service_factory import get_job_service\n')] |
from typing import Tuple
from hypothesis import given
from tests.port_tests.hints import PortedPolygon
from tests.utils import (equivalence,
implication)
from . import strategies
@given(strategies.polygons)
def test_reflexivity(polygon: PortedPolygon) -> None:
assert polygon == polygon
@given(strategies.polygons_pairs)
def test_symmetry(polygons_pair: Tuple[PortedPolygon, PortedPolygon]) -> None:
first_polygon, second_polygon = polygons_pair
assert equivalence(first_polygon == second_polygon,
second_polygon == first_polygon)
@given(strategies.polygons_triplets)
def test_transitivity(polygons_triplet: Tuple[PortedPolygon, PortedPolygon,
PortedPolygon]) -> None:
first_polygon, second_polygon, third_polygon = polygons_triplet
assert implication(first_polygon == second_polygon
and second_polygon == third_polygon,
first_polygon == third_polygon)
@given(strategies.polygons_pairs)
def test_connection_with_inequality(polygons_pair: Tuple[PortedPolygon,
PortedPolygon]
) -> None:
first_polygon, second_polygon = polygons_pair
assert equivalence(not first_polygon == second_polygon,
first_polygon != second_polygon)
| [
"hypothesis.given",
"tests.utils.implication",
"tests.utils.equivalence"
] | [((209, 235), 'hypothesis.given', 'given', (['strategies.polygons'], {}), '(strategies.polygons)\n', (214, 235), False, 'from hypothesis import given\n'), ((323, 355), 'hypothesis.given', 'given', (['strategies.polygons_pairs'], {}), '(strategies.polygons_pairs)\n', (328, 355), False, 'from hypothesis import given\n'), ((601, 636), 'hypothesis.given', 'given', (['strategies.polygons_triplets'], {}), '(strategies.polygons_triplets)\n', (606, 636), False, 'from hypothesis import given\n'), ((1026, 1058), 'hypothesis.given', 'given', (['strategies.polygons_pairs'], {}), '(strategies.polygons_pairs)\n', (1031, 1058), False, 'from hypothesis import given\n'), ((497, 574), 'tests.utils.equivalence', 'equivalence', (['(first_polygon == second_polygon)', '(second_polygon == first_polygon)'], {}), '(first_polygon == second_polygon, second_polygon == first_polygon)\n', (508, 574), False, 'from tests.utils import equivalence, implication\n'), ((864, 980), 'tests.utils.implication', 'implication', (['(first_polygon == second_polygon and second_polygon == third_polygon)', '(first_polygon == third_polygon)'], {}), '(first_polygon == second_polygon and second_polygon ==\n third_polygon, first_polygon == third_polygon)\n', (875, 980), False, 'from tests.utils import equivalence, implication\n'), ((1312, 1397), 'tests.utils.equivalence', 'equivalence', (['(not first_polygon == second_polygon)', '(first_polygon != second_polygon)'], {}), '(not first_polygon == second_polygon, first_polygon !=\n second_polygon)\n', (1323, 1397), False, 'from tests.utils import equivalence, implication\n')] |
from flask import Flask, render_template, request, jsonify, \
redirect, Response, url_for, abort
import helpers
config_dic = helpers.load_config()
# flask app setup
app = Flask(__name__)
app.secret_key = config_dic["app_secret_key"]
@app.route("/", methods=["GET"])
def home():
return render_template("home.html", public_key=config_dic["captcha_public_key"])
@app.route("/validate", methods=["POST"])
def validate():
data = None
client_ip = request.remote_addr
captcha_response = request.form['g-recaptcha-response']
if helpers.verify(config_dic["captcha_private_key"], captcha_response, client_ip):
data = {"status":True,
"msg":"Here's the email you were looking for",
"email":config_dic["hidden_address"]}
else:
data = {"status":False,
"msg":"reCAPTCHA test failed."}
return render_template("validate.html", data=data)
@app.route("/_validate", methods=["POST"])
def ajax_validate():
data = None
client_ip = request.remote_addr
captcha_response = request.form['g-recaptcha-response']
if helpers.verify(config_dic["captcha_private_key"], captcha_response, client_ip):
data = {"status":True,
"msg":"Here's the email you were looking for",
"email":config_dic["hidden_address"]}
else:
data = {"status":False,
"msg":"reCAPTCHA test failed."}
return jsonify(data)
if __name__ == "__main__":
app.run(debug=True) | [
"flask.render_template",
"flask.Flask",
"helpers.verify",
"helpers.load_config",
"flask.jsonify"
] | [((146, 167), 'helpers.load_config', 'helpers.load_config', ([], {}), '()\n', (165, 167), False, 'import helpers\n'), ((193, 208), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (198, 208), False, 'from flask import Flask, render_template, request, jsonify, redirect, Response, url_for, abort\n'), ((313, 386), 'flask.render_template', 'render_template', (['"""home.html"""'], {'public_key': "config_dic['captcha_public_key']"}), "('home.html', public_key=config_dic['captcha_public_key'])\n", (328, 386), False, 'from flask import Flask, render_template, request, jsonify, redirect, Response, url_for, abort\n'), ((553, 631), 'helpers.verify', 'helpers.verify', (["config_dic['captcha_private_key']", 'captcha_response', 'client_ip'], {}), "(config_dic['captcha_private_key'], captcha_response, client_ip)\n", (567, 631), False, 'import helpers\n'), ((825, 868), 'flask.render_template', 'render_template', (['"""validate.html"""'], {'data': 'data'}), "('validate.html', data=data)\n", (840, 868), False, 'from flask import Flask, render_template, request, jsonify, redirect, Response, url_for, abort\n'), ((1041, 1119), 'helpers.verify', 'helpers.verify', (["config_dic['captcha_private_key']", 'captcha_response', 'client_ip'], {}), "(config_dic['captcha_private_key'], captcha_response, client_ip)\n", (1055, 1119), False, 'import helpers\n'), ((1313, 1326), 'flask.jsonify', 'jsonify', (['data'], {}), '(data)\n', (1320, 1326), False, 'from flask import Flask, render_template, request, jsonify, redirect, Response, url_for, abort\n')] |
from scripts.processing import Processor
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--train", type=str, default='files/mmhsct_dataset.csv', help="--train file_path")
parser.add_argument("--data", type=str, default='files/sr_all_comments_111.csv', help="--data file_path")
parser.add_argument("--output", type=str, default='files/system_a_output.csv', help="--output file_path")
args = parser.parse_args()
training_file = args.train
data_file = args.data
output_file = args.output
settings = {
'training_file': training_file,
'data_file': data_file,
'max_reviews': None, # Options: 0 to any integer | default: None (all)
'output_file': output_file
}
if __name__ == "__main__":
start_time = time.time()
processor = Processor(settings=settings)
processor.run()
print("--- %s seconds ---" % (time.time() - start_time)) | [
"scripts.processing.Processor",
"time.time",
"argparse.ArgumentParser"
] | [((79, 104), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (102, 104), False, 'import argparse\n'), ((756, 767), 'time.time', 'time.time', ([], {}), '()\n', (765, 767), False, 'import time\n'), ((785, 813), 'scripts.processing.Processor', 'Processor', ([], {'settings': 'settings'}), '(settings=settings)\n', (794, 813), False, 'from scripts.processing import Processor\n'), ((869, 880), 'time.time', 'time.time', ([], {}), '()\n', (878, 880), False, 'import time\n')] |
#!/usr/bin/env python3
from joblib import Parallel, delayed
import os
import sys
from pathlib import Path
from typing import Dict, List
import fire
from logless import get_logger, logged, logged_block
import runnow
from tqdm import tqdm
import uio
code_file = os.path.realpath(__file__)
repo_dir = os.path.dirname(os.path.dirname(os.path.dirname(code_file)))
sys.path.append(os.path.join(repo_dir, "src"))
sys.path.append(os.path.dirname(code_file))
DEBUG = False
logging = get_logger("slalom.dataops.infra", debug=DEBUG)
SPECIAL_CASE_WORDS = ["AWS", "ECR", "ECS", "IAM", "VPC", "DBT", "EC2", "RDS", "MySQL"]
def _proper(str: str, title_case=True, special_case_words=None):
"""
Return the same string in proper case, respected override rules for
acronyms and special-cased words.
"""
special_case_words = special_case_words or SPECIAL_CASE_WORDS
word_lookup = {w.lower(): w for w in special_case_words}
if title_case:
str = str.title()
words = str.split(" ")
new_words = []
for word in words:
new_subwords = []
for subword in word.split("-"):
new_subwords.append(word_lookup.get(subword.lower(), subword))
new_word = "-".join(new_subwords)
new_words.append(new_word)
return " ".join(new_words)
def _update_var_output(output_var):
return_code, output = runnow.run(f"terraform output {output_var}", echo=False)
uio.create_text_file(os.path.join("outputs", output_var), contents=output)
return True
@logged("updating output files")
def update_var_outputs(infra_dir, output_vars=[]):
outputs_dir = os.path.join(infra_dir, "outputs")
uio.create_folder(outputs_dir)
for oldfile in uio.list_local_files(outputs_dir, recursive=False):
uio.delete_file(oldfile)
results = Parallel(n_jobs=40, verbose=2)(
delayed(_update_var_output)(outvar)
for outvar in tqdm(output_vars, "Saving output to infra/outputs")
)
def install(*args, infra_dir="./infra", deploy=False, git_ref="master"):
"""
Usage example:
```
s-infra install catalog:aws-prereqs --infra_dir=infra/prereqs --deploy=True
s-infra install samples:aws --infra_dir=infra --deploy=True
```
Which is identical to:
```
s-infra install catalog:aws-prereqs --infra_dir=infra/prereqs
s-infra init+apply --infra_dir=infra/prereqs
s-infra install samples:aws --infra_dir=infra
s-infra init+apply --infra_dir=infra
```
"""
uio.create_folder(infra_dir)
for arg in args:
with logged_block(f"installing terraform modules from '{arg}'"):
infra_type, infra_name = arg.split(":")
if infra_type not in ["catalog", "samples"]:
raise ValueError(
f"Expected infra_type to be one of: 'catalog', 'samples'. Received type: {infra_type}"
)
uio.download_folder(
remote_folder=f"git://github.com/slalom-ggp/dataops-infra#{git_ref}//{infra_type}/{infra_name}",
local_folder=infra_dir,
)
lf = "\n"
logging.info(f"List of installed modules:\n{lf.join(uio.ls(infra_dir))}")
init(infra_dir=infra_dir)
if deploy:
apply(infra_dir=infra_dir)
@logged("initializing terraform project at '{infra_dir}'")
def init(infra_dir: str = "./infra/"):
infra_dir = os.path.realpath(infra_dir)
runnow.run("terraform init", working_dir=infra_dir)
@logged("applying terraform changes")
def apply(infra_dir: str = "./infra/", save_output: bool = False, prompt: bool = False):
infra_dir = os.path.realpath(infra_dir)
runnow.run(
f"terraform apply {'' if prompt else '-auto-approve'}", working_dir=infra_dir
)
if save_output:
update_var_outputs(infra_dir=infra_dir)
def init_and_apply(infra_dir: str = "./infra/", save_output: bool = False):
infra_dir = os.path.realpath(infra_dir)
init(infra_dir=infra_dir)
apply(infra_dir=infra_dir, save_output=save_output, prompt=False)
DOCS_HEADER = """
# {module_title}
`{module_path}`
## Overview
"""
# TODO: inject into footer:
# ## Import Template
# Copy-paste the below to get started with this module in your own project:
# ```hcl
# module "{clean_name}" {
# source = "git::{git_repo}/{module_path}?ref=master"
# // ...
# }
# ```
DOCS_FOOTER = """
---------------------
## Source Files
_Source code for this module is available using the links below._
{src}
---------------------
_**NOTE:** This documentation was auto-generated using
`terraform-docs` and `s-infra` from `slalom.dataops`.
Please do not attempt to manually update this file._
"""
def update_module_docs(
tf_dir: str,
*,
recursive: bool = True,
readme: str = "README.md",
footer: bool = True,
header: bool = True,
special_case_words: List[str] = None,
extra_docs_names: List[str] = ["USAGE.md", "NOTES.md"],
git_repo: str = "https://github.com/slalom-ggp/dataops-infra",
):
"""
Replace all README.md files with auto-generated documentation, a wrapper
around the `terraform-docs` tool.
Parameters:
----------
tf_dir: Directory of terraform scripts to document.
recursive : Optional (default=True). 'True' to run on all subdirectories, recursively.
readme : Optional (default="README.md"). The filename to create when generating docs.
footnote: Optional (default=True). 'True' to include the standard footnote.
special_case_words: Optional. A list of words to override special casing rules.
extra_docs_names: (Optional.) A list of filenames which, if found, will be appended
to each module's README.md file.
git_repo: Optional. The git repo path to use in rendering 'source' paths.
Returns:
-------
None
"""
markdown_text = ""
if ".git" not in tf_dir and ".terraform" not in tf_dir:
tf_files = [
x for x in uio.list_local_files(tf_dir, recursive=False) if x.endswith(".tf")
]
extra_docs = [
x
for x in uio.list_local_files(tf_dir, recursive=False)
if extra_docs_names and os.path.basename(x) in extra_docs_names
]
if tf_files:
module_title = _proper(
os.path.basename(tf_dir), special_case_words=special_case_words
)
parent_dir_name = os.path.basename(Path(tf_dir).parent)
if parent_dir_name != ".":
module_title = _proper(
f"{parent_dir_name} {module_title}",
special_case_words=special_case_words,
)
module_path = tf_dir.replace(".", "").replace("//", "/").replace("\\", "/")
_, markdown_output = runnow.run(
f"terraform-docs md --no-providers --sort-by-required {tf_dir}",
echo=False,
)
if header:
markdown_text += DOCS_HEADER.format(
module_title=module_title, module_path=module_path
)
markdown_text += markdown_output
for extra_file in extra_docs:
markdown_text += uio.get_text_file_contents(extra_file) + "\n"
if footer:
markdown_text += DOCS_FOOTER.format(
src="\n".join(
[
"* [{file}]({repo}/tree/master/{dir}/{file})".format(
repo=git_repo,
dir=module_path,
file=os.path.basename(tf_file),
)
for tf_file in tf_files
]
)
)
uio.create_text_file(f"{tf_dir}/{readme}", markdown_text)
if recursive:
for folder in uio.list_local_files(tf_dir, recursive=False):
if os.path.isdir(folder):
update_module_docs(folder, recursive=recursive, readme=readme)
def get_tf_metadata(
tf_dir: str, recursive: bool = False,
):
"""
Return a dictionary of Terraform module paths to JSON metadata about each module,
a wrapper around the `terraform-docs` tool.
Parameters:
----------
tf_dir: Directory of terraform scripts to scan.
recursive : Optional (default=True). 'True' to run on all subdirectories, recursively.
Returns:
-------
dict
"""
import json
result = {}
if (
".git" not in tf_dir
and ".terraform" not in tf_dir
and "samples" not in tf_dir
and "tests" not in tf_dir
):
if [
x for x in uio.list_local_files(tf_dir, recursive=False) if x.endswith(".tf")
]:
_, json_text = runnow.run(f"terraform-docs json {tf_dir}", echo=False)
result[tf_dir] = json.loads(json_text)
if recursive:
for folder in uio.list_local_files(tf_dir, recursive=False):
folder = folder.replace("\\", "/")
if os.path.isdir(folder):
result.update(get_tf_metadata(folder, recursive=recursive))
return result
def check_tf_metadata(
tf_dir,
recursive: bool = True,
check_module_headers: bool = True,
check_input_descriptions: bool = True,
check_output_descriptions: bool = True,
required_input_vars: list = ["name_prefix", "resource_tags", "environment"],
required_output_vars: list = ["summary"],
raise_error=True,
abspath=False,
):
"""
Return a dictionary of reference paths to error messages and a dictionary
of errors to reference paths.
"""
def _log_issue(module_path, issue_desc, details_list):
if details_list:
if issue_desc in error_locations:
error_locations[issue_desc].extend(details_list)
else:
error_locations[issue_desc] = details_list
error_locations: Dict[str, List[str]] = {}
with logged_block("checking Terraform modules against repository code standards"):
modules_metadata = get_tf_metadata(tf_dir, recursive=recursive)
for module_path, metadata in modules_metadata.items():
if abspath:
path_sep = os.path.sep
module_path = os.path.abspath(module_path)
module_path = module_path.replace("\\", path_sep).replace("/", path_sep)
else:
path_sep = "/"
if check_module_headers and not metadata["header"]:
_log_issue(
module_path,
"1. Blank module headers",
[f"{module_path}{path_sep}main.tf"],
)
if required_input_vars:
issue_details = [
f"{module_path}{path_sep}variables.tf:var.{required_input}"
for required_input in required_input_vars
if required_input
not in [var["name"] for var in metadata.get("inputs", {})]
]
_log_issue(
module_path, "2. Missing required input variables", issue_details
)
if required_output_vars:
issue_details = [
f"{module_path}{path_sep}outputs.tf:output.{required_output}"
for required_output in required_output_vars
if required_output
not in [var["name"] for var in metadata.get("outputs", {})]
]
_log_issue(
module_path, "3. Missing required output variables", issue_details
)
if check_input_descriptions:
issue_details = [
f"{module_path}{path_sep}variables.tf:var.{var['name']}"
for var in metadata.get("inputs", {})
if not var.get("description")
]
_log_issue(
module_path, "4. Missing input variable descriptions", issue_details
)
if check_output_descriptions:
issue_details = [
f"{module_path}{path_sep}outputs.tf:output.{var['name']}"
for var in metadata.get("outputs", {})
if not var.get("description")
]
_log_issue(
module_path, "5. Missing output variable descriptions", issue_details
)
result_str = "\n".join(
[
f"\n{k}:\n - [ ] " + ("\n - [ ] ".join(error_locations[k]))
for k in sorted(error_locations.keys())
]
)
if raise_error and error_locations:
raise ValueError(f"One or more validation errors occurred.\n{result_str}")
return result_str
def change_upstream_source(
dir_to_update=".",
git_repo="https://github.com/slalom-ggp/dataops-infra",
branch="master",
relative_path="../../dataops-infra",
to_relative=False,
to_git=False,
dry_run=False,
):
"""Change Terraform source"""
if to_relative and to_git or not (to_relative or to_git):
raise ValueError("Must specify `--to_git` or `--to_relative`, but not both.")
for tf_file in uio.list_local_files(dir_to_update, recursive=False):
if tf_file.endswith(".tf"):
# print(tf_file)
new_lines = []
for line in uio.get_text_file_contents(tf_file).splitlines():
new_line = line
if line.lstrip().startswith("source "):
current_path = line.lstrip().split('"')[1]
start_pos = max(
[current_path.find("catalog/"), current_path.find("components/")]
)
if start_pos > 0:
module_path = current_path[start_pos:].split("?ref=")[0]
if to_relative:
local_patten = "{relative_path}/{path}"
new_path = local_patten.format(
relative_path=relative_path, path=module_path
)
elif to_git:
git_pattern = "git::{git_repo}//{path}?ref={branch}"
new_path = git_pattern.format(
git_repo=git_repo, path=module_path, branch=branch
)
if current_path == new_path:
print(f"{current_path} \n\t\t\t-> (unchanged)")
else:
print(f"{current_path} \n\t\t\t-> {new_path}")
new_line = f' source = "{new_path}"'
new_lines.append(new_line)
new_file_text = "\n".join(new_lines)
if dry_run:
print(f"\n\n------------\n-- {tf_file}\n------------")
print(new_file_text)
else:
uio.create_text_file(tf_file, new_file_text)
if not dry_run:
runnow.run("terraform fmt -recursive", dir_to_update)
def main():
fire.Fire(
{
"install": install,
"init": init,
"apply": apply,
"init+apply": init_and_apply,
"deploy": init_and_apply,
"change_upstream_source": change_upstream_source,
"update_module_docs": update_module_docs,
"get_tf_metadata": get_tf_metadata,
"check_tf_metadata": check_tf_metadata,
}
)
if __name__ == "__main__":
main()
| [
"uio.delete_file",
"uio.create_text_file",
"fire.Fire",
"logless.get_logger",
"logless.logged",
"uio.ls",
"logless.logged_block",
"pathlib.Path",
"os.path.isdir",
"runnow.run",
"json.loads",
"os.path.dirname",
"uio.create_folder",
"uio.get_text_file_contents",
"uio.list_local_files",
"... | [((262, 288), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (278, 288), False, 'import os\n'), ((477, 524), 'logless.get_logger', 'get_logger', (['"""slalom.dataops.infra"""'], {'debug': 'DEBUG'}), "('slalom.dataops.infra', debug=DEBUG)\n", (487, 524), False, 'from logless import get_logger, logged, logged_block\n'), ((1515, 1546), 'logless.logged', 'logged', (['"""updating output files"""'], {}), "('updating output files')\n", (1521, 1546), False, 'from logless import get_logger, logged, logged_block\n'), ((3249, 3306), 'logless.logged', 'logged', (['"""initializing terraform project at \'{infra_dir}\'"""'], {}), '("initializing terraform project at \'{infra_dir}\'")\n', (3255, 3306), False, 'from logless import get_logger, logged, logged_block\n'), ((3449, 3485), 'logless.logged', 'logged', (['"""applying terraform changes"""'], {}), "('applying terraform changes')\n", (3455, 3485), False, 'from logless import get_logger, logged, logged_block\n'), ((377, 406), 'os.path.join', 'os.path.join', (['repo_dir', '"""src"""'], {}), "(repo_dir, 'src')\n", (389, 406), False, 'import os\n'), ((424, 450), 'os.path.dirname', 'os.path.dirname', (['code_file'], {}), '(code_file)\n', (439, 450), False, 'import os\n'), ((1360, 1416), 'runnow.run', 'runnow.run', (['f"""terraform output {output_var}"""'], {'echo': '(False)'}), "(f'terraform output {output_var}', echo=False)\n", (1370, 1416), False, 'import runnow\n'), ((1616, 1650), 'os.path.join', 'os.path.join', (['infra_dir', '"""outputs"""'], {}), "(infra_dir, 'outputs')\n", (1628, 1650), False, 'import os\n'), ((1655, 1685), 'uio.create_folder', 'uio.create_folder', (['outputs_dir'], {}), '(outputs_dir)\n', (1672, 1685), False, 'import uio\n'), ((1705, 1755), 'uio.list_local_files', 'uio.list_local_files', (['outputs_dir'], {'recursive': '(False)'}), '(outputs_dir, recursive=False)\n', (1725, 1755), False, 'import uio\n'), ((2483, 2511), 'uio.create_folder', 'uio.create_folder', (['infra_dir'], {}), '(infra_dir)\n', (2500, 2511), False, 'import uio\n'), ((3362, 3389), 'os.path.realpath', 'os.path.realpath', (['infra_dir'], {}), '(infra_dir)\n', (3378, 3389), False, 'import os\n'), ((3394, 3445), 'runnow.run', 'runnow.run', (['"""terraform init"""'], {'working_dir': 'infra_dir'}), "('terraform init', working_dir=infra_dir)\n", (3404, 3445), False, 'import runnow\n'), ((3591, 3618), 'os.path.realpath', 'os.path.realpath', (['infra_dir'], {}), '(infra_dir)\n', (3607, 3618), False, 'import os\n'), ((3623, 3716), 'runnow.run', 'runnow.run', (['f"""terraform apply {\'\' if prompt else \'-auto-approve\'}"""'], {'working_dir': 'infra_dir'}), '(f"terraform apply {\'\' if prompt else \'-auto-approve\'}",\n working_dir=infra_dir)\n', (3633, 3716), False, 'import runnow\n'), ((3889, 3916), 'os.path.realpath', 'os.path.realpath', (['infra_dir'], {}), '(infra_dir)\n', (3905, 3916), False, 'import os\n'), ((13239, 13291), 'uio.list_local_files', 'uio.list_local_files', (['dir_to_update'], {'recursive': '(False)'}), '(dir_to_update, recursive=False)\n', (13259, 13291), False, 'import uio\n'), ((15143, 15445), 'fire.Fire', 'fire.Fire', (["{'install': install, 'init': init, 'apply': apply, 'init+apply':\n init_and_apply, 'deploy': init_and_apply, 'change_upstream_source':\n change_upstream_source, 'update_module_docs': update_module_docs,\n 'get_tf_metadata': get_tf_metadata, 'check_tf_metadata': check_tf_metadata}"], {}), "({'install': install, 'init': init, 'apply': apply, 'init+apply':\n init_and_apply, 'deploy': init_and_apply, 'change_upstream_source':\n change_upstream_source, 'update_module_docs': update_module_docs,\n 'get_tf_metadata': get_tf_metadata, 'check_tf_metadata': check_tf_metadata}\n )\n", (15152, 15445), False, 'import fire\n'), ((332, 358), 'os.path.dirname', 'os.path.dirname', (['code_file'], {}), '(code_file)\n', (347, 358), False, 'import os\n'), ((1442, 1477), 'os.path.join', 'os.path.join', (['"""outputs"""', 'output_var'], {}), "('outputs', output_var)\n", (1454, 1477), False, 'import os\n'), ((1765, 1789), 'uio.delete_file', 'uio.delete_file', (['oldfile'], {}), '(oldfile)\n', (1780, 1789), False, 'import uio\n'), ((1804, 1834), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': '(40)', 'verbose': '(2)'}), '(n_jobs=40, verbose=2)\n', (1812, 1834), False, 'from joblib import Parallel, delayed\n'), ((7842, 7887), 'uio.list_local_files', 'uio.list_local_files', (['tf_dir'], {'recursive': '(False)'}), '(tf_dir, recursive=False)\n', (7862, 7887), False, 'import uio\n'), ((8909, 8954), 'uio.list_local_files', 'uio.list_local_files', (['tf_dir'], {'recursive': '(False)'}), '(tf_dir, recursive=False)\n', (8929, 8954), False, 'import uio\n'), ((9955, 10031), 'logless.logged_block', 'logged_block', (['"""checking Terraform modules against repository code standards"""'], {}), "('checking Terraform modules against repository code standards')\n", (9967, 10031), False, 'from logless import get_logger, logged, logged_block\n'), ((15071, 15124), 'runnow.run', 'runnow.run', (['"""terraform fmt -recursive"""', 'dir_to_update'], {}), "('terraform fmt -recursive', dir_to_update)\n", (15081, 15124), False, 'import runnow\n'), ((2546, 2604), 'logless.logged_block', 'logged_block', (['f"""installing terraform modules from \'{arg}\'"""'], {}), '(f"installing terraform modules from \'{arg}\'")\n', (2558, 2604), False, 'from logless import get_logger, logged, logged_block\n'), ((2886, 3036), 'uio.download_folder', 'uio.download_folder', ([], {'remote_folder': 'f"""git://github.com/slalom-ggp/dataops-infra#{git_ref}//{infra_type}/{infra_name}"""', 'local_folder': 'infra_dir'}), "(remote_folder=\n f'git://github.com/slalom-ggp/dataops-infra#{git_ref}//{infra_type}/{infra_name}'\n , local_folder=infra_dir)\n", (2905, 3036), False, 'import uio\n'), ((6739, 6830), 'runnow.run', 'runnow.run', (['f"""terraform-docs md --no-providers --sort-by-required {tf_dir}"""'], {'echo': '(False)'}), "(f'terraform-docs md --no-providers --sort-by-required {tf_dir}',\n echo=False)\n", (6749, 6830), False, 'import runnow\n'), ((7744, 7801), 'uio.create_text_file', 'uio.create_text_file', (['f"""{tf_dir}/{readme}"""', 'markdown_text'], {}), "(f'{tf_dir}/{readme}', markdown_text)\n", (7764, 7801), False, 'import uio\n'), ((7904, 7925), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (7917, 7925), False, 'import os\n'), ((8762, 8817), 'runnow.run', 'runnow.run', (['f"""terraform-docs json {tf_dir}"""'], {'echo': '(False)'}), "(f'terraform-docs json {tf_dir}', echo=False)\n", (8772, 8817), False, 'import runnow\n'), ((8847, 8868), 'json.loads', 'json.loads', (['json_text'], {}), '(json_text)\n', (8857, 8868), False, 'import json\n'), ((9018, 9039), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (9031, 9039), False, 'import os\n'), ((1844, 1871), 'joblib.delayed', 'delayed', (['_update_var_output'], {}), '(_update_var_output)\n', (1851, 1871), False, 'from joblib import Parallel, delayed\n'), ((1902, 1953), 'tqdm.tqdm', 'tqdm', (['output_vars', '"""Saving output to infra/outputs"""'], {}), "(output_vars, 'Saving output to infra/outputs')\n", (1906, 1953), False, 'from tqdm import tqdm\n'), ((5919, 5964), 'uio.list_local_files', 'uio.list_local_files', (['tf_dir'], {'recursive': '(False)'}), '(tf_dir, recursive=False)\n', (5939, 5964), False, 'import uio\n'), ((6054, 6099), 'uio.list_local_files', 'uio.list_local_files', (['tf_dir'], {'recursive': '(False)'}), '(tf_dir, recursive=False)\n', (6074, 6099), False, 'import uio\n'), ((6259, 6283), 'os.path.basename', 'os.path.basename', (['tf_dir'], {}), '(tf_dir)\n', (6275, 6283), False, 'import os\n'), ((8657, 8702), 'uio.list_local_files', 'uio.list_local_files', (['tf_dir'], {'recursive': '(False)'}), '(tf_dir, recursive=False)\n', (8677, 8702), False, 'import uio\n'), ((10261, 10289), 'os.path.abspath', 'os.path.abspath', (['module_path'], {}), '(module_path)\n', (10276, 10289), False, 'import os\n'), ((14998, 15042), 'uio.create_text_file', 'uio.create_text_file', (['tf_file', 'new_file_text'], {}), '(tf_file, new_file_text)\n', (15018, 15042), False, 'import uio\n'), ((3144, 3161), 'uio.ls', 'uio.ls', (['infra_dir'], {}), '(infra_dir)\n', (3150, 3161), False, 'import uio\n'), ((6384, 6396), 'pathlib.Path', 'Path', (['tf_dir'], {}), '(tf_dir)\n', (6388, 6396), False, 'from pathlib import Path\n'), ((7159, 7197), 'uio.get_text_file_contents', 'uio.get_text_file_contents', (['extra_file'], {}), '(extra_file)\n', (7185, 7197), False, 'import uio\n'), ((13409, 13444), 'uio.get_text_file_contents', 'uio.get_text_file_contents', (['tf_file'], {}), '(tf_file)\n', (13435, 13444), False, 'import uio\n'), ((6136, 6155), 'os.path.basename', 'os.path.basename', (['x'], {}), '(x)\n', (6152, 6155), False, 'import os\n'), ((7557, 7582), 'os.path.basename', 'os.path.basename', (['tf_file'], {}), '(tf_file)\n', (7573, 7582), False, 'import os\n')] |
"""
:copyright: © 2019, <NAME>
:license: Apache License 2.0
"""
from urllib.parse import quote_plus
import requests
from pyquery import PyQuery as pq
from .mobilizer import Mobilizer
class InstapaperMobilizer(Mobilizer):
"""From a URL, get an Instapaper mobilizered HTML"""
mobilizer_url = "http://www.instapaper.com/text?u={encoded_url}"
def fetch(self, url):
mobilizer_url = self.mobilizer_url.format(
encoded_url=quote_plus(url.encode("utf-8"))
)
self.log.info("Downloading instapaperized {!r}".format(url))
r = requests.get(mobilizer_url)
self.log.debug("GET {url!r} returned {0.status_code}".format(r, url=url))
if r.status_code != 200:
raise Exception("GET {url!r} returned {0.status_code}".format(r, url=url))
d = pq(r.content)
return dict(url=url, body=d("#story"), title=d("title").text())
| [
"pyquery.PyQuery",
"requests.get"
] | [((581, 608), 'requests.get', 'requests.get', (['mobilizer_url'], {}), '(mobilizer_url)\n', (593, 608), False, 'import requests\n'), ((824, 837), 'pyquery.PyQuery', 'pq', (['r.content'], {}), '(r.content)\n', (826, 837), True, 'from pyquery import PyQuery as pq\n')] |
# ===========================================================================
# imgcv.py ----------------------------------------------------------------
# ===========================================================================
# import ------------------------------------------------------------------
# ---------------------------------------------------------------------------
import rsvis.utils.imgtools as imgtools
import rsvis.utils.logger
import logging
import numpy as np
from PIL import Image, ImageTk
from tkinter import Canvas, NW
# class -------------------------------------------------------------------
# ---------------------------------------------------------------------------
class ImgCanvas(Canvas):
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def __init__(
self,
parent,
shift=[4,4],
sensitivity = 4,
logger=None,
**kwargs
):
super(ImgCanvas, self).__init__(parent)
self.bind("<Configure>", self.resize_image)
self._mask = [None]
self._mask_alpha = [150]
self._mask_color = [[0,0,0]]
self._mask_invert = [False]
self._shift = shift
self._scale = [1.0, 1.0]
self.set_size([self.winfo_reqwidth(), self.winfo_reqheight()])
self._parent = parent
self._logger = rsvis.utils.logger.Logger(logger=logger)
# key bindings ----------------------------------------------------
self._mouse_sensitivity = 4
self._mouse_box = [0, 0, 0, 0]
self._mouse_point = [0, 0]
self._mouse_event = [0, 0]
self._mouse_img = [0, 0]
self._keys = dict()
self.bind("<Button-1>", self.mouse_button_1_pressed)
self.bind("<ButtonRelease-1>", self.mouse_button_1_released)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def clear(self, **kwargs):
pass
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_keys(self, **kwargs):
return self._keys
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_logger(self):
return self._logger
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def resize_image(self, event):
# determine the ratio of old width/height to new width/height
event_size = [event.width, event.height] #####################
self._scale = [float(e)/s for e, s in zip(event_size, self._size)]
self.set_size(event_size)
# resize the canvas
self.config(width=self._size[0], height=self._size[1]) #################
# rescale all the objects tagged with the "all" tag
self.scale("all", 0, 0, self._scale[0], self._scale[1]) ################
self.create_image()
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def resize_boxes(self, boxes, inversion=False):
scale = [float(s)/i for s, i in zip(self.get_size(), self._img_size)]
if inversion:
scale = [1/s for s in scale]
boxes = boxes if isinstance(boxes[0], list) and len(boxes[0]) !=2 else [boxes]
return [self.resize_bbox(box, scale) for box in boxes]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def resize_bbox(self, box, scale):
if len(box)==4:
return [
int(box[0]*scale[1]), int(box[1]*scale[1]),
int(box[2]*scale[0]), int(box[3]*scale[0])
]
else:
return [[int(n[0] *scale[0]), int(n[1]*scale[1])] for n in box ]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def resize_points(self, points, inversion=False):
scale = [float(s)/i for s, i in zip(self.get_size(), self._img_size)]
if inversion:
scale = [1/s for s in scale]
points = points if isinstance(points[0], list) else [points]
return [self.resize_point(point, scale) for point in points]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def resize_point(self, point, scale):
return [int(point[0]*scale[1]), int(point[1]*scale[0])]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def resize_event(self, event):
ev = [event.y, event.x]
ev[0] = ev[0] if ev[0] >= 0 else 0
ev[0] = ev[0] if ev[0] < self._img_draw.size[1] else self._img_draw.size[1]-1
ev[1] = ev[1] if ev[1] >= 0 else 0
ev[1] = ev[1] if ev[1] < self._img_draw.size[0] else self._img_draw.size[0]-1
return ev
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_event_box(self, event):
return [
min([self._mouse_point[0], self._mouse_event[0]]),
max([self._mouse_point[0], self._mouse_event[0]]),
min([self._mouse_point[1], self._mouse_event[1]]),
max([self._mouse_point[1], self._mouse_event[1]])
]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def set_img(self, img, clear_mask=True):
if not isinstance(img, np.ndarray):
return
self._img_size = [img.shape[1], img.shape[0]]
self._data_img = imgtools.expand_image_dim(img)
if not isinstance(img.dtype, np.uint8):
img = imgtools.project_and_stack(img, dtype=np.uint8, factor=255)
self._img = Image.fromarray(img)
if clear_mask:
self.set_mask(show=False)
self.create_image()
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def set_mask(self, mask=None, show=True, alpha=150, color=[0,0,0], invert=False):
self._mask = mask if isinstance(mask, list) else [mask]
self._mask_alpha = alpha if isinstance(alpha, list) else [alpha]
self._mask_color = color if isinstance(color[0], list) else [color]
self._mask_invert= invert if isinstance(invert, list) else [invert]
if show:
self.create_image()
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_mask(self, index=None, resize=False):
if index is None:
mask = self._mask[0]
for idx in range(1, len(self._mask)):
if isinstance(self._mask[idx], np.ndarray):
mask = np.where(np.logical_and(mask, self._mask[idx]), 1, 0).astype(np.uint8)
return mask
else:
if isinstance(self._mask[index], np.ndarray):
return np.asarray(Image.fromarray(self._mask[index]).resize(self.get_size())) if resize else self._mask[index]
else:
return self._mask[index]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def is_mouse_event(self, bbox):
if not (bbox[1]-bbox[0] > self._mouse_sensitivity and bbox[3]-bbox[2] > self._mouse_sensitivity):
return False
return True
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_img(self, show=False):
if show:
return np.asarray(self._img).copy()
return self._data_img.copy()
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def set_size(self, size):
self._size = [s - sh for s, sh in zip(size, self._shift)]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_size(self):
return [s + sh for s, sh in zip(self._size, self._shift)]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_shape(self):
size = self.get_size()
return (size[1], size[0], 3)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_intial_draw_image(self):
return np.zeros(self.get_shape(), dtype=np.int16) - 1
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def create_image(self, **kwargs):
self._img_draw = self._img.resize(self.get_size())
if isinstance(self._mask[0], np.ndarray):
for idx, (mask, color, alpha, invert) in enumerate(zip(self._mask, self._mask_color, self._mask_alpha, self._mask_invert)):
mask = self.get_mask(index=idx, resize=True)
mask = mask if not invert else imgtools.invert_bool_img(mask)
mask = Image.fromarray(
imgtools.get_transparent_image(
imgtools.bool_to_img(mask, value=-1, dtype=np.int16, color=color, factor=255),
value=alpha
)
)
self._img_draw.paste(mask, (0, 0), mask)
image = Image.fromarray(
imgtools.get_transparent_image(self.draw_image(), value=200))
self._img_draw.paste(image, (0, 0), image)
self._img_canvas = ImageTk.PhotoImage(image=self._img_draw)
self._img_on_canvas = super(ImgCanvas, self).create_image(0, 0, image=self._img_canvas, anchor=NW)
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def draw_image(self, **kwargs):
img_assembly = self.get_intial_draw_image()
return img_assembly
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def mouse_button_1_pressed(self, event):
self.focus_set()
self._mouse_event = self.resize_event(event)
self._mouse_point = [self._mouse_event[0], self._mouse_event[1]]
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def get_roi(self):
if sum(self._mouse_box):
roi_xy = self.resize_boxes(self._mouse_box, inversion=True)[0]
roi = [roi_xy[2], roi_xy[0], roi_xy[3]-roi_xy[2], roi_xy[1]-roi_xy[0]]
else:
roi = [0, 0, self._data_img.shape[1]-1, self._data_img.shape[0]-1]
return roi
# method --------------------------------------------------------------
# -----------------------------------------------------------------------
def mouse_button_1_released(self, event):
self.focus_set()
self._mouse_event = self.resize_event(event)
self._mouse_box = self.get_event_box(event)
self._mouse_img = self.resize_points(self._mouse_event, inversion=True)[0]
self._logger("[MOUSE] Pixel: {}, Value: {}".format(self._mouse_img,
self._data_img[self._mouse_img[0], self._mouse_img[1], :]
)
) | [
"rsvis.utils.imgtools.expand_image_dim",
"PIL.Image.fromarray",
"numpy.logical_and",
"rsvis.utils.imgtools.project_and_stack",
"numpy.asarray",
"rsvis.utils.imgtools.invert_bool_img",
"rsvis.utils.imgtools.bool_to_img",
"PIL.ImageTk.PhotoImage"
] | [((6408, 6438), 'rsvis.utils.imgtools.expand_image_dim', 'imgtools.expand_image_dim', (['img'], {}), '(img)\n', (6433, 6438), True, 'import rsvis.utils.imgtools as imgtools\n'), ((6594, 6614), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (6609, 6614), False, 'from PIL import Image, ImageTk\n'), ((10803, 10843), 'PIL.ImageTk.PhotoImage', 'ImageTk.PhotoImage', ([], {'image': 'self._img_draw'}), '(image=self._img_draw)\n', (10821, 10843), False, 'from PIL import Image, ImageTk\n'), ((6505, 6564), 'rsvis.utils.imgtools.project_and_stack', 'imgtools.project_and_stack', (['img'], {'dtype': 'np.uint8', 'factor': '(255)'}), '(img, dtype=np.uint8, factor=255)\n', (6531, 6564), True, 'import rsvis.utils.imgtools as imgtools\n'), ((8628, 8649), 'numpy.asarray', 'np.asarray', (['self._img'], {}), '(self._img)\n', (8638, 8649), True, 'import numpy as np\n'), ((10249, 10279), 'rsvis.utils.imgtools.invert_bool_img', 'imgtools.invert_bool_img', (['mask'], {}), '(mask)\n', (10273, 10279), True, 'import rsvis.utils.imgtools as imgtools\n'), ((10396, 10473), 'rsvis.utils.imgtools.bool_to_img', 'imgtools.bool_to_img', (['mask'], {'value': '(-1)', 'dtype': 'np.int16', 'color': 'color', 'factor': '(255)'}), '(mask, value=-1, dtype=np.int16, color=color, factor=255)\n', (10416, 10473), True, 'import rsvis.utils.imgtools as imgtools\n'), ((7712, 7749), 'numpy.logical_and', 'np.logical_and', (['mask', 'self._mask[idx]'], {}), '(mask, self._mask[idx])\n', (7726, 7749), True, 'import numpy as np\n'), ((7904, 7938), 'PIL.Image.fromarray', 'Image.fromarray', (['self._mask[index]'], {}), '(self._mask[index])\n', (7919, 7938), False, 'from PIL import Image, ImageTk\n')] |
# -*- coding: utf-8 -*-
# (The MIT License)
#
# Copyright (c) 2013-2021 Kura
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import logging
import os
import tempfile
import pytest
from blackhole.utils import Singleton
logging.getLogger("blackhole").addHandler(logging.NullHandler())
@pytest.fixture()
def cleandir():
newpath = tempfile.mkdtemp()
os.chdir(newpath)
@pytest.fixture()
def reset():
Singleton._instances = {}
def create_config(data):
cwd = os.getcwd()
path = os.path.join(cwd, "test.conf")
with open(path, "w") as cfile:
cfile.write("\n".join(data))
return path
def create_file(name, data=""):
cwd = os.getcwd()
path = os.path.join(cwd, name)
with open(path, "w") as ffile:
ffile.write(str(data))
return path
class Args(object):
def __init__(self, args=None):
if args is not None:
for arg in args:
setattr(self, arg[0], arg[1])
| [
"logging.NullHandler",
"logging.getLogger",
"os.path.join",
"os.getcwd",
"os.chdir",
"tempfile.mkdtemp",
"pytest.fixture"
] | [((1302, 1318), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1316, 1318), False, 'import pytest\n'), ((1393, 1409), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1407, 1409), False, 'import pytest\n'), ((1276, 1297), 'logging.NullHandler', 'logging.NullHandler', ([], {}), '()\n', (1295, 1297), False, 'import logging\n'), ((1349, 1367), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (1365, 1367), False, 'import tempfile\n'), ((1372, 1389), 'os.chdir', 'os.chdir', (['newpath'], {}), '(newpath)\n', (1380, 1389), False, 'import os\n'), ((1490, 1501), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1499, 1501), False, 'import os\n'), ((1513, 1543), 'os.path.join', 'os.path.join', (['cwd', '"""test.conf"""'], {}), "(cwd, 'test.conf')\n", (1525, 1543), False, 'import os\n'), ((1676, 1687), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1685, 1687), False, 'import os\n'), ((1699, 1722), 'os.path.join', 'os.path.join', (['cwd', 'name'], {}), '(cwd, name)\n', (1711, 1722), False, 'import os\n'), ((1234, 1264), 'logging.getLogger', 'logging.getLogger', (['"""blackhole"""'], {}), "('blackhole')\n", (1251, 1264), False, 'import logging\n')] |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
pytest.importorskip("ethosu.vela")
import tvm
import tvm.script
from tvm.script import tir
from tvm import relay
from tvm.relay.testing import run_opt_pass
from tvm.relay.backend.contrib.ethosu.tir.compiler import lower_to_tir
from .infra import make_ethosu_conv2d
# fmt: off
@tvm.script.ir_module
class ReferenceModule:
@tir.prim_func
def main(placeholder: tir.handle, placeholder_1: tir.handle, placeholder_2: tir.handle, placeholder_3: tir.handle, placeholder_4: tir.handle, placeholder_5: tir.handle, placeholder_6: tir.handle, placeholder_7: tir.handle, placeholder_8: tir.handle, placeholder_9: tir.handle, T_concat: tir.handle) -> None:
# function attr dict
tir.func_attr({"from_legacy_te_schedule": True, "global_symbol": "main", "tir.noalias": True})
buffer = tir.match_buffer(placeholder_2, [2992], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
buffer_1 = tir.match_buffer(placeholder_4, [2992], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
placeholder_10 = tir.match_buffer(placeholder_1, [1, 8, 10, 16], dtype="int8", elem_offset=0, align=128, offset_factor=1)
buffer_2 = tir.match_buffer(placeholder_9, [160], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
buffer_3 = tir.match_buffer(placeholder_8, [2992], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
buffer_4 = tir.match_buffer(placeholder_5, [160], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
buffer_5 = tir.match_buffer(placeholder_6, [2992], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
T_concat_1 = tir.match_buffer(T_concat, [1, 8, 32, 16], dtype="int8", elem_offset=0, align=128, offset_factor=1)
placeholder_11 = tir.match_buffer(placeholder, [1, 8, 12, 16], dtype="int8", elem_offset=0, align=128, offset_factor=1)
buffer_6 = tir.match_buffer(placeholder_7, [160], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
buffer_7 = tir.match_buffer(placeholder_3, [160], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
# body
T_concat_2 = tir.allocate([2816], "int8", "global", annotations={"disable_lower_builtin": True})
tir.evaluate(tir.call_extern("ethosu_conv2d", "int8", 8, 10, 16, 8, 0, 10, tir.load("int8", placeholder_10.data, 0), 0, 0, 0, tir.float32(0.5), 10, "NHWC", 160, 16, 1, "int8", 8, 10, 16, 8, 0, 10, tir.load("int8", T_concat_2, 192), 0, 0, 0, tir.float32(0.25), 14, "NHWC", 352, 16, 1, 3, 3, 1, 1, 1, 1, tir.load("uint8", buffer_1.data, 0), 2992, 12, tir.load("uint8", buffer_4.data, 0), 160, 1, 1, 1, 1, "NONE", 0, 0, "TFL", "NONE", dtype="handle"))
tir.evaluate(tir.call_extern("ethosu_conv2d", "int8", 8, 10, 16, 8, 0, 10, tir.load("int8", T_concat_2, 192), 0, 0, 0, tir.float32(0.5), 10, "NHWC", 352, 16, 1, "int8", 8, 10, 16, 8, 0, 10, tir.load("int8", T_concat_1.data, 352), 0, 0, 0, tir.float32(0.25), 14, "NHWC", 512, 16, 1, 3, 3, 1, 1, 1, 1, tir.load("uint8", buffer_3.data, 0), 2992, 12, tir.load("uint8", buffer_2.data, 0), 160, 1, 1, 1, 1, "NONE", 0, 0, "TFL", "NONE", dtype="handle"))
tir.evaluate(tir.call_extern("ethosu_conv2d", "int8", 8, 12, 16, 8, 0, 12, tir.load("int8", placeholder_11.data, 0), 0, 0, 0, tir.float32(0.5), 10, "NHWC", 192, 16, 1, "int8", 8, 12, 16, 8, 0, 12, tir.load("int8", T_concat_2, 0), 0, 0, 0, tir.float32(0.25), 14, "NHWC", 352, 16, 1, 3, 3, 1, 1, 1, 1, tir.load("uint8", buffer.data, 0), 2992, 12, tir.load("uint8", buffer_7.data, 0), 160, 1, 1, 1, 1, "NONE", 0, 0, "TFL", "NONE", dtype="handle"))
tir.evaluate(tir.call_extern("ethosu_conv2d", "int8", 8, 22, 16, 8, 0, 22, tir.load("int8", T_concat_2, 0), 0, 0, 0, tir.float32(0.5), 10, "NHWC", 352, 16, 1, "int8", 8, 22, 16, 8, 0, 22, tir.load("int8", T_concat_1.data, 0), 0, 0, 0, tir.float32(0.25), 14, "NHWC", 512, 16, 1, 3, 3, 1, 1, 1, 1, tir.load("uint8", buffer_5.data, 0), 2992, 12, tir.load("uint8", buffer_6.data, 0), 160, 1, 1, 1, 1, "NONE", 0, 0, "TFL", "NONE", dtype="handle"))
__tvm_meta__ = None
# fmt: on
def test_concat():
def _get_func():
ifm1 = relay.var("ifm1", shape=(1, 8, 12, 16), dtype="int8")
ifm2 = relay.var("ifm2", shape=(1, 8, 10, 16), dtype="int8")
conv1 = make_ethosu_conv2d(ifm1, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))
conv2 = make_ethosu_conv2d(ifm2, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))
conc1 = relay.concatenate((conv1, conv2), axis=2)
conv3 = make_ethosu_conv2d(conc1, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))
conv4 = make_ethosu_conv2d(conv2, 16, 16, (3, 3), (1, 1), (1, 1), (1, 1))
conc2 = relay.concatenate((conv3, conv4), axis=2)
func = relay.Function(relay.analysis.free_vars(conc2), conc2)
func = run_opt_pass(func, relay.transform.InferType())
return func
func = _get_func()
mod, _ = lower_to_tir(func)
script = mod.script(show_meta=True)
test_mod = tvm.script.from_source(script)
reference_mod = ReferenceModule
tvm.ir.assert_structural_equal(test_mod["main"], reference_mod["main"], True)
if __name__ == "__main__":
pytest.main([__file__])
| [
"tvm.script.tir.func_attr",
"tvm.script.tir.allocate",
"tvm.script.tir.match_buffer",
"tvm.script.tir.float32",
"pytest.main",
"tvm.script.tir.load",
"tvm.relay.var",
"pytest.importorskip",
"tvm.relay.concatenate",
"tvm.relay.transform.InferType",
"tvm.ir.assert_structural_equal",
"tvm.relay.a... | [((800, 834), 'pytest.importorskip', 'pytest.importorskip', (['"""ethosu.vela"""'], {}), "('ethosu.vela')\n", (819, 834), False, 'import pytest\n'), ((5677, 5695), 'tvm.relay.backend.contrib.ethosu.tir.compiler.lower_to_tir', 'lower_to_tir', (['func'], {}), '(func)\n', (5689, 5695), False, 'from tvm.relay.backend.contrib.ethosu.tir.compiler import lower_to_tir\n'), ((5751, 5781), 'tvm.script.from_source', 'tvm.script.from_source', (['script'], {}), '(script)\n', (5773, 5781), False, 'import tvm\n'), ((5823, 5900), 'tvm.ir.assert_structural_equal', 'tvm.ir.assert_structural_equal', (["test_mod['main']", "reference_mod['main']", '(True)'], {}), "(test_mod['main'], reference_mod['main'], True)\n", (5853, 5900), False, 'import tvm\n'), ((5934, 5957), 'pytest.main', 'pytest.main', (['[__file__]'], {}), '([__file__])\n', (5945, 5957), False, 'import pytest\n'), ((1491, 1589), 'tvm.script.tir.func_attr', 'tir.func_attr', (["{'from_legacy_te_schedule': True, 'global_symbol': 'main', 'tir.noalias': True}"], {}), "({'from_legacy_te_schedule': True, 'global_symbol': 'main',\n 'tir.noalias': True})\n", (1504, 1589), False, 'from tvm.script import tir\n'), ((1603, 1705), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_2', '[2992]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_2, [2992], dtype='uint8', elem_offset=0, align\n =128, offset_factor=1)\n", (1619, 1705), False, 'from tvm.script import tir\n'), ((1720, 1822), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_4', '[2992]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_4, [2992], dtype='uint8', elem_offset=0, align\n =128, offset_factor=1)\n", (1736, 1822), False, 'from tvm.script import tir\n'), ((1843, 1951), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_1', '[1, 8, 10, 16]'], {'dtype': '"""int8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_1, [1, 8, 10, 16], dtype='int8', elem_offset=0,\n align=128, offset_factor=1)\n", (1859, 1951), False, 'from tvm.script import tir\n'), ((1967, 2068), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_9', '[160]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_9, [160], dtype='uint8', elem_offset=0, align=\n 128, offset_factor=1)\n", (1983, 2068), False, 'from tvm.script import tir\n'), ((2083, 2185), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_8', '[2992]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_8, [2992], dtype='uint8', elem_offset=0, align\n =128, offset_factor=1)\n", (2099, 2185), False, 'from tvm.script import tir\n'), ((2200, 2301), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_5', '[160]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_5, [160], dtype='uint8', elem_offset=0, align=\n 128, offset_factor=1)\n", (2216, 2301), False, 'from tvm.script import tir\n'), ((2316, 2418), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_6', '[2992]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_6, [2992], dtype='uint8', elem_offset=0, align\n =128, offset_factor=1)\n", (2332, 2418), False, 'from tvm.script import tir\n'), ((2435, 2538), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['T_concat', '[1, 8, 32, 16]'], {'dtype': '"""int8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(T_concat, [1, 8, 32, 16], dtype='int8', elem_offset=0,\n align=128, offset_factor=1)\n", (2451, 2538), False, 'from tvm.script import tir\n'), ((2560, 2666), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder', '[1, 8, 12, 16]'], {'dtype': '"""int8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder, [1, 8, 12, 16], dtype='int8', elem_offset=0,\n align=128, offset_factor=1)\n", (2576, 2666), False, 'from tvm.script import tir\n'), ((2682, 2783), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_7', '[160]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_7, [160], dtype='uint8', elem_offset=0, align=\n 128, offset_factor=1)\n", (2698, 2783), False, 'from tvm.script import tir\n'), ((2798, 2899), 'tvm.script.tir.match_buffer', 'tir.match_buffer', (['placeholder_3', '[160]'], {'dtype': '"""uint8"""', 'elem_offset': '(0)', 'align': '(128)', 'offset_factor': '(1)'}), "(placeholder_3, [160], dtype='uint8', elem_offset=0, align=\n 128, offset_factor=1)\n", (2814, 2899), False, 'from tvm.script import tir\n'), ((2931, 3018), 'tvm.script.tir.allocate', 'tir.allocate', (['[2816]', '"""int8"""', '"""global"""'], {'annotations': "{'disable_lower_builtin': True}"}), "([2816], 'int8', 'global', annotations={'disable_lower_builtin':\n True})\n", (2943, 3018), False, 'from tvm.script import tir\n'), ((4922, 4975), 'tvm.relay.var', 'relay.var', (['"""ifm1"""'], {'shape': '(1, 8, 12, 16)', 'dtype': '"""int8"""'}), "('ifm1', shape=(1, 8, 12, 16), dtype='int8')\n", (4931, 4975), False, 'from tvm import relay\n'), ((4991, 5044), 'tvm.relay.var', 'relay.var', (['"""ifm2"""'], {'shape': '(1, 8, 10, 16)', 'dtype': '"""int8"""'}), "('ifm2', shape=(1, 8, 10, 16), dtype='int8')\n", (5000, 5044), False, 'from tvm import relay\n'), ((5223, 5264), 'tvm.relay.concatenate', 'relay.concatenate', (['(conv1, conv2)'], {'axis': '(2)'}), '((conv1, conv2), axis=2)\n', (5240, 5264), False, 'from tvm import relay\n'), ((5445, 5486), 'tvm.relay.concatenate', 'relay.concatenate', (['(conv3, conv4)'], {'axis': '(2)'}), '((conv3, conv4), axis=2)\n', (5462, 5486), False, 'from tvm import relay\n'), ((5517, 5548), 'tvm.relay.analysis.free_vars', 'relay.analysis.free_vars', (['conc2'], {}), '(conc2)\n', (5541, 5548), False, 'from tvm import relay\n'), ((5591, 5618), 'tvm.relay.transform.InferType', 'relay.transform.InferType', ([], {}), '()\n', (5616, 5618), False, 'from tvm import relay\n'), ((3098, 3138), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'placeholder_10.data', '(0)'], {}), "('int8', placeholder_10.data, 0)\n", (3106, 3138), False, 'from tvm.script import tir\n'), ((3149, 3165), 'tvm.script.tir.float32', 'tir.float32', (['(0.5)'], {}), '(0.5)\n', (3160, 3165), False, 'from tvm.script import tir\n'), ((3220, 3253), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'T_concat_2', '(192)'], {}), "('int8', T_concat_2, 192)\n", (3228, 3253), False, 'from tvm.script import tir\n'), ((3264, 3281), 'tvm.script.tir.float32', 'tir.float32', (['(0.25)'], {}), '(0.25)\n', (3275, 3281), False, 'from tvm.script import tir\n'), ((3325, 3360), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer_1.data', '(0)'], {}), "('uint8', buffer_1.data, 0)\n", (3333, 3360), False, 'from tvm.script import tir\n'), ((3372, 3407), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer_4.data', '(0)'], {}), "('uint8', buffer_4.data, 0)\n", (3380, 3407), False, 'from tvm.script import tir\n'), ((3555, 3588), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'T_concat_2', '(192)'], {}), "('int8', T_concat_2, 192)\n", (3563, 3588), False, 'from tvm.script import tir\n'), ((3599, 3615), 'tvm.script.tir.float32', 'tir.float32', (['(0.5)'], {}), '(0.5)\n', (3610, 3615), False, 'from tvm.script import tir\n'), ((3670, 3708), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'T_concat_1.data', '(352)'], {}), "('int8', T_concat_1.data, 352)\n", (3678, 3708), False, 'from tvm.script import tir\n'), ((3719, 3736), 'tvm.script.tir.float32', 'tir.float32', (['(0.25)'], {}), '(0.25)\n', (3730, 3736), False, 'from tvm.script import tir\n'), ((3780, 3815), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer_3.data', '(0)'], {}), "('uint8', buffer_3.data, 0)\n", (3788, 3815), False, 'from tvm.script import tir\n'), ((3827, 3862), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer_2.data', '(0)'], {}), "('uint8', buffer_2.data, 0)\n", (3835, 3862), False, 'from tvm.script import tir\n'), ((4010, 4050), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'placeholder_11.data', '(0)'], {}), "('int8', placeholder_11.data, 0)\n", (4018, 4050), False, 'from tvm.script import tir\n'), ((4061, 4077), 'tvm.script.tir.float32', 'tir.float32', (['(0.5)'], {}), '(0.5)\n', (4072, 4077), False, 'from tvm.script import tir\n'), ((4132, 4163), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'T_concat_2', '(0)'], {}), "('int8', T_concat_2, 0)\n", (4140, 4163), False, 'from tvm.script import tir\n'), ((4174, 4191), 'tvm.script.tir.float32', 'tir.float32', (['(0.25)'], {}), '(0.25)\n', (4185, 4191), False, 'from tvm.script import tir\n'), ((4235, 4268), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer.data', '(0)'], {}), "('uint8', buffer.data, 0)\n", (4243, 4268), False, 'from tvm.script import tir\n'), ((4280, 4315), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer_7.data', '(0)'], {}), "('uint8', buffer_7.data, 0)\n", (4288, 4315), False, 'from tvm.script import tir\n'), ((4463, 4494), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'T_concat_2', '(0)'], {}), "('int8', T_concat_2, 0)\n", (4471, 4494), False, 'from tvm.script import tir\n'), ((4505, 4521), 'tvm.script.tir.float32', 'tir.float32', (['(0.5)'], {}), '(0.5)\n', (4516, 4521), False, 'from tvm.script import tir\n'), ((4576, 4612), 'tvm.script.tir.load', 'tir.load', (['"""int8"""', 'T_concat_1.data', '(0)'], {}), "('int8', T_concat_1.data, 0)\n", (4584, 4612), False, 'from tvm.script import tir\n'), ((4623, 4640), 'tvm.script.tir.float32', 'tir.float32', (['(0.25)'], {}), '(0.25)\n', (4634, 4640), False, 'from tvm.script import tir\n'), ((4684, 4719), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer_5.data', '(0)'], {}), "('uint8', buffer_5.data, 0)\n", (4692, 4719), False, 'from tvm.script import tir\n'), ((4731, 4766), 'tvm.script.tir.load', 'tir.load', (['"""uint8"""', 'buffer_6.data', '(0)'], {}), "('uint8', buffer_6.data, 0)\n", (4739, 4766), False, 'from tvm.script import tir\n')] |
# from django.core.cache import cache
from django.db.models import Sum
from django.http import JsonResponse, Http404, HttpResponse
from django.shortcuts import render, redirect
from django.core.cache import cache
# from django.urls import reverse
# from django.views.decorators.csrf import csrf_exempt
from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView
from blog.helper import page_cache
# from asynchronous_send_mail import send_mail
from blog.tasks import increase_uv
# from django.core.mail import send_mail
@page_cache(60*60*24)
def home(request):
"""
首页
:param request:
:return:
"""
wheels = Wheels.objects.all().order_by('-id')
if wheels.count() >= 4:
wheels = wheels[:4]
blogs = Blog.objects.all().order_by('-create_time')
friends_blog = FriendsBlog.objects.all().filter(status=1)
tags = Tag.objects.all()
data = {
'title': '首页|Hubery的个人博客',
'wheels': wheels,
'blogs': blogs,
'tags': tags,
'friends_blog': friends_blog
}
return render(request, 'blog/home.html', context=data)
def get_all_blog(request):
"""
返回所有的博客
:param request:
:return:
"""
blogs = Blog.objects.all().order_by('-create_time')
data = {
'title': '全部博客',
'blogs': blogs
}
return render(request, 'blog/blog_list.html', context=data)
def create_blog(request):
pass
@page_cache(60*60*24)
def read_blog(request):
"""
阅读博客
:param request:
:return:
"""
try:
blog_id = int(request.GET.get('blogid', 1))
blog = Blog.objects.filter(pk=blog_id).first()
pre_blog = Blog.objects.filter(id__lt=blog.id).order_by('-id')
next_blog = Blog.objects.filter(id__gt=blog.id).order_by('id')
# 取第1条记录
if pre_blog.count() > 0:
pre_blog = pre_blog[0]
else:
pre_blog = None
if next_blog.count() > 0:
next_blog = next_blog[0]
else:
next_blog = None
data = {
'title': blog.title,
'blog': blog,
'pre_blog': pre_blog,
'next_blog': next_blog
}
response = render(request, 'blog/read_blog.html', context=data)
if not request.COOKIES.get('blog_%s_readed' % blog_id):
increase_uv.delay(blog_id) # 使用celery异步添加阅读数
response.set_cookie('blog_%s_readed' % blog_id, 'True')
return response
except Blog.DoesNotExist:
raise Http404
return response
def get_categories(request):
"""
返回对应分类下的所以文章
:param request:
:return:
"""
category_name = request.GET.get('category_name')
category = Category.objects.filter(name=category_name).first()
blogs = category.blog_set.all().order_by('-create_time')
data = {
'title': category_name,
'blogs': blogs
}
return render(request, 'blog/blog_list.html', context=data)
def get_tags(request):
"""
返回对应标签下的所以博客
:param request:
"""
tag_id = request.GET.get('tag_id')
tag = Tag.objects.filter(pk=tag_id).first()
blogs = tag.blog_set.all()
data = {
'title': tag.name,
'blogs': blogs
}
return render(request, 'blog/blog_list.html', context=data)
# def test_email(request):
# subject = '这是djiango邮件发送测试'
# message = '这是测试内容'
# frome_mail = '<EMAIL>'
# recipient_list = ['<EMAIL>']
# html = '<h1 style="color: red">没有查到相关博客</h1>'
# try:
# send_mail(subject, message, frome_mail, recipient_list, fail_silently=False, html_message=html)
# return HttpResponse('发送成功')
# except Exception as e:
# print(e)
# return HttpResponse('发送失败')
def web_nav(request):
"""
网站导航
:param request:
:return:
"""
web_categories = WebCategory.objects.all()
data = {
'title': '网站导航',
'web_categories': web_categories
}
return render(request, 'blog/web_nav.html', context=data)
@page_cache(60*60*24)
def archives(request):
"""
文章归档
:param request:
:return:
"""
dates = Blog.objects.all().order_by('-create_time')
data = {
'title': '文章归档',
'dates': dates
}
return render(request, 'blog/archives.html', context=data)
# @page_cache(60*60*24)
def message_board(request):
"""
留言
:param request:
:return:
"""
message = MessageBoard.objects.filter(id=1).first()
data = {
'title': '留言板',
'message': message
}
return render(request, 'blog/message_board.html', context=data)
@page_cache(60*60*24)
def about(request):
return render(request, 'blog/about.html', context={'title': '关于我'})
def get_online_ips(request):
"""
返回在线人数
:param request:
:return:
"""
online_ips = cache.get("online_ips", [])
online_ips_num = 0
visits_nums = VisitView.objects.aggregate(Sum("visit_num")).get('visit_num__sum', 0)
if online_ips:
online_ips_num = len(online_ips)
data_html = '历史总访问次数:%s 当前在线人数:%s' % (visits_nums, online_ips_num)
return JsonResponse({'code':'200', 'data_html': data_html})
def return_ip(request):
if 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META.get('HTTP_X_FORWARDED_FOR')
else:
ip = request.META.get('REMOTE_ADDR')
return HttpResponse('%s'% ip) | [
"django.shortcuts.render",
"blog.models.Wheels.objects.all",
"blog.models.Tag.objects.filter",
"django.http.JsonResponse",
"blog.models.FriendsBlog.objects.all",
"django.http.HttpResponse",
"blog.helper.page_cache",
"blog.models.Blog.objects.filter",
"blog.models.Category.objects.filter",
"blog.mo... | [((572, 596), 'blog.helper.page_cache', 'page_cache', (['(60 * 60 * 24)'], {}), '(60 * 60 * 24)\n', (582, 596), False, 'from blog.helper import page_cache\n'), ((1464, 1488), 'blog.helper.page_cache', 'page_cache', (['(60 * 60 * 24)'], {}), '(60 * 60 * 24)\n', (1474, 1488), False, 'from blog.helper import page_cache\n'), ((4051, 4075), 'blog.helper.page_cache', 'page_cache', (['(60 * 60 * 24)'], {}), '(60 * 60 * 24)\n', (4061, 4075), False, 'from blog.helper import page_cache\n'), ((4646, 4670), 'blog.helper.page_cache', 'page_cache', (['(60 * 60 * 24)'], {}), '(60 * 60 * 24)\n', (4656, 4670), False, 'from blog.helper import page_cache\n'), ((907, 924), 'blog.models.Tag.objects.all', 'Tag.objects.all', ([], {}), '()\n', (922, 924), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((1099, 1146), 'django.shortcuts.render', 'render', (['request', '"""blog/home.html"""'], {'context': 'data'}), "(request, 'blog/home.html', context=data)\n", (1105, 1146), False, 'from django.shortcuts import render, redirect\n'), ((1371, 1423), 'django.shortcuts.render', 'render', (['request', '"""blog/blog_list.html"""'], {'context': 'data'}), "(request, 'blog/blog_list.html', context=data)\n", (1377, 1423), False, 'from django.shortcuts import render, redirect\n'), ((2947, 2999), 'django.shortcuts.render', 'render', (['request', '"""blog/blog_list.html"""'], {'context': 'data'}), "(request, 'blog/blog_list.html', context=data)\n", (2953, 2999), False, 'from django.shortcuts import render, redirect\n'), ((3276, 3328), 'django.shortcuts.render', 'render', (['request', '"""blog/blog_list.html"""'], {'context': 'data'}), "(request, 'blog/blog_list.html', context=data)\n", (3282, 3328), False, 'from django.shortcuts import render, redirect\n'), ((3875, 3900), 'blog.models.WebCategory.objects.all', 'WebCategory.objects.all', ([], {}), '()\n', (3898, 3900), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((3997, 4047), 'django.shortcuts.render', 'render', (['request', '"""blog/web_nav.html"""'], {'context': 'data'}), "(request, 'blog/web_nav.html', context=data)\n", (4003, 4047), False, 'from django.shortcuts import render, redirect\n'), ((4287, 4338), 'django.shortcuts.render', 'render', (['request', '"""blog/archives.html"""'], {'context': 'data'}), "(request, 'blog/archives.html', context=data)\n", (4293, 4338), False, 'from django.shortcuts import render, redirect\n'), ((4586, 4642), 'django.shortcuts.render', 'render', (['request', '"""blog/message_board.html"""'], {'context': 'data'}), "(request, 'blog/message_board.html', context=data)\n", (4592, 4642), False, 'from django.shortcuts import render, redirect\n'), ((4698, 4758), 'django.shortcuts.render', 'render', (['request', '"""blog/about.html"""'], {'context': "{'title': '关于我'}"}), "(request, 'blog/about.html', context={'title': '关于我'})\n", (4704, 4758), False, 'from django.shortcuts import render, redirect\n'), ((4867, 4894), 'django.core.cache.cache.get', 'cache.get', (['"""online_ips"""', '[]'], {}), "('online_ips', [])\n", (4876, 4894), False, 'from django.core.cache import cache\n'), ((5162, 5215), 'django.http.JsonResponse', 'JsonResponse', (["{'code': '200', 'data_html': data_html}"], {}), "({'code': '200', 'data_html': data_html})\n", (5174, 5215), False, 'from django.http import JsonResponse, Http404, HttpResponse\n'), ((5408, 5431), 'django.http.HttpResponse', 'HttpResponse', (["('%s' % ip)"], {}), "('%s' % ip)\n", (5420, 5431), False, 'from django.http import JsonResponse, Http404, HttpResponse\n'), ((2241, 2293), 'django.shortcuts.render', 'render', (['request', '"""blog/read_blog.html"""'], {'context': 'data'}), "(request, 'blog/read_blog.html', context=data)\n", (2247, 2293), False, 'from django.shortcuts import render, redirect\n'), ((685, 705), 'blog.models.Wheels.objects.all', 'Wheels.objects.all', ([], {}), '()\n', (703, 705), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((790, 808), 'blog.models.Blog.objects.all', 'Blog.objects.all', ([], {}), '()\n', (806, 808), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((853, 878), 'blog.models.FriendsBlog.objects.all', 'FriendsBlog.objects.all', ([], {}), '()\n', (876, 878), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((1249, 1267), 'blog.models.Blog.objects.all', 'Blog.objects.all', ([], {}), '()\n', (1265, 1267), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((2370, 2396), 'blog.tasks.increase_uv.delay', 'increase_uv.delay', (['blog_id'], {}), '(blog_id)\n', (2387, 2396), False, 'from blog.tasks import increase_uv\n'), ((2749, 2792), 'blog.models.Category.objects.filter', 'Category.objects.filter', ([], {'name': 'category_name'}), '(name=category_name)\n', (2772, 2792), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((3127, 3156), 'blog.models.Tag.objects.filter', 'Tag.objects.filter', ([], {'pk': 'tag_id'}), '(pk=tag_id)\n', (3145, 3156), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((4165, 4183), 'blog.models.Blog.objects.all', 'Blog.objects.all', ([], {}), '()\n', (4181, 4183), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((4463, 4496), 'blog.models.MessageBoard.objects.filter', 'MessageBoard.objects.filter', ([], {'id': '(1)'}), '(id=1)\n', (4490, 4496), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((1643, 1674), 'blog.models.Blog.objects.filter', 'Blog.objects.filter', ([], {'pk': 'blog_id'}), '(pk=blog_id)\n', (1662, 1674), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((1702, 1737), 'blog.models.Blog.objects.filter', 'Blog.objects.filter', ([], {'id__lt': 'blog.id'}), '(id__lt=blog.id)\n', (1721, 1737), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((1774, 1809), 'blog.models.Blog.objects.filter', 'Blog.objects.filter', ([], {'id__gt': 'blog.id'}), '(id__gt=blog.id)\n', (1793, 1809), False, 'from blog.models import Wheels, Blog, Tag, Category, WebCategory, MessageBoard, FriendsBlog, VisitView\n'), ((4964, 4980), 'django.db.models.Sum', 'Sum', (['"""visit_num"""'], {}), "('visit_num')\n", (4967, 4980), False, 'from django.db.models import Sum\n')] |
#! /usr/bin/env python3
#
"""
Plot time series data in an interactive plot viewer.
Usage
=====
$ python3 plot_time_series.py --loglevel=20 --stderr
Plots add new data every second, and update on screen every 5 sec.
24 hours of data is kept. Each plot starts out in "autoaxis X PAN"
and "autoaxis Y VIS".
Things you can do in a plot:
1) Scroll the mouse wheel to zoom the X axis
2) Hold CTRL and scroll the mouse wheel to zoom the Y axis.
3) Press 'y' to autozoom the Y axis to the full range of the Y data.
(The message "Autoaxis Y ON" should appear briefly).
Press 'y' again to toggle off this behavior.
4) Press 'v' to autozoom the Y axis to the range of the *visible* data shown
(The message "Autoaxis Y VIS" should appear briefly).
Press 'v' again to toggle off this behavior.
5) Press 'x' to autozoom the X axis to the full range of the X data
(The message "Autoaxis X ON" should appear briefly).
Press 'x' again to toggle off this behavior.
6) Press 'p' to autopan the X axis to always show the latest data on
the right (the message "Autoaxis X PAN" should appear briefly).
Press 'p' again to toggle off this behavior.
.
"""
import sys
import time
import threading
import numpy as np
import ginga.toolkit as ginga_toolkit
from ginga.misc import log, Bunch
from ginga.plot.plotaide import PlotAide
import ginga.plot.data_source as dsp
win_wd, win_ht = 800, 280
class FakeData:
"""Generate fake time-series data."""
def __init__(self, name, t_start, y_range, num_pts):
self.name = name
self.t_start = t_start
self.y_range = y_range
self.num_pts = num_pts
self.data_src = None
self.tv = 0.0
self.tv_dir = 'up'
self.tv_dct = {0: 'up', 1: 'down'}
self.tv_delta = 0.1
self.tv_dmin = 1.0
self.tv_dmax = 30.0
self.tv_deadline = time.time()
def rand_rng(self, a, b):
return (b - a) * np.random.random_sample() + a
def generate_point(self, t):
x, y = t, self.tv
if self.tv_dir == 'up':
y = self.rand_rng(y, min(y + self.tv_delta, self.y_range[1]))
else:
y = self.rand_rng(max(y - self.tv_delta, self.y_range[0]), y)
self.tv = y
if t >= self.tv_deadline:
v = np.random.randint(0, 2)
self.tv_dir = self.tv_dct[v]
self.tv_deadline = t + self.rand_rng(self.tv_dmin, self.tv_dmax)
## p = np.random.randint(0, 100)
## if p >= 98:
## y = np.nan
return (x, y)
def init_points(self, data_src, start=None):
N, t = self.num_pts, self.t_start
if start is None:
start = (self.y_range[0] + self.y_range[1]) * 0.5
self.tv = start
self.tv_deadline = t - N + self.rand_rng(self.tv_dmin, self.tv_dmax)
points = np.array([self.generate_point(ti)
for ti in np.arange(t - N, t, 1.0)])
data_src.set_points(points)
self.data_src = data_src
def add_point(self, t):
pt = self.generate_point(t)
self.data_src.add(pt)
return pt
def timer1_cb(timer, fdg_l, interval):
t = time.time()
timer.set(interval)
for fdg in fdg_l:
fdg.add_point(t)
dsp.update_plot_from_source(fdg.data_src, fdg.data_src.plot,
update_limits=True)
def timer2_cb(timer, app, aides, fdg_l, interval):
timer.set(interval)
for a in aides:
# keep plots responsive
app.process_events()
a.aide.update_plots()
def make_plot(logger, dims, sources, y_rng, y_acc=np.mean,
title='', warn_y=None, alert_y=None,
show_x_axis=True, show_y_axis=True):
from ginga.gw import Viewers
from ginga.canvas.types import plots as gplots
import ginga.plot.time_series as tsp
win_wd, win_ht = dims[:2]
viewer = Viewers.CanvasView(logger, render='widget')
viewer.set_desired_size(win_wd, win_ht)
viewer.set_zoom_algorithm('rate')
viewer.set_zoomrate(1.41)
viewer.enable_autozoom('off')
viewer.set_background('white')
viewer.set_foreground('black')
viewer.set_enter_focus(True)
# our plot
aide = PlotAide(viewer)
aide.settings.set(autoaxis_x='pan', autoaxis_y='vis')
bg = tsp.TimePlotBG(warn_y=warn_y, alert_y=alert_y, linewidth=2)
aide.add_plot_decor(bg)
title = tsp.TimePlotTitle(title=title)
aide.add_plot_decor(title)
x_axis = tsp.XTimeAxis(num_labels=4)
aide.add_plot_decor(x_axis)
y_axis = gplots.YAxis(num_labels=4)
aide.add_plot_decor(y_axis)
colors = ['purple', 'palegreen4', 'red', 'brown', 'blue']
for i, src in enumerate(sources):
psrc = gplots.XYPlot(name=src.name, color=colors[i % len(colors)],
x_acc=np.mean, y_acc=y_acc,
linewidth=2.0, coord='data')
buf = np.zeros((src.num_pts, 2), dtype=np.float)
dsrc = dsp.XYDataSource(buf, none_for_empty=True, overwrite=True)
dsrc.plot = psrc
src.init_points(dsrc)
aide.add_plot(psrc)
dsp.update_plot_from_source(dsrc, psrc, update_limits=True)
# initially, show last 4 hours worth of data.
t, _ = dsrc.get_latest()
aide.zoom_limit_x(t - 4 * 3600, t)
# add scrollbar interface around this viewer
si = Viewers.GingaScrolledViewerWidget(viewer=viewer, width=win_wd,
height=win_ht)
aide.configure_scrollbars(si)
res = Bunch.Bunch(viewer=viewer, aide=aide, widget=si)
return res
def make_data(t, N, names, y_range):
srcs = []
for i, name in enumerate(names):
fdg = FakeData(name, t, y_range, N)
srcs.append(fdg)
return srcs
def cross_connect_plots(plot_info):
# cross connect the plots so that zooming or panning in X in one
# does the same to all the others
m_settings = plot_info[0].aide.settings
for res_a in plot_info:
for res_b in set(plot_info) - set([res_a]):
res_a.aide.add_callback('plot-zoom-x', res_b.aide.plot_zoom_x_cb)
if res_a.aide.settings is not m_settings:
m_settings.share_settings(res_a.aide.settings, keylist=['autoaxis_x'])
def main(options, args):
logger = log.get_logger("example1", options=options)
if options.toolkit is None:
logger.error("Please choose a GUI toolkit with -t option")
# decide our toolkit, then import
ginga_toolkit.use(options.toolkit)
# now we can import
from ginga.gw import Widgets
def quit(self, *args):
logger.info("Top window closed.")
sys.exit()
ev_quit = threading.Event()
app = Widgets.Application(logger=logger)
app.add_callback('shutdown', quit)
w = app.make_window("EnvMon")
w.add_callback('close', quit)
vbox = Widgets.VBox()
vbox.set_spacing(1)
dims = (win_wd, win_ht)
# default: data every second for 24 hours
N = options.numvalues
M = options.numplots
t = time.time()
plots = []
fdgs = []
# make a plot of outside and dome wind speed
y_rng = (0.0, 50.0)
srcs = make_data(t, N, ["Outside", "Dome"], y_rng)
fdgs.extend(srcs)
res = make_plot(logger, dims, srcs, y_rng,
y_acc=np.mean, title="Wind Speed (m/s)")
vbox.add_widget(res.widget, stretch=1)
plots.append(res)
# make a plot of outside and dome temperature
y_rng = (-30.0, 50.0)
srcs = make_data(t, N, ["Outside", "Dome"], y_rng)
fdgs.extend(srcs)
res = make_plot(logger, dims, srcs, y_rng,
y_acc=np.mean, title="Temperature (C)")
vbox.add_widget(res.widget, stretch=1)
plots.append(res)
# make a plot of outside and dome humidity
y_rng = (0.0, 100.0)
srcs = make_data(t, N, ["Outside", "Dome"], y_rng)
fdgs.extend(srcs)
res = make_plot(logger, dims, srcs, y_rng,
y_acc=np.mean, title="Humidity (%)",
warn_y=70, alert_y=80)
vbox.add_widget(res.widget, stretch=1)
plots.append(res)
# make a plot of outside and dome dew point
y_rng = (-30.0, 50.0)
srcs = make_data(t, N, ["Outside", "Dome"], y_rng)
fdgs.extend(srcs)
res = make_plot(logger, dims, srcs, y_rng,
y_acc=np.mean, title="M1 & Dew (C)")
vbox.add_widget(res.widget, stretch=1)
plots.append(res)
# make a plot of front and rear top-ring wind speed
y_rng = (0.0, 50.0)
srcs = make_data(t, N, ["Front", "Rear"], y_rng)
fdgs.extend(srcs)
res = make_plot(logger, dims, srcs, y_rng,
y_acc=np.mean, title="Top Ring Wind (m/s)")
vbox.add_widget(res.widget, stretch=1)
plots.append(res)
# cross connect plots so zooming/panning in X affects all plots
cross_connect_plots(plots)
hbox = Widgets.HBox()
hbox.set_margins(4, 2, 4, 2)
wquit = Widgets.Button("Quit")
wquit.add_callback('activated', quit)
hbox.add_widget(Widgets.Label(''), stretch=1)
hbox.add_widget(wquit)
vbox.add_widget(hbox, stretch=0)
w.set_widget(vbox)
# timer to add a point every second
t1 = app.make_timer()
t1.add_callback('expired', timer1_cb, fdgs, 1.0)
t1.set(1.0)
# timer to update the plot every interval seconds
t2 = app.make_timer()
t2.add_callback('expired', timer2_cb, app, plots, fdgs,
options.update_interval)
t2.set(options.update_interval)
w.resize(win_wd, win_ht * len(plots) + 50)
w.show()
app.mainloop()
if __name__ == "__main__":
# Parse command line options
from argparse import ArgumentParser
argprs = ArgumentParser("test ginga plot")
argprs.add_argument("--debug", dest="debug", default=False,
action="store_true",
help="Enter the pdb debugger on main()")
argprs.add_argument("-n", "--numvalues", dest="numvalues", default=86400,
type=int,
help="Number of items to show per plot")
argprs.add_argument("-m", "--numplots", dest="numplots", default=2,
type=int,
help="Number of plots to show per graph")
argprs.add_argument("--profile", dest="profile", action="store_true",
default=False,
help="Run the profiler on main()")
argprs.add_argument("-t", "--toolkit", dest="toolkit", metavar="NAME",
default='qt',
help="Choose GUI toolkit (gtk|qt)")
argprs.add_argument("--update", dest="update_interval", default=5.0,
type=float,
help="Number of seconds between plot updates")
log.addlogopts(argprs)
(options, args) = argprs.parse_known_args(sys.argv[1:])
# Are we debugging this?
if options.debug:
import pdb
pdb.run('main(options, args)')
# Are we profiling this?
elif options.profile:
import profile
print(("%s profile:" % sys.argv[0]))
profile.run('main(options, args)')
else:
main(options, args)
| [
"ginga.plot.data_source.XYDataSource",
"ginga.gw.Widgets.Button",
"ginga.toolkit.use",
"ginga.plot.data_source.update_plot_from_source",
"ginga.plot.time_series.TimePlotTitle",
"ginga.gw.Widgets.HBox",
"ginga.gw.Viewers.CanvasView",
"sys.exit",
"numpy.arange",
"ginga.plot.time_series.TimePlotBG",
... | [((3175, 3186), 'time.time', 'time.time', ([], {}), '()\n', (3184, 3186), False, 'import time\n'), ((3906, 3949), 'ginga.gw.Viewers.CanvasView', 'Viewers.CanvasView', (['logger'], {'render': '"""widget"""'}), "(logger, render='widget')\n", (3924, 3949), False, 'from ginga.gw import Viewers\n'), ((4227, 4243), 'ginga.plot.plotaide.PlotAide', 'PlotAide', (['viewer'], {}), '(viewer)\n', (4235, 4243), False, 'from ginga.plot.plotaide import PlotAide\n'), ((4312, 4371), 'ginga.plot.time_series.TimePlotBG', 'tsp.TimePlotBG', ([], {'warn_y': 'warn_y', 'alert_y': 'alert_y', 'linewidth': '(2)'}), '(warn_y=warn_y, alert_y=alert_y, linewidth=2)\n', (4326, 4371), True, 'import ginga.plot.time_series as tsp\n'), ((4413, 4443), 'ginga.plot.time_series.TimePlotTitle', 'tsp.TimePlotTitle', ([], {'title': 'title'}), '(title=title)\n', (4430, 4443), True, 'import ginga.plot.time_series as tsp\n'), ((4489, 4516), 'ginga.plot.time_series.XTimeAxis', 'tsp.XTimeAxis', ([], {'num_labels': '(4)'}), '(num_labels=4)\n', (4502, 4516), True, 'import ginga.plot.time_series as tsp\n'), ((4563, 4589), 'ginga.canvas.types.plots.YAxis', 'gplots.YAxis', ([], {'num_labels': '(4)'}), '(num_labels=4)\n', (4575, 4589), True, 'from ginga.canvas.types import plots as gplots\n'), ((5375, 5452), 'ginga.gw.Viewers.GingaScrolledViewerWidget', 'Viewers.GingaScrolledViewerWidget', ([], {'viewer': 'viewer', 'width': 'win_wd', 'height': 'win_ht'}), '(viewer=viewer, width=win_wd, height=win_ht)\n', (5408, 5452), False, 'from ginga.gw import Viewers\n'), ((5541, 5589), 'ginga.misc.Bunch.Bunch', 'Bunch.Bunch', ([], {'viewer': 'viewer', 'aide': 'aide', 'widget': 'si'}), '(viewer=viewer, aide=aide, widget=si)\n', (5552, 5589), False, 'from ginga.misc import log, Bunch\n'), ((6303, 6346), 'ginga.misc.log.get_logger', 'log.get_logger', (['"""example1"""'], {'options': 'options'}), "('example1', options=options)\n", (6317, 6346), False, 'from ginga.misc import log, Bunch\n'), ((6490, 6524), 'ginga.toolkit.use', 'ginga_toolkit.use', (['options.toolkit'], {}), '(options.toolkit)\n', (6507, 6524), True, 'import ginga.toolkit as ginga_toolkit\n'), ((6687, 6704), 'threading.Event', 'threading.Event', ([], {}), '()\n', (6702, 6704), False, 'import threading\n'), ((6716, 6750), 'ginga.gw.Widgets.Application', 'Widgets.Application', ([], {'logger': 'logger'}), '(logger=logger)\n', (6735, 6750), False, 'from ginga.gw import Widgets\n'), ((6871, 6885), 'ginga.gw.Widgets.VBox', 'Widgets.VBox', ([], {}), '()\n', (6883, 6885), False, 'from ginga.gw import Widgets\n'), ((7045, 7056), 'time.time', 'time.time', ([], {}), '()\n', (7054, 7056), False, 'import time\n'), ((8863, 8877), 'ginga.gw.Widgets.HBox', 'Widgets.HBox', ([], {}), '()\n', (8875, 8877), False, 'from ginga.gw import Widgets\n'), ((8924, 8946), 'ginga.gw.Widgets.Button', 'Widgets.Button', (['"""Quit"""'], {}), "('Quit')\n", (8938, 8946), False, 'from ginga.gw import Widgets\n'), ((9684, 9717), 'argparse.ArgumentParser', 'ArgumentParser', (['"""test ginga plot"""'], {}), "('test ginga plot')\n", (9698, 9717), False, 'from argparse import ArgumentParser\n'), ((10771, 10793), 'ginga.misc.log.addlogopts', 'log.addlogopts', (['argprs'], {}), '(argprs)\n', (10785, 10793), False, 'from ginga.misc import log, Bunch\n'), ((1870, 1881), 'time.time', 'time.time', ([], {}), '()\n', (1879, 1881), False, 'import time\n'), ((3267, 3352), 'ginga.plot.data_source.update_plot_from_source', 'dsp.update_plot_from_source', (['fdg.data_src', 'fdg.data_src.plot'], {'update_limits': '(True)'}), '(fdg.data_src, fdg.data_src.plot, update_limits=True\n )\n', (3294, 3352), True, 'import ginga.plot.data_source as dsp\n'), ((4928, 4970), 'numpy.zeros', 'np.zeros', (['(src.num_pts, 2)'], {'dtype': 'np.float'}), '((src.num_pts, 2), dtype=np.float)\n', (4936, 4970), True, 'import numpy as np\n'), ((4986, 5044), 'ginga.plot.data_source.XYDataSource', 'dsp.XYDataSource', (['buf'], {'none_for_empty': '(True)', 'overwrite': '(True)'}), '(buf, none_for_empty=True, overwrite=True)\n', (5002, 5044), True, 'import ginga.plot.data_source as dsp\n'), ((5137, 5196), 'ginga.plot.data_source.update_plot_from_source', 'dsp.update_plot_from_source', (['dsrc', 'psrc'], {'update_limits': '(True)'}), '(dsrc, psrc, update_limits=True)\n', (5164, 5196), True, 'import ginga.plot.data_source as dsp\n'), ((6661, 6671), 'sys.exit', 'sys.exit', ([], {}), '()\n', (6669, 6671), False, 'import sys\n'), ((9010, 9027), 'ginga.gw.Widgets.Label', 'Widgets.Label', (['""""""'], {}), "('')\n", (9023, 9027), False, 'from ginga.gw import Widgets\n'), ((10935, 10965), 'pdb.run', 'pdb.run', (['"""main(options, args)"""'], {}), "('main(options, args)')\n", (10942, 10965), False, 'import pdb\n'), ((2293, 2316), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (2310, 2316), True, 'import numpy as np\n'), ((11099, 11133), 'profile.run', 'profile.run', (['"""main(options, args)"""'], {}), "('main(options, args)')\n", (11110, 11133), False, 'import profile\n'), ((1938, 1963), 'numpy.random.random_sample', 'np.random.random_sample', ([], {}), '()\n', (1961, 1963), True, 'import numpy as np\n'), ((2917, 2941), 'numpy.arange', 'np.arange', (['(t - N)', 't', '(1.0)'], {}), '(t - N, t, 1.0)\n', (2926, 2941), True, 'import numpy as np\n')] |
import asyncio
from aioflows.simple import Printer, Ticker
async def start():
await (Ticker() >> Printer()).start()
asyncio.run(start())
| [
"aioflows.simple.Printer",
"aioflows.simple.Ticker"
] | [((92, 100), 'aioflows.simple.Ticker', 'Ticker', ([], {}), '()\n', (98, 100), False, 'from aioflows.simple import Printer, Ticker\n'), ((104, 113), 'aioflows.simple.Printer', 'Printer', ([], {}), '()\n', (111, 113), False, 'from aioflows.simple import Printer, Ticker\n')] |
from functools import wraps
from typing import TYPE_CHECKING, Any, AnyStr, Callable, Type, TypeVar
from graia.amnesia.json import TJson
from graia.amnesia.json.frontend import Json
if TYPE_CHECKING:
from graia.amnesia.transport.common.websocket.io import AbstractWebsocketIO
_S = TypeVar("_S")
_R = TypeVar("_R")
def data_type(type: Type[AnyStr], error: bool = False):
def decorator(func: Callable[[Any, "AbstractWebsocketIO", AnyStr], Any]):
@wraps(func)
async def wrapper(self, io, data: Any):
if isinstance(data, type):
return await func(self, io, data)
elif error:
raise TypeError(f"Expected {type.__name__}, got {data.__class__.__name__}")
return wrapper
return decorator
def json_require(
func: Callable[[_S, "AbstractWebsocketIO", TJson], _R]
) -> Callable[[_S, "AbstractWebsocketIO", str], _R]:
@wraps(func)
def wrapper(self: _S, io, data: str) -> _R:
return func(self, io, Json.deserialize(data))
return wrapper
| [
"graia.amnesia.json.frontend.Json.deserialize",
"functools.wraps",
"typing.TypeVar"
] | [((288, 301), 'typing.TypeVar', 'TypeVar', (['"""_S"""'], {}), "('_S')\n", (295, 301), False, 'from typing import TYPE_CHECKING, Any, AnyStr, Callable, Type, TypeVar\n'), ((307, 320), 'typing.TypeVar', 'TypeVar', (['"""_R"""'], {}), "('_R')\n", (314, 320), False, 'from typing import TYPE_CHECKING, Any, AnyStr, Callable, Type, TypeVar\n'), ((914, 925), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (919, 925), False, 'from functools import wraps\n'), ((466, 477), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (471, 477), False, 'from functools import wraps\n'), ((1004, 1026), 'graia.amnesia.json.frontend.Json.deserialize', 'Json.deserialize', (['data'], {}), '(data)\n', (1020, 1026), False, 'from graia.amnesia.json.frontend import Json\n')] |
#
# download.py
#
# futaba - A Discord Mod bot for the Programming server
# Copyright (c) 2017-2020 <NAME>, <NAME>, jackylam5
#
# futaba is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in the hopes that it will be useful, but
# WITHOUT ANY WARRANTY. See the LICENSE file for more details.
#
import asyncio
import logging
from io import BytesIO
from ssl import SSLError
import aiohttp
logger = logging.getLogger(__name__)
__all__ = ["MAXIMUM_FILE_SIZE", "download_links", "download_link"]
# Maximum size to download from foreign sites
MAXIMUM_FILE_SIZE = 24 * 1024 * 1024
# How large each read request should be
CHUNK_SIZE = 4 * 1024
# Prevent connections from hanging for too long
TIMEOUT = aiohttp.ClientTimeout(total=45, sock_read=5)
async def download_links(urls):
async with aiohttp.ClientSession(timeout=TIMEOUT, trust_env=True) as session:
buffers = await asyncio.gather(*[download(session, url) for url in urls])
return buffers
async def download_link(url):
async with aiohttp.ClientSession(timeout=TIMEOUT, trust_env=True) as session:
return await download(session, url)
async def download(session, url):
binio = BytesIO()
try:
async with session.get(url) as response:
if response.content_length is not None:
if response.content_length > MAXIMUM_FILE_SIZE:
logger.info(
"File is reportedly too large (%d bytes > %d bytes)",
response.content_length,
MAXIMUM_FILE_SIZE,
)
return None
while len(binio.getbuffer()) < MAXIMUM_FILE_SIZE:
chunk = await response.content.read(CHUNK_SIZE)
if chunk:
binio.write(chunk)
else:
return binio
logger.info(
"File was too large, bailing out (max file size: %d bytes)",
MAXIMUM_FILE_SIZE,
)
return None
except SSLError:
# Ignore SSL errors
pass
except Exception as error:
logger.info("Error while downloading %s for hash check", url, exc_info=error)
return None
| [
"logging.getLogger",
"aiohttp.ClientSession",
"io.BytesIO",
"aiohttp.ClientTimeout"
] | [((499, 526), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (516, 526), False, 'import logging\n'), ((801, 845), 'aiohttp.ClientTimeout', 'aiohttp.ClientTimeout', ([], {'total': '(45)', 'sock_read': '(5)'}), '(total=45, sock_read=5)\n', (822, 845), False, 'import aiohttp\n'), ((1269, 1278), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (1276, 1278), False, 'from io import BytesIO\n'), ((895, 949), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {'timeout': 'TIMEOUT', 'trust_env': '(True)'}), '(timeout=TIMEOUT, trust_env=True)\n', (916, 949), False, 'import aiohttp\n'), ((1110, 1164), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {'timeout': 'TIMEOUT', 'trust_env': '(True)'}), '(timeout=TIMEOUT, trust_env=True)\n', (1131, 1164), False, 'import aiohttp\n')] |
#-*- coding:utf-8 -*-
from __future__ import print_function
import os,sys,sip,time
from datetime import datetime,timedelta
from qtpy.QtWidgets import QTreeWidgetItem,QMenu,QApplication,QAction,QMainWindow
from qtpy import QtGui,QtWidgets
from qtpy.QtCore import Qt,QUrl,QDate
from Graph import graphpage
from layout import Ui_MainWindow
from pandas import DataFrame as df
import pandas as pd
import tushare as ts
import pickle
import numpy as np
list1 = []
class MyUi(QMainWindow):
def __init__(self):
super(MyUi, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
cwd = os.getcwd()
cwd = str(cwd)
if os.path.isfile(cwd+"/time"):
with open("time","rb") as outfile:#reads current time
history = pickle.load(outfile)
if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours
print("Less than 12 hours. Loading previously saved Pickle...")
else:
print("More than 12 hours. Updating Pickle...")
data = ts.get_industry_classified()
with open("class","wb+") as outfile:
pickle.dump(data,outfile)
now = datetime.now()
with open("time", "wb+") as outfile: #update time
pickle.dump(now, outfile)
else:
print("No Pickle found!") #If this is first time using tuchart in this directory
data = df()
data = ts.get_industry_classified()
with open('class', 'wb+') as outfile: #records pickle
pickle.dump(data, outfile)
now = datetime.now()
with open("time", "wb+") as outfile:
pickle.dump(now,outfile)
with open("class", "rb") as infile: # reads current time
series = pickle.load(infile)
#series = pd.read_json(cwd + "\\class.json")
#series = ts.get_industry_classified()
series = pd.DataFrame(series)
curdate = time.strftime("%Y/%m/%d") # gets current time to put into dateedit
curdateQ = QDate.fromString(curdate,"yyyy/MM/dd")
dateobj = datetime.strptime(curdate, "%Y/%m/%d")#converts to datetime object
past = dateobj - timedelta(days = 7) #minus a week to start date
pasttime = datetime.strftime(past, "%Y/%m/%d")
pastQ = QDate.fromString(pasttime,"yyyy/MM/dd") #convert to qtime so that widget accepts the values
pastL = dateobj - timedelta(days=30) # minus a month to start date
pasttimeL = datetime.strftime(pastL, "%Y/%m/%d")
pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd")
np_indexes = np.array([['sh', '上证指数', '大盘指数'],
['sz', '深证成指', '大盘指数'],
['hs300', '沪深300指数', '大盘指数'],
['sz50', '上证50', '大盘指数'],
['zxb', '中小板', '大盘指数'],
['cyb', '创业板', '大盘指数']])
indexes = df(data=np_indexes,
index=range(5000, 5006),
columns=["code", "name", "c_name"])
series = indexes.append(series)
list1_bfr = series["c_name"].tolist() #Get industry categories. Filters out redundant ones
list1 = list(set(list1_bfr))
list1.sort(key=list1_bfr.index)
#w = database()
#zsparent = QTreeWidgetItem(self.ui.treeWidget)
#zsparent.setText(0,"股票指数")
#zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]
self.init_treeWidget(list1,series)
self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)
#self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861))
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file
local_url = QUrl.fromLocalFile(file_path)
self.ui.webView.load(local_url)
#self.ui.commandLinkButton.setFixedSize(50, 50)
self.ui.search_btn.clicked.connect(lambda: self.search_comp(series))
self.ui.init_code_btn.clicked.connect(lambda: self.code_sort_tree(series))
self.ui.init_category_btn.clicked.connect(lambda: self.init_treeWidget(list1, series))
self.ui.commandLinkButton.clicked.connect(self.classify) #when the arrow button is clicked, trigger events
#self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
# QSizePolicy
try:
retain_size = self.ui.dateEdit_2.sizePolicy()
retain_size.setRetainSizeWhenHidden(True)
self.ui.dateEdit_2.setSizePolicy(retain_size)
retain_size = self.ui.comboBox.sizePolicy()
retain_size.setRetainSizeWhenHidden(True)
self.ui.comboBox.setSizePolicy(retain_size)
retain_size = self.ui.label_2.sizePolicy()
retain_size.setRetainSizeWhenHidden(True)
self.ui.label_2.setSizePolicy(retain_size)
except AttributeError:
print("No PYQT5 Binding! Widgets might be deformed")
self.ui.dateEdit.setDate(pastQL)
self.ui.dateEdit_2.setDate(curdateQ)#populate widgets
self.ui.dateEdit.setCalendarPopup(True)
self.ui.dateEdit_2.setCalendarPopup(True)
self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])
self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.treeWidget_2.customContextMenuRequested.connect(self.openWidgetMenu)
#self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
self.ui.combobox.currentIndexChanged.connect(lambda: self.modifycombo(pastQL,pastQ))
def init_treeWidget(self, list1, series):
self.ui.treeWidget.clear()
for j in list1:
parent = QTreeWidgetItem(self.ui.treeWidget) #populate treewidget with names
parent.setText(0,j)
var = series.loc[series["c_name"] == j]
list2 = var["code"].tolist()
name = var["name"].tolist()
#var = showcollection(i) #Display database items
for idx,val in enumerate(list2):
child = QTreeWidgetItem(parent)
child.setText(0, name[idx]+"-"+val)
#for i in Drag:
#grandson = QTreeWidgetItem(child) #Commented out because increases program response time
#grandson.setText(0, i)
#self.ui.treeWidget.itemDoubleClicked.connect(self.onClickItem) #Display Collection items
def code_sort_tree(self, companies):
self.ui.treeWidget.clear()
sorted_comps = companies.sort_values(["code"])
code_list = sorted_comps["code"].tolist()
name_list = sorted_comps["name"].tolist()
shares_parent = QTreeWidgetItem(self.ui.treeWidget)
shares_parent.setText(0, "个股行情")
for idx, val in enumerate(code_list):
child = QTreeWidgetItem(shares_parent)
child.setText(0, name_list[idx] + "-" + str(val))
self.ui.treeWidget.expandToDepth(0)
def search_comp(self, companies):
self.ui.treeWidget.clear()
text = self.ui.search_lineEdit.text()
filtered_codes = companies[companies['code'].str.contains(text)]
filtered_names = companies[companies['name'].str.contains(text)]
filtered_comps = filtered_codes.append(filtered_names)
code_list = filtered_comps["code"].tolist()
name_list = filtered_comps["name"].tolist()
parent = QTreeWidgetItem(self.ui.treeWidget)
parent.setText(0, "搜索结果")
for idx, val in enumerate(code_list):
child = QTreeWidgetItem(parent)
child.setText(0, name_list[idx] + "-" + str(val))
self.ui.treeWidget.expandToDepth(0)
def modifycombo(self,pastQL,pastQ):
if self.ui.combobox.currentText()=="复权": #if 复权 is selected, clear all existing queries to avoid value conflict
self.ui.label_2.show()
self.ui.dateEdit_2.show()
self.ui.dateEdit.setDate(pastQL)
self.ui.interval_label.show()
self.ui.comboBox.show()
self.ui.comboBox.clear()
self.ui.comboBox.addItems(["hfq", "qfq"])
self.ui.treeWidget_2.clear()
if self.ui.combobox.currentText()=="K线":
self.ui.label_2.show()
self.ui.dateEdit_2.show()
self.ui.dateEdit.setDate(pastQL)
self.ui.interval_label.show()
self.ui.comboBox.show()
self.ui.comboBox.clear()
self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])#same as above
self.ui.treeWidget_2.clear()
if self.ui.combobox.currentText()=="分笔数据":
self.ui.interval_label.hide()
self.ui.comboBox.hide()
self.ui.label_2.hide()
self.ui.dateEdit_2.hide()
self.ui.dateEdit.setDate(pastQ)
self.ui.treeWidget_2.clear()
if self.ui.combobox.currentText()=="历史分钟":
self.ui.interval_label.hide()
self.ui.comboBox.show()
self.ui.comboBox.clear()
self.ui.comboBox.addItems(["1min","5min","15min","30min","60min"])
self.ui.label_2.hide()
self.ui.dateEdit_2.hide()
self.ui.dateEdit.setDate(pastQ)
self.ui.treeWidget_2.clear()
if self.ui.combobox.currentText()==u"十大股东":
self.ui.interval_label.hide()
self.ui.comboBox.hide()
self.ui.label_2.hide()
self.ui.dateEdit_2.hide()
self.ui.treeWidget_2.clear()
def openMenu(self,position):
indexes = self.ui.treeWidget.selectedIndexes()
item = self.ui.treeWidget.itemAt(position)
db_origin = ""
#if item.parent():
# db_origin = item.parent().text(0)
collec = item.text(0)
if len(indexes) > 0:
level = 0
index = indexes[0]
while index.parent().isValid():
index = index.parent()
level = level + 1
menu = QMenu()
#print((collec, db_origin))
if level ==0:
pass
else:
#keyarray = GetKeys(collec, db_origin)
#if "Open" in keyarray:
if self.ui.combobox.currentText()==u"K线":
menu.addAction(QAction("Kline", menu, checkable=True))
menu.addAction(QAction("Open", menu, checkable=True))
menu.addAction(QAction("Close", menu, checkable=True))#open up different menu with different kind of graphs
menu.addAction(QAction("High", menu, checkable=True))
menu.addAction(QAction("Low", menu, checkable=True))
menu.addAction(QAction("Volume", menu, checkable=True))
#menu.addAction(QAction("P_change", menu, checkable=True))
#menu.addAction(QAction("Turnover",menu,checkable=True))
if self.ui.combobox.currentText()==u"复权":
menu.addAction(QAction("Kline", menu, checkable=True))
menu.addAction(QAction("Open", menu, checkable=True))
menu.addAction(QAction("Close", menu, checkable=True))
menu.addAction(QAction("High", menu, checkable=True))
menu.addAction(QAction("Low", menu, checkable=True))
menu.addAction(QAction("Volume", menu, checkable=True))
menu.addAction(QAction("Amount", menu, checkable=True))
if self.ui.combobox.currentText()==u"分笔数据":
menu.addAction(QAction("分笔", menu, checkable=True))
if self.ui.combobox.currentText()==u"历史分钟":
menu.addAction(QAction("Kline", menu, checkable=True))
menu.addAction(QAction("Open", menu, checkable=True))
menu.addAction(QAction("Close", menu, checkable=True))
menu.addAction(QAction("High", menu, checkable=True))
menu.addAction(QAction("Low", menu, checkable=True))
menu.addAction(QAction("Volume", menu, checkable=True))
menu.addAction(QAction("Amount", menu, checkable=True))
if self.ui.combobox.currentText()==u"十大股东":
menu.addAction(QAction("季度饼图", menu, checkable=True))
#menu.addAction(QAction("持股比例", menu, checkable=True))
#for g in keyarray:
#menu.addAction(QAction(g, menu, checkable=True))
menu.triggered.connect(lambda action: self.methodSelected(action, collec))
menu.exec_(self.ui.treeWidget.viewport().mapToGlobal(position))
def methodSelected(self, action, collec):
# print(action.text()) #Choice
# if (self.ui.treewidget.count() == 5):
# self.ui.label.setText("Maximum number of queries")
# return
# self.ui.label.setText("")
Choice = action.text()
Stock = collec
# print(collec) #Stock Name
# print(db_origin) #DataBase name
# list1 = [self.tr(Stock+"-"+Choice+"-"+db_origin)]
# self.ui.treewidget.addItems(list1)
parent = QTreeWidgetItem(self.ui.treeWidget_2)
parent.setText(0, Stock+ "-" + Choice)
def openWidgetMenu(self,position):
indexes = self.ui.treeWidget_2.selectedIndexes()
item = self.ui.treeWidget_2.itemAt(position)
if item == None:
return
#item = self.ui.listWidget.itemAt(position)
if len(indexes) > 0:
menu = QMenu()
menu.addAction(QAction("Delete", menu,checkable = True))#This function is perhaps useless
#menu.triggered.connect(self.eraseItem)
item = self.ui.treeWidget_2.itemAt(position)
#collec = str(item.text())
menu.triggered.connect(lambda action: self.ListMethodSelected(action, item))
menu.exec_(self.ui.treeWidget_2.viewport().mapToGlobal(position))
def ListMethodSelected(self, action, item):
if action.text() == "Delete":
self.eraseItem()
if action.text() == "Combine":
global CombineKeyword
collec = str(item.text())
CombineKeyword.append(collec)#Useless function(maybe?)
list1 = [self.tr(collec)]
self.ui.listwidget.addItems(list1)
self.eraseItem()
def eraseItem(self):
for x in self.ui.treeWidget_2.selectedItems():#delete with write click menu
#item = self.ui.treewidget.takeItem(self.ui.treewidget.currentRow())
sip.delete(x)
#item.delete
def classify(self, folder):
startdate = self.ui.dateEdit.date()
startdate = startdate.toPyDate()
startdate = startdate.strftime("%Y/%m/%d")#converts date from dateedit to tushare readable date
enddate = self.ui.dateEdit_2.date()
enddate = enddate.toPyDate()
enddate = enddate.strftime("%Y/%m/%d")
option = self.ui.comboBox.currentText()
option = str(option)
#if (self.ui.treewidget) == 0:
#self.ui.label.setText("Need to select at least one query")
#return
root = self.ui.treeWidget_2.invisibleRootItem()# This is for iterating child items
child_count = root.childCount()
texts = []
if child_count==0:
return
for i in range(child_count):
item = root.child(i)
text = item.text(0)#with 3 part'stock_name'+'-'+'code'+'-'+action
texts.append(text)
labels = [k for k in texts]
#items = ([x.encode("utf-8") for x in labels])
width = self.ui.webView.width()#give width and height of user's screen so that graphs can be generated with dynamic size
height = self.ui.webView.height()
mode_combo = self.ui.combobox.currentText()
graphpage(labels,mode_combo, startdate,enddate,option,width, height)#labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc
self.ui.webView.reload()#refreshes webengine
self.ui.webView.repaint()
self.ui.webView.update()
def graphmerge(self, combineKeyword):
sth = ""
for i in combineKeyword:
if sth == "":
sth = sth + i
else :
sth = sth + "\n" + "&"+ "-"+i
list1 = sth
return sth
global CombineKeyword
CombineKeyword = []
self.ui.listwidget.clear() #combine stuff so that different graphs can be drawn together
app = QApplication(sys.argv)
w = MyUi()
w.show()
sys.exit(app.exec_())
| [
"qtpy.QtCore.QUrl.fromLocalFile",
"qtpy.QtCore.QDate.fromString",
"Graph.graphpage",
"numpy.array",
"qtpy.QtWidgets.QAction",
"tushare.get_industry_classified",
"datetime.timedelta",
"qtpy.QtWidgets.QTreeWidgetItem",
"pandas.DataFrame",
"layout.Ui_MainWindow",
"qtpy.QtWidgets.QMenu",
"pickle.l... | [((16921, 16943), 'qtpy.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (16933, 16943), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((564, 579), 'layout.Ui_MainWindow', 'Ui_MainWindow', ([], {}), '()\n', (577, 579), False, 'from layout import Ui_MainWindow\n'), ((624, 635), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (633, 635), False, 'import os, sys, sip, time\n'), ((671, 700), 'os.path.isfile', 'os.path.isfile', (["(cwd + '/time')"], {}), "(cwd + '/time')\n", (685, 700), False, 'import os, sys, sip, time\n'), ((2024, 2044), 'pandas.DataFrame', 'pd.DataFrame', (['series'], {}), '(series)\n', (2036, 2044), True, 'import pandas as pd\n'), ((2064, 2089), 'time.strftime', 'time.strftime', (['"""%Y/%m/%d"""'], {}), "('%Y/%m/%d')\n", (2077, 2089), False, 'import os, sys, sip, time\n'), ((2151, 2190), 'qtpy.QtCore.QDate.fromString', 'QDate.fromString', (['curdate', '"""yyyy/MM/dd"""'], {}), "(curdate, 'yyyy/MM/dd')\n", (2167, 2190), False, 'from qtpy.QtCore import Qt, QUrl, QDate\n'), ((2209, 2247), 'datetime.datetime.strptime', 'datetime.strptime', (['curdate', '"""%Y/%m/%d"""'], {}), "(curdate, '%Y/%m/%d')\n", (2226, 2247), False, 'from datetime import datetime, timedelta\n'), ((2370, 2405), 'datetime.datetime.strftime', 'datetime.strftime', (['past', '"""%Y/%m/%d"""'], {}), "(past, '%Y/%m/%d')\n", (2387, 2405), False, 'from datetime import datetime, timedelta\n'), ((2422, 2462), 'qtpy.QtCore.QDate.fromString', 'QDate.fromString', (['pasttime', '"""yyyy/MM/dd"""'], {}), "(pasttime, 'yyyy/MM/dd')\n", (2438, 2462), False, 'from qtpy.QtCore import Qt, QUrl, QDate\n'), ((2614, 2650), 'datetime.datetime.strftime', 'datetime.strftime', (['pastL', '"""%Y/%m/%d"""'], {}), "(pastL, '%Y/%m/%d')\n", (2631, 2650), False, 'from datetime import datetime, timedelta\n'), ((2668, 2709), 'qtpy.QtCore.QDate.fromString', 'QDate.fromString', (['pasttimeL', '"""yyyy/MM/dd"""'], {}), "(pasttimeL, 'yyyy/MM/dd')\n", (2684, 2709), False, 'from qtpy.QtCore import Qt, QUrl, QDate\n'), ((2733, 2904), 'numpy.array', 'np.array', (["[['sh', '上证指数', '大盘指数'], ['sz', '深证成指', '大盘指数'], ['hs300', '沪深300指数',\n '大盘指数'], ['sz50', '上证50', '大盘指数'], ['zxb', '中小板', '大盘指数'], ['cyb',\n '创业板', '大盘指数']]"], {}), "([['sh', '上证指数', '大盘指数'], ['sz', '深证成指', '大盘指数'], ['hs300',\n '沪深300指数', '大盘指数'], ['sz50', '上证50', '大盘指数'], ['zxb', '中小板', '大盘指数'], [\n 'cyb', '创业板', '大盘指数']])\n", (2741, 2904), True, 'import numpy as np\n'), ((3986, 4015), 'qtpy.QtCore.QUrl.fromLocalFile', 'QUrl.fromLocalFile', (['file_path'], {}), '(file_path)\n', (4004, 4015), False, 'from qtpy.QtCore import Qt, QUrl, QDate\n'), ((7045, 7080), 'qtpy.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['self.ui.treeWidget'], {}), '(self.ui.treeWidget)\n', (7060, 7080), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((7775, 7810), 'qtpy.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['self.ui.treeWidget'], {}), '(self.ui.treeWidget)\n', (7790, 7810), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((13557, 13594), 'qtpy.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['self.ui.treeWidget_2'], {}), '(self.ui.treeWidget_2)\n', (13572, 13594), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((16264, 16336), 'Graph.graphpage', 'graphpage', (['labels', 'mode_combo', 'startdate', 'enddate', 'option', 'width', 'height'], {}), '(labels, mode_combo, startdate, enddate, option, width, height)\n', (16273, 16336), False, 'from Graph import graphpage\n'), ((1500, 1504), 'pandas.DataFrame', 'df', ([], {}), '()\n', (1502, 1504), True, 'from pandas import DataFrame as df\n'), ((1524, 1552), 'tushare.get_industry_classified', 'ts.get_industry_classified', ([], {}), '()\n', (1550, 1552), True, 'import tushare as ts\n'), ((1680, 1694), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1692, 1694), False, 'from datetime import datetime, timedelta\n'), ((1873, 1892), 'pickle.load', 'pickle.load', (['infile'], {}), '(infile)\n', (1884, 1892), False, 'import pickle\n'), ((2302, 2319), 'datetime.timedelta', 'timedelta', ([], {'days': '(7)'}), '(days=7)\n', (2311, 2319), False, 'from datetime import datetime, timedelta\n'), ((2544, 2562), 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), '(days=30)\n', (2553, 2562), False, 'from datetime import datetime, timedelta\n'), ((6061, 6096), 'qtpy.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['self.ui.treeWidget'], {}), '(self.ui.treeWidget)\n', (6076, 6096), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((7188, 7218), 'qtpy.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['shares_parent'], {}), '(shares_parent)\n', (7203, 7218), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((7911, 7934), 'qtpy.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['parent'], {}), '(parent)\n', (7926, 7934), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((10365, 10372), 'qtpy.QtWidgets.QMenu', 'QMenu', ([], {}), '()\n', (10370, 10372), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((13937, 13944), 'qtpy.QtWidgets.QMenu', 'QMenu', ([], {}), '()\n', (13942, 13944), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((14969, 14982), 'sip.delete', 'sip.delete', (['x'], {}), '(x)\n', (14979, 14982), False, 'import os, sys, sip, time\n'), ((792, 812), 'pickle.load', 'pickle.load', (['outfile'], {}), '(outfile)\n', (803, 812), False, 'import pickle\n'), ((1096, 1124), 'tushare.get_industry_classified', 'ts.get_industry_classified', ([], {}), '()\n', (1122, 1124), True, 'import tushare as ts\n'), ((1246, 1260), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1258, 1260), False, 'from datetime import datetime, timedelta\n'), ((1635, 1661), 'pickle.dump', 'pickle.dump', (['data', 'outfile'], {}), '(data, outfile)\n', (1646, 1661), False, 'import pickle\n'), ((1760, 1785), 'pickle.dump', 'pickle.dump', (['now', 'outfile'], {}), '(now, outfile)\n', (1771, 1785), False, 'import pickle\n'), ((3899, 3924), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3914, 3924), False, 'import os, sys, sip, time\n'), ((6425, 6448), 'qtpy.QtWidgets.QTreeWidgetItem', 'QTreeWidgetItem', (['parent'], {}), '(parent)\n', (6440, 6448), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((13972, 14011), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Delete"""', 'menu'], {'checkable': '(True)'}), "('Delete', menu, checkable=True)\n", (13979, 14011), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((1198, 1224), 'pickle.dump', 'pickle.dump', (['data', 'outfile'], {}), '(data, outfile)\n', (1209, 1224), False, 'import pickle\n'), ((1347, 1372), 'pickle.dump', 'pickle.dump', (['now', 'outfile'], {}), '(now, outfile)\n', (1358, 1372), False, 'import pickle\n'), ((10666, 10704), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Kline"""', 'menu'], {'checkable': '(True)'}), "('Kline', menu, checkable=True)\n", (10673, 10704), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((10741, 10778), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Open"""', 'menu'], {'checkable': '(True)'}), "('Open', menu, checkable=True)\n", (10748, 10778), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((10815, 10853), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Close"""', 'menu'], {'checkable': '(True)'}), "('Close', menu, checkable=True)\n", (10822, 10853), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((10943, 10980), 'qtpy.QtWidgets.QAction', 'QAction', (['"""High"""', 'menu'], {'checkable': '(True)'}), "('High', menu, checkable=True)\n", (10950, 10980), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11017, 11053), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Low"""', 'menu'], {'checkable': '(True)'}), "('Low', menu, checkable=True)\n", (11024, 11053), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11090, 11129), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Volume"""', 'menu'], {'checkable': '(True)'}), "('Volume', menu, checkable=True)\n", (11097, 11129), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11380, 11418), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Kline"""', 'menu'], {'checkable': '(True)'}), "('Kline', menu, checkable=True)\n", (11387, 11418), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11455, 11492), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Open"""', 'menu'], {'checkable': '(True)'}), "('Open', menu, checkable=True)\n", (11462, 11492), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11529, 11567), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Close"""', 'menu'], {'checkable': '(True)'}), "('Close', menu, checkable=True)\n", (11536, 11567), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11604, 11641), 'qtpy.QtWidgets.QAction', 'QAction', (['"""High"""', 'menu'], {'checkable': '(True)'}), "('High', menu, checkable=True)\n", (11611, 11641), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11678, 11714), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Low"""', 'menu'], {'checkable': '(True)'}), "('Low', menu, checkable=True)\n", (11685, 11714), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11751, 11790), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Volume"""', 'menu'], {'checkable': '(True)'}), "('Volume', menu, checkable=True)\n", (11758, 11790), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11827, 11866), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Amount"""', 'menu'], {'checkable': '(True)'}), "('Amount', menu, checkable=True)\n", (11834, 11866), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((11963, 11998), 'qtpy.QtWidgets.QAction', 'QAction', (['"""分笔"""', 'menu'], {'checkable': '(True)'}), "('分笔', menu, checkable=True)\n", (11970, 11998), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12095, 12133), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Kline"""', 'menu'], {'checkable': '(True)'}), "('Kline', menu, checkable=True)\n", (12102, 12133), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12170, 12207), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Open"""', 'menu'], {'checkable': '(True)'}), "('Open', menu, checkable=True)\n", (12177, 12207), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12244, 12282), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Close"""', 'menu'], {'checkable': '(True)'}), "('Close', menu, checkable=True)\n", (12251, 12282), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12319, 12356), 'qtpy.QtWidgets.QAction', 'QAction', (['"""High"""', 'menu'], {'checkable': '(True)'}), "('High', menu, checkable=True)\n", (12326, 12356), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12393, 12429), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Low"""', 'menu'], {'checkable': '(True)'}), "('Low', menu, checkable=True)\n", (12400, 12429), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12466, 12505), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Volume"""', 'menu'], {'checkable': '(True)'}), "('Volume', menu, checkable=True)\n", (12473, 12505), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12542, 12581), 'qtpy.QtWidgets.QAction', 'QAction', (['"""Amount"""', 'menu'], {'checkable': '(True)'}), "('Amount', menu, checkable=True)\n", (12549, 12581), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((12678, 12715), 'qtpy.QtWidgets.QAction', 'QAction', (['"""季度饼图"""', 'menu'], {'checkable': '(True)'}), "('季度饼图', menu, checkable=True)\n", (12685, 12715), False, 'from qtpy.QtWidgets import QTreeWidgetItem, QMenu, QApplication, QAction, QMainWindow\n'), ((829, 843), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (841, 843), False, 'from datetime import datetime, timedelta\n')] |
# Licensed to the Encore Technologies ("Encore") under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os.path
from setuptools import setup, find_packages
from pip.req import parse_requirements
from menandmice import __version__
def fetch_requirements(requirements_file_path):
"""
Return a list of requirements and links by parsing the provided requirements file.
"""
links = []
reqs = []
for req in parse_requirements(requirements_file_path, session=False):
if req.link:
links.append(str(req.link))
reqs.append(str(req.req))
return (reqs, links)
PACKAGE_NAME = 'menandmice'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
REQUIREMENTS_FILE = os.path.join(BASE_DIR, 'requirements.txt')
install_reqs, dep_links = fetch_requirements(REQUIREMENTS_FILE)
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name=PACKAGE_NAME,
version=__version__,
description='Python bindings for the Men&Mice IPAM REST API ',
long_description=readme,
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/EncoreTechnologies/py-menandmice',
license=license,
install_requires=install_reqs,
dependency_links=dep_links,
test_suite="nose.collector",
tests_require=["nose", "mock"],
packages=find_packages(exclude=['tests'])
)
| [
"pip.req.parse_requirements",
"setuptools.find_packages"
] | [((1117, 1174), 'pip.req.parse_requirements', 'parse_requirements', (['requirements_file_path'], {'session': '(False)'}), '(requirements_file_path, session=False)\n', (1135, 1174), False, 'from pip.req import parse_requirements\n'), ((2044, 2076), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests']"}), "(exclude=['tests'])\n", (2057, 2076), False, 'from setuptools import setup, find_packages\n')] |
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Recall metric."""
from sklearn.metrics import recall_score
import datasets
_DESCRIPTION = """
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""
_KWARGS_DESCRIPTION = """
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.
- `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
- `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
- `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
- `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.
- `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
- `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
- `0`: If there is a zero division, the return value is `0`.
- `1`: If there is a zero division, the return value is `1`.
Returns:
- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.
Examples:
Example 1-A simple example with some errors
>>> recall_metric = datasets.load_metric('recall')
>>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
>>> print(results)
{'recall': 0.6666666666666666}
Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
>>> recall_metric = datasets.load_metric('recall')
>>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
>>> print(results)
{'recall': 0.5}
Example 3-The same example as Example 1, but with `sample_weight` included.
>>> recall_metric = datasets.load_metric('recall')
>>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
>>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
>>> print(results)
{'recall': 0.55}
Example 4-A multiclass example, using different averages.
>>> recall_metric = datasets.load_metric('recall')
>>> predictions = [0, 2, 1, 0, 0, 1]
>>> references = [0, 1, 2, 0, 1, 2]
>>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
>>> print(results)
{'recall': 0.3333333333333333}
>>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
>>> print(results)
{'recall': 0.3333333333333333}
>>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
>>> print(results)
{'recall': 0.3333333333333333}
>>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
>>> print(results)
{'recall': array([1., 0., 0.])}
"""
_CITATION = """
@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={<NAME> <NAME> <NAME> <NAME> <NAME>.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class Recall(datasets.Metric):
def _info(self):
return datasets.MetricInfo(
description=_DESCRIPTION,
citation=_CITATION,
inputs_description=_KWARGS_DESCRIPTION,
features=datasets.Features(
{
"predictions": datasets.Sequence(datasets.Value("int32")),
"references": datasets.Sequence(datasets.Value("int32")),
}
if self.config_name == "multilabel"
else {
"predictions": datasets.Value("int32"),
"references": datasets.Value("int32"),
}
),
reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"],
)
def _compute(
self,
predictions,
references,
labels=None,
pos_label=1,
average="binary",
sample_weight=None,
zero_division="warn",
):
score = recall_score(
references,
predictions,
labels=labels,
pos_label=pos_label,
average=average,
sample_weight=sample_weight,
zero_division=zero_division,
)
return {"recall": float(score) if score.size == 1 else score}
| [
"datasets.utils.file_utils.add_start_docstrings",
"datasets.Value",
"sklearn.metrics.recall_score"
] | [((5732, 5817), 'datasets.utils.file_utils.add_start_docstrings', 'datasets.utils.file_utils.add_start_docstrings', (['_DESCRIPTION', '_KWARGS_DESCRIPTION'], {}), '(_DESCRIPTION,\n _KWARGS_DESCRIPTION)\n', (5778, 5817), False, 'import datasets\n'), ((6833, 6985), 'sklearn.metrics.recall_score', 'recall_score', (['references', 'predictions'], {'labels': 'labels', 'pos_label': 'pos_label', 'average': 'average', 'sample_weight': 'sample_weight', 'zero_division': 'zero_division'}), '(references, predictions, labels=labels, pos_label=pos_label,\n average=average, sample_weight=sample_weight, zero_division=zero_division)\n', (6845, 6985), False, 'from sklearn.metrics import recall_score\n'), ((6367, 6390), 'datasets.Value', 'datasets.Value', (['"""int32"""'], {}), "('int32')\n", (6381, 6390), False, 'import datasets\n'), ((6426, 6449), 'datasets.Value', 'datasets.Value', (['"""int32"""'], {}), "('int32')\n", (6440, 6449), False, 'import datasets\n'), ((6135, 6158), 'datasets.Value', 'datasets.Value', (['"""int32"""'], {}), "('int32')\n", (6149, 6158), False, 'import datasets\n'), ((6213, 6236), 'datasets.Value', 'datasets.Value', (['"""int32"""'], {}), "('int32')\n", (6227, 6236), False, 'import datasets\n')] |
# Find simplified formula for bank balance sheet change as a result of
# ELA collateral seizure
# <NAME>
# MIT License
################################################################################
# Import SymPy
import sympy as sp
from sympy.abc import eta, gamma
# Define symbols (eta and gamma imported)
A, AD = sp.symbols('A A_d')
print(sp.latex(lambdaA))
#######
# Expanded form expression for the change in non-performing loans after ELA
# collateral seizure
expr_npl1 = (gamma * A) / A
expr_npl2 = (gamma * A - eta * gamma * AD)/ (A - AD)
# Subtract and print simplified form as LaTeX
print(sp.latex((expr_npl1 - expr_npl2)))
| [
"sympy.symbols",
"sympy.latex"
] | [((319, 338), 'sympy.symbols', 'sp.symbols', (['"""A A_d"""'], {}), "('A A_d')\n", (329, 338), True, 'import sympy as sp\n'), ((346, 363), 'sympy.latex', 'sp.latex', (['lambdaA'], {}), '(lambdaA)\n', (354, 363), True, 'import sympy as sp\n'), ((605, 636), 'sympy.latex', 'sp.latex', (['(expr_npl1 - expr_npl2)'], {}), '(expr_npl1 - expr_npl2)\n', (613, 636), True, 'import sympy as sp\n')] |
"""
Versions of the base functionality optimized for the NT kernel.
The 9x kernel is just unsupported.
"""
import ctypes
import _winapi
import signal
from . import base
__all__ = ('Process', 'ProcessGroup')
# {{{ win32 API calls
def _falsey_errcheck(result, func, arguments):
if not result:
raise ctypes.WinError()
return arguments
def _truthy_errcheck_nt(result, func, arguments):
if result:
raise OSError(None, "NT Error", None, result)
return arguments
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = [("Length", ctypes.wintypes.DWORD),
("SecDescriptor", ctypes.wintypes.LPVOID),
("InheritHandle", ctypes.wintypes.BOOL)]
CreateJobObject = ctypes.windll.kernel32.CreateJobObjectW
CreateJobObject.argtypes = (ctypes.POINTER(SECURITY_ATTRIBUTES), ctypes.wintypes.LPCWSTR)
CreateJobObject.restype = ctypes.wintypes.HANDLE
CreateJobObject.errcheck = _falsey_errcheck
AssignProcessToJobObject = ctypes.windll.kernel32.AssignProcessToJobObject
AssignProcessToJobObject.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.UINT)
AssignProcessToJobObject.restype = ctypes.wintypes.BOOL
AssignProcessToJobObject.errcheck = _falsey_errcheck
TerminateJobObject = ctypes.windll.kernel32.TerminateJobObject
TerminateJobObject.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.HANDLE)
TerminateJobObject.restype = ctypes.wintypes.BOOL
TerminateJobObject.errcheck = _falsey_errcheck
CloseHandle = _winapi.CloseHandle
OpenProcess = _winapi.OpenProcess
PROCESS_SUSPEND_RESUME = 0x0800
NtSuspendProcess = ctypes.windll.ntdll.NtSuspendProcess
NtSuspendProcess.argtypes = (ctypes.wintypes.HANDLE,)
NtSuspendProcess.restype = ctypes.c_long
NtSuspendProcess.errcheck = _truthy_errcheck_nt
NtResumeProcess = ctypes.windll.ntdll.NtResumeProcess
NtResumeProcess.argtypes = (ctypes.wintypes.HANDLE,)
NtResumeProcess.restype = ctypes.c_long
NtResumeProcess.errcheck = _truthy_errcheck_nt
# }}}
class Process(base.Process):
# https://groups.google.com/d/topic/microsoft.public.win32.programmer.kernel/IA-y-isvL9I/discussion
# Note: Because Cygwin has complete control of all the processes, it does other things.
# We don't have control of our children, so we can't do those things.
def pause(self):
"""
Pause the process, able to be continued later
"""
if self.pid is not None:
hproc = OpenProcess(PROCESS_SUSPEND_RESUME, False, self.pid)
try:
NtSuspendProcess(hproc)
finally:
CloseHandle(hproc)
def unpause(self):
"""
Continue the process after it's been paused
"""
if self.pid is not None:
hproc = OpenProcess(PROCESS_SUSPEND_RESUME, False, self.pid)
try:
NtResumeProcess(hproc)
finally:
CloseHandle(hproc)
class ProcessGroup(base.ProcessGroup):
def __init__(self):
super().__init__()
self.job = CreateJobObject(None, None)
def __del__(self):
CloseHandle(self.job)
self.job = None
# __contains__ with IsProcessInJob? No matching __iter__.
def add(self, proc):
super().add(proc)
if proc.started and not isinstance(proc, base.VirtualProcess):
# _handle is subprocess.Popen internal. Beats looking up the process ourselves.
AssignProcessToJobObject(self.job, proc._proc._handle)
def start(self):
super().start()
for proc in self:
if isinstance(proc, base.VirtualProcess):
continue
# _handle is subprocess.Popen internal. Beats looking up the process ourselves.
# FIXME: Handle if the process was already joined to us
AssignProcessToJobObject(self.job, proc._proc._handle)
def signal(self, sig):
"""
Signal the process of an event.
"""
if sig == signal.SIGKILL:
self.kill()
elif sig == signal.SIGTERM:
self.terminate()
else:
super().signal(sig)
def kill(self):
TerminateJobObject(self.job, -9)
for proc in self:
if isinstance(proc, base.VirtualProcess):
proc.kill()
def terminate(self):
TerminateJobObject(self.job, -9)
for proc in self:
if isinstance(proc, base.VirtualProcess):
proc.terminate()
| [
"ctypes.WinError",
"ctypes.POINTER"
] | [((797, 832), 'ctypes.POINTER', 'ctypes.POINTER', (['SECURITY_ATTRIBUTES'], {}), '(SECURITY_ATTRIBUTES)\n', (811, 832), False, 'import ctypes\n'), ((314, 331), 'ctypes.WinError', 'ctypes.WinError', ([], {}), '()\n', (329, 331), False, 'import ctypes\n')] |
import collections
import logging
import asyncio
import importlib
import pip
import toastbot.toast as toast
try:
import discord
import discord.ext.commands as commands
except ImportError:
print('Installing discord package...')
pip.main(['install', 'discord'])
import discord
import discord.ext.commands as commands
finally:
print('Importing discord package...')
globals()['discord'] = importlib.import_module('discord')
globals()['commands'] = importlib.import_module('discord.ext.commands')
import toastbot.configuration as botconf
import toastbot.defaultlogger as logger
import toastbot.botfunctions.diceroller as diceroller
import toastbot.botfunctions.logbot as logbot
DEFAULT_API_CREDENTIALS_LOCATION = "configuration/api_keys.txt"
DEFAULT_CONFIG_LOCATION = "configuration/config.txt"
DEFAULT_BOT_TOKEN_SECTION = 'discord'
DEFAULT_BOT_TOKEN_VALUE_NAME = 'BotToken'
DEFAULT_LOGGING_SECTION = 'logging'
DEFAULT_LOG_LEVEL_VALUE_NAME = 'LogLevel'
def _monospace_message(str):
msg = "`{str}`".format(str=str)
return msg
def _create_roll_response(roll_results, author_name):
if len(roll_results.raw_rolls) > 10:
msg_template = _create_long_roll_response(roll_results, author_name)
else:
msg_template = _create_simple_roll_response(roll_results, author_name)
return msg_template
def _create_simple_roll_response(roll_results, author_name):
msg_template = "\nAuthor: {author}\n" \
"{roll_results}".format(author=author_name, roll_results=str(roll_results))
return msg_template
def _create_long_roll_response(roll_results, author_name):
value_counter = collections.Counter(roll_results.raw_rolls)
mod_value_counter = collections.Counter(roll_results.modified_rolls)
raw_vals = list(value_counter.keys())
raw_vals.sort()
mod_vals = list(mod_value_counter.keys())
mod_vals.sort()
count = [value_counter[value] for value in raw_vals]
values = [len(str(x)) for x in raw_vals + mod_vals + count]
pad_len = max(values)
results_table = [
'{mod_val} ({raw_val}): {count}'.format(
mod_val=str(mod).ljust(pad_len, ' '),
raw_val=str(raw).ljust(pad_len, ' '),
count=str(count).ljust(pad_len, ' ')
)
for mod, raw, count
in zip(mod_vals, raw_vals, count)
]
formatted_colnames = "Value (Unmodified): Count"
msg_base = [
"\nAuthor: {author}".format(author=author_name),
formatted_colnames
]
result_msg = '\n'.join(msg_base + results_table)
return result_msg
def init_logging():
config = botconf.read_api_configuration(DEFAULT_CONFIG_LOCATION)
logging_level_setting = config[DEFAULT_LOGGING_SECTION][DEFAULT_LOG_LEVEL_VALUE_NAME]
logging_level = logger.LOG_LEVEL_MAP[logging_level_setting]
logger.init_logging(level=logging_level)
logging.info('Logging initialized, level: {}'.format(logging_level_setting))
def main():
init_logging()
bot_prefix = "!"
logging.debug('Bot prefix set to: {}'.format(bot_prefix))
logging.info('Initializing Discord Bot...')
bot = toast.ToastBot(command_prefix=bot_prefix, pm_help=True)
logging.info('Initializing Dicebot...')
dice = diceroller.Dicebot()
engine = logbot.initialize_engine()
session = logbot.create_session(engine)
@bot.event
@asyncio.coroutine
def on_ready():
logging.info("Bot online!")
@bot.command(pass_context=True)
@asyncio.coroutine
def test(context):
author = context.message.author
logging.info('Bot received test command from {}'.format(author))
msg_text = "\nAuthor: {author}\nBot is online.".format(author=author.display_name)
msg_text = _monospace_message(msg_text)
logging.info('Bot responded to test command.')
yield from bot.say(content=msg_text)
help_roll = ("- Roll dice: !roll <i>d<j>[+-][k] - type !help roll for more details.\n"
"i = # of dice\n"
"j = # of sides per die\n"
"k = # to add or subtract from each die\n"
"Elements in square brackets are optional.\n"
"Ex. !roll 2d10+5, or !roll 1d20"
)
@bot.command(pass_context=True, help=help_roll)
@asyncio.coroutine
def roll(context):
author = context.message.author
logging.info('Bot received roll command from {}.'.format(author))
try:
results = dice.roll(context.message.content)
msg_text = _create_roll_response(results, author.display_name)
except diceroller.DiceRollFormatError:
msg_text = "Valid dice roll command not found. Command: {}\nType !help roll for dice-rolling help.".format(
context.message.content
)
msg_text = _monospace_message(msg_text)
logging.info('Bot responded to roll command.')
yield from bot.say(content=msg_text)
help_startlog = (
"- Start logging: !startlog <log name>-<Name 1>-<Name 2>-...-<Name N>\n"
"Start logging by naming the log, and adding the displayed names of players.\n"
"The log name will be used to end the log at the end of the event."
)
@bot.command(pass_context=True, help=help_startlog)
@asyncio.coroutine
def startlog(context):
logging.info('Initializing log...')
command = context.message.content
split_command = command.split(' ')
try:
command_contents = split_command[1]
command_params = command_contents.split('-')
command_log_name = command_params[0]
command_characters = command_params[1:]
except IndexError:
error_msg = 'Error: Not all parameters specified for log start. Use !help startlog for more info.'
yield from bot.say(content=error_msg)
else:
log_initialized_timestamp = context.message.timestamp
initialized_info_string = 'Started log {} at {}\nCharacters: {}.'.format(
command_log_name, log_initialized_timestamp, '; '.join(command_characters))
logging.info(initialized_info_string)
created_session = logbot.create_session(engine)
logbot.add_log(created_session, command_log_name, log_initialized_timestamp)
log_id = logbot.get_log_id(created_session, command_log_name, log_initialized_timestamp)
for name in command_params[1:]:
logging.info('Found names in command: {}'.format('; '.join(command_characters)))
try:
logbot.LogSessionConfigs.add_log_to_user(name, log_id)
except KeyError:
logbot.LogSessionConfigs.add_user(name)
logbot.LogSessionConfigs.add_log_to_user(name, log_id)
yield from bot.say(content=initialized_info_string)
@bot.listen('on_message')
@asyncio.coroutine
def listen_for_text(message):
try:
author_name = message.author.nick if message.author.nick is not None else message.author.name
except AttributeError:
author_name = message.author.name
logging.info('Heard message from {}.'.format(author_name))
if author_name in logbot.LogSessionConfigs.active_logs:
logging.info('User in active log.')
created_session = logbot.create_session(engine)
for log_id in logbot.LogSessionConfigs.active_logs[author_name]:
created_session = logbot.add_new_text(
session=created_session,
timestamp=message.timestamp,
character_name=author_name,
username=message.author.name,
text=message.content,
log_id=log_id
)
help_endlog = (
"- End logging: !endlog <log name>-<Name 1>-<Name 2>-...-<Name N>\n"
"End the log with this command."
)
@bot.command(pass_context=True, help=help_endlog)
@asyncio.coroutine
def endlog(context):
try:
log_name = context.message.content.split(' ')[1]
created_session = logbot.create_session(engine)
except IndexError:
yield from bot.say('Please specify name of log to end.')
else:
log_id = logbot.get_log_id(created_session, log_name)
for character in list(logbot.LogSessionConfigs.active_logs):
if len(logbot.LogSessionConfigs.active_logs[character]) == 1:
del logbot.LogSessionConfigs.active_logs[character]
else:
logbot.LogSessionConfigs.active_logs[character].remove(log_id)
ended_info_string = 'Ended log {name}.'.format(name=log_name)
logging.info(ended_info_string)
yield from bot.say(ended_info_string)
@bot.command(pass_context=True)
@asyncio.coroutine
def getlog(context):
requestor = context.message.author
try:
log_name = context.message.content.split(' ')[1]
except IndexError:
yield from bot.say('Please specify log to receive.')
else:
created_session = logbot.create_session(engine)
log_id = logbot.get_log_id(created_session, log_name)
responses = logbot.get_text(created_session, log_id)
full_text = [str(response) for response in responses]
full_text = '\n'.join(full_text)
yield from bot.send_message(requestor, full_text)
logging.info('Retrieving API details...')
config = botconf.read_api_configuration(DEFAULT_API_CREDENTIALS_LOCATION)
token = config[DEFAULT_BOT_TOKEN_SECTION][DEFAULT_BOT_TOKEN_VALUE_NAME]
logging.info('Running bot...')
bot.run(token)
logging.info('Script finished.')
if __name__ == "__main__":
main()
| [
"importlib.import_module",
"toastbot.botfunctions.logbot.get_log_id",
"toastbot.toast.ToastBot",
"toastbot.configuration.read_api_configuration",
"collections.Counter",
"toastbot.botfunctions.logbot.get_text",
"toastbot.defaultlogger.init_logging",
"toastbot.botfunctions.logbot.LogSessionConfigs.add_l... | [((420, 454), 'importlib.import_module', 'importlib.import_module', (['"""discord"""'], {}), "('discord')\n", (443, 454), False, 'import importlib\n'), ((483, 530), 'importlib.import_module', 'importlib.import_module', (['"""discord.ext.commands"""'], {}), "('discord.ext.commands')\n", (506, 530), False, 'import importlib\n'), ((1669, 1712), 'collections.Counter', 'collections.Counter', (['roll_results.raw_rolls'], {}), '(roll_results.raw_rolls)\n', (1688, 1712), False, 'import collections\n'), ((1737, 1785), 'collections.Counter', 'collections.Counter', (['roll_results.modified_rolls'], {}), '(roll_results.modified_rolls)\n', (1756, 1785), False, 'import collections\n'), ((2644, 2699), 'toastbot.configuration.read_api_configuration', 'botconf.read_api_configuration', (['DEFAULT_CONFIG_LOCATION'], {}), '(DEFAULT_CONFIG_LOCATION)\n', (2674, 2699), True, 'import toastbot.configuration as botconf\n'), ((2858, 2898), 'toastbot.defaultlogger.init_logging', 'logger.init_logging', ([], {'level': 'logging_level'}), '(level=logging_level)\n', (2877, 2898), True, 'import toastbot.defaultlogger as logger\n'), ((3101, 3144), 'logging.info', 'logging.info', (['"""Initializing Discord Bot..."""'], {}), "('Initializing Discord Bot...')\n", (3113, 3144), False, 'import logging\n'), ((3155, 3210), 'toastbot.toast.ToastBot', 'toast.ToastBot', ([], {'command_prefix': 'bot_prefix', 'pm_help': '(True)'}), '(command_prefix=bot_prefix, pm_help=True)\n', (3169, 3210), True, 'import toastbot.toast as toast\n'), ((3215, 3254), 'logging.info', 'logging.info', (['"""Initializing Dicebot..."""'], {}), "('Initializing Dicebot...')\n", (3227, 3254), False, 'import logging\n'), ((3266, 3286), 'toastbot.botfunctions.diceroller.Dicebot', 'diceroller.Dicebot', ([], {}), '()\n', (3284, 3286), True, 'import toastbot.botfunctions.diceroller as diceroller\n'), ((3301, 3327), 'toastbot.botfunctions.logbot.initialize_engine', 'logbot.initialize_engine', ([], {}), '()\n', (3325, 3327), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((3342, 3371), 'toastbot.botfunctions.logbot.create_session', 'logbot.create_session', (['engine'], {}), '(engine)\n', (3363, 3371), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((9612, 9653), 'logging.info', 'logging.info', (['"""Retrieving API details..."""'], {}), "('Retrieving API details...')\n", (9624, 9653), False, 'import logging\n'), ((9667, 9731), 'toastbot.configuration.read_api_configuration', 'botconf.read_api_configuration', (['DEFAULT_API_CREDENTIALS_LOCATION'], {}), '(DEFAULT_API_CREDENTIALS_LOCATION)\n', (9697, 9731), True, 'import toastbot.configuration as botconf\n'), ((9812, 9842), 'logging.info', 'logging.info', (['"""Running bot..."""'], {}), "('Running bot...')\n", (9824, 9842), False, 'import logging\n'), ((9866, 9898), 'logging.info', 'logging.info', (['"""Script finished."""'], {}), "('Script finished.')\n", (9878, 9898), False, 'import logging\n'), ((246, 278), 'pip.main', 'pip.main', (["['install', 'discord']"], {}), "(['install', 'discord'])\n", (254, 278), False, 'import pip\n'), ((3439, 3466), 'logging.info', 'logging.info', (['"""Bot online!"""'], {}), "('Bot online!')\n", (3451, 3466), False, 'import logging\n'), ((3811, 3857), 'logging.info', 'logging.info', (['"""Bot responded to test command."""'], {}), "('Bot responded to test command.')\n", (3823, 3857), False, 'import logging\n'), ((4902, 4948), 'logging.info', 'logging.info', (['"""Bot responded to roll command."""'], {}), "('Bot responded to roll command.')\n", (4914, 4948), False, 'import logging\n'), ((5383, 5418), 'logging.info', 'logging.info', (['"""Initializing log..."""'], {}), "('Initializing log...')\n", (5395, 5418), False, 'import logging\n'), ((6182, 6219), 'logging.info', 'logging.info', (['initialized_info_string'], {}), '(initialized_info_string)\n', (6194, 6219), False, 'import logging\n'), ((6250, 6279), 'toastbot.botfunctions.logbot.create_session', 'logbot.create_session', (['engine'], {}), '(engine)\n', (6271, 6279), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((6292, 6368), 'toastbot.botfunctions.logbot.add_log', 'logbot.add_log', (['created_session', 'command_log_name', 'log_initialized_timestamp'], {}), '(created_session, command_log_name, log_initialized_timestamp)\n', (6306, 6368), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((6390, 6469), 'toastbot.botfunctions.logbot.get_log_id', 'logbot.get_log_id', (['created_session', 'command_log_name', 'log_initialized_timestamp'], {}), '(created_session, command_log_name, log_initialized_timestamp)\n', (6407, 6469), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((7367, 7402), 'logging.info', 'logging.info', (['"""User in active log."""'], {}), "('User in active log.')\n", (7379, 7402), False, 'import logging\n'), ((7433, 7462), 'toastbot.botfunctions.logbot.create_session', 'logbot.create_session', (['engine'], {}), '(engine)\n', (7454, 7462), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((8233, 8262), 'toastbot.botfunctions.logbot.create_session', 'logbot.create_session', (['engine'], {}), '(engine)\n', (8254, 8262), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((8394, 8438), 'toastbot.botfunctions.logbot.get_log_id', 'logbot.get_log_id', (['created_session', 'log_name'], {}), '(created_session, log_name)\n', (8411, 8438), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((8853, 8884), 'logging.info', 'logging.info', (['ended_info_string'], {}), '(ended_info_string)\n', (8865, 8884), False, 'import logging\n'), ((9273, 9302), 'toastbot.botfunctions.logbot.create_session', 'logbot.create_session', (['engine'], {}), '(engine)\n', (9294, 9302), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((9324, 9368), 'toastbot.botfunctions.logbot.get_log_id', 'logbot.get_log_id', (['created_session', 'log_name'], {}), '(created_session, log_name)\n', (9341, 9368), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((9393, 9433), 'toastbot.botfunctions.logbot.get_text', 'logbot.get_text', (['created_session', 'log_id'], {}), '(created_session, log_id)\n', (9408, 9433), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((7574, 7751), 'toastbot.botfunctions.logbot.add_new_text', 'logbot.add_new_text', ([], {'session': 'created_session', 'timestamp': 'message.timestamp', 'character_name': 'author_name', 'username': 'message.author.name', 'text': 'message.content', 'log_id': 'log_id'}), '(session=created_session, timestamp=message.timestamp,\n character_name=author_name, username=message.author.name, text=message.\n content, log_id=log_id)\n', (7593, 7751), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((6652, 6706), 'toastbot.botfunctions.logbot.LogSessionConfigs.add_log_to_user', 'logbot.LogSessionConfigs.add_log_to_user', (['name', 'log_id'], {}), '(name, log_id)\n', (6692, 6706), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((6760, 6799), 'toastbot.botfunctions.logbot.LogSessionConfigs.add_user', 'logbot.LogSessionConfigs.add_user', (['name'], {}), '(name)\n', (6793, 6799), True, 'import toastbot.botfunctions.logbot as logbot\n'), ((6820, 6874), 'toastbot.botfunctions.logbot.LogSessionConfigs.add_log_to_user', 'logbot.LogSessionConfigs.add_log_to_user', (['name', 'log_id'], {}), '(name, log_id)\n', (6860, 6874), True, 'import toastbot.botfunctions.logbot as logbot\n')] |
import time
from alpha_vantage.fundamentaldata import FundamentalData
def fundamental_download_case(case: int,
ticker: str,
fd):
'''
Due to the API limit of 5 calls per minute, this function was desinged so
that every 5th download can impose a sleep time of a minute.
Parameters
----------
case : int
The download switch statement.
ticker : str
The ticker to download the data for
fd : Fundamental Data Downloader
The fundamental data downloader for AlphaVantage.
Returns
-------
None
'''
if case == 0:
annual_IS = fd.get_income_statement_annual(ticker)
annual_IS[0].to_csv(f'../../data/{ticker}_annual_IS.csv', index = False)
elif case == 1:
annual_BS = fd.get_balance_sheet_annual(ticker)
annual_BS[0].to_csv(f'../../data/{ticker}_annual_BS.csv', index = False)
elif case == 2:
annual_CF = fd.get_cash_flow_annual(ticker)
annual_CF[0].to_csv(f'../../data/{ticker}_annual_CF.csv', index = False)
if case == 3:
quarterly_IS = fd.get_income_statement_quarterly(ticker)
quarterly_IS[0].to_csv(f'../../data/{ticker}_quarterly_IS.csv', index = False)
elif case == 4:
quarterly_BS = fd.get_balance_sheet_quarterly(ticker)
quarterly_BS[0].to_csv(f'../../data/{ticker}_quarterly_BS.csv', index = False)
elif case == 5:
quarterly_CF = fd.get_cash_flow_quarterly(ticker)
quarterly_CF[0].to_csv(f'../../data/{ticker}_quarterly_CF.csv', index = False)
return
def get_historical_fundamentals(ticker_list: list,
api_key: str):
'''
Using the AlphaVantage API, obtain the historical fundamental data for a
set of tickers
Parameters
----------
ticker_list : list
The list of tickers to download the fundamentals for
api_key : str
The AlphaVantage API key
Returns
-------
None
Notes
-----
On a free API key, only 500 calls per day are allowed. Given that this
function downloads 6 different statements, a maximum of 83 tickers can be
considered. Likewise, only 5 API calls can be made per minute, so a sleep
step is included at every 5 downloads.
'''
fd = FundamentalData(api_key,
output_format = 'pandas',
)
download = 0
incomplete_downloads = []
print('Downloading the fundamental stock data.\n\nTickers completed:')
try:
for ticker in ticker_list:
# Looping over each download case, for both annual and quarterly we have:
# - IS = Income Statement
# - BS = Balance Sheet
# - CF = Cash Flow
for case in range(0, 6):
fundamental_download_case(case, ticker, fd)
download += 1
# This step ensures the 5 API calls per minute are not exceeded
if download%5 == 0:
time.sleep(65)
print(ticker)
except:
incomplete_downloads.append(ticker)
print(f'{ticker} - failed download')
time.sleep(65)
download = 0
return incomplete_downloads
api_key = 'INSERT'
ticker_list = ['TROW', 'VIAC', 'ZION', 'INFO', 'TTWO', 'XLNX', 'ZTS', 'TMUS']
incomplete_downloads = get_historical_fundamentals(ticker_list,
api_key) | [
"alpha_vantage.fundamentaldata.FundamentalData",
"time.sleep"
] | [((2391, 2439), 'alpha_vantage.fundamentaldata.FundamentalData', 'FundamentalData', (['api_key'], {'output_format': '"""pandas"""'}), "(api_key, output_format='pandas')\n", (2406, 2439), False, 'from alpha_vantage.fundamentaldata import FundamentalData\n'), ((3307, 3321), 'time.sleep', 'time.sleep', (['(65)'], {}), '(65)\n', (3317, 3321), False, 'import time\n'), ((3135, 3149), 'time.sleep', 'time.sleep', (['(65)'], {}), '(65)\n', (3145, 3149), False, 'import time\n')] |
#Función que calcula la matriz resultante "C" después de aplicar la operación convolución de A*B=
# EJERCICIO 28 DE OCTUBRE
# <NAME> A01377098
import numpy as np
def convolucion (A, B):
contaFil = 0
contaCol = 0
limiteFil = len(A)
limiteCol = len(A)
longitudB = len(B)
for x in range (len(C)):
for y in range (len(C)):
for n in range (contaFil, len(B)+contaFil):
if len(B)+contaFil > limiteFil:
break
for o in range (contaCol, len(B)+contaCol):
if len(B)+contaCol> limiteCol:
break
C[x][y] += A[n][o] * B[n-contaFil][o-contaCol]
if contaCol+longitudB<limiteCol:
contaCol += 1
elif contaCol+longitudB== limiteCol:
contaCol = 0
if contaFil+longitudB< limiteFil:
contaFil += 1
elif contaFil+longitudB == limiteFil:
return
Matriz = [[6, 9, 0, 3], [8, 4, 9, 1], [4, 1, 3, 12], [3, 2, 1, 100]]
Filtro = [[1, 0, 2], [5, 0, 9], [6, 2, 1]]
A = np.array(Matriz)
B = np.array(Filtro)
C = np.zeros((2,2))
convolucion(A,B)
print (C)
| [
"numpy.array",
"numpy.zeros"
] | [((1153, 1169), 'numpy.array', 'np.array', (['Matriz'], {}), '(Matriz)\n', (1161, 1169), True, 'import numpy as np\n'), ((1174, 1190), 'numpy.array', 'np.array', (['Filtro'], {}), '(Filtro)\n', (1182, 1190), True, 'import numpy as np\n'), ((1196, 1212), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (1204, 1212), True, 'import numpy as np\n')] |
# Generated by Django 2.1.8 on 2020-05-27 15:24
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ArticleCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(blank=True, max_length=100)),
('created', models.DateField(default=datetime.datetime(2020, 5, 27, 15, 24, 34, 743876, tzinfo=utc))),
],
options={
'verbose_name': '类别管理',
'verbose_name_plural': '类别管理',
'db_table': 'tb_category',
},
),
]
| [
"datetime.datetime",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((365, 458), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (381, 458), False, 'from django.db import migrations, models\n'), ((483, 527), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(100)'}), '(blank=True, max_length=100)\n', (499, 527), False, 'from django.db import migrations, models\n'), ((583, 645), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(5)', '(27)', '(15)', '(24)', '(34)', '(743876)'], {'tzinfo': 'utc'}), '(2020, 5, 27, 15, 24, 34, 743876, tzinfo=utc)\n', (600, 645), False, 'import datetime\n')] |
from flask import Flask, render_template, redirect, session, request
import random
import datetime
app = Flask(__name__)
app.secret_key = "<KEY>"
@app.route('/')
def index():
if not 'gold' in session:
session['gold'] = 0
if not 'log' in session:
session['log'] = ["Thanks for joining the game!"]
return render_template('index.html')
@app.route('/reset', methods=['POST'])
def reset():
session.clear()
return redirect('/')
@app.route('/process_money', methods=['POST'])
def process():
when = datetime.datetime.now()
if request.form['arena'] == 'farm':
money = random.randint(10,20)
msg = "Baled some hay and earned " + str(money) + " gold (" + str(when) + ")"
session['log'].append(msg)
session['gold'] += money
elif request.form['arena'] == 'cave':
money = random.randint(5,10)
msg = "Mined some ore and earned " + str(money) + " gold (" + str(when) + ")"
session['log'].append(msg)
session['gold'] += money
elif request.form['arena'] == 'house':
money = random.randint(2,5)
msg = "Cleaned some dishes and earned " + str(money) + " gold (" + str(when) + ")"
session['log'].append(msg)
session['gold'] += money
else:
odds = random.randint(1,10)
if odds < 3:
money = random.randint(0,50)
msg = "Got lucky and won " + str(money) + " gold (" + str(when) + ")"
session['log'].append(msg)
session['gold'] += money
else:
money = random.randint(-50,0)
msg = "Lost " + str(abs(money)) + " gold at the casino (" + str(when) + ")"
session['log'].append(msg)
session['gold'] += money
return redirect('/')
app.run() | [
"flask.render_template",
"flask.Flask",
"flask.redirect",
"datetime.datetime.now",
"flask.session.clear",
"random.randint"
] | [((106, 121), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (111, 121), False, 'from flask import Flask, render_template, redirect, session, request\n'), ((312, 341), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (327, 341), False, 'from flask import Flask, render_template, redirect, session, request\n'), ((396, 411), 'flask.session.clear', 'session.clear', ([], {}), '()\n', (409, 411), False, 'from flask import Flask, render_template, redirect, session, request\n'), ((420, 433), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (428, 433), False, 'from flask import Flask, render_template, redirect, session, request\n'), ((505, 528), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (526, 528), False, 'import datetime\n'), ((1552, 1565), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (1560, 1565), False, 'from flask import Flask, render_template, redirect, session, request\n'), ((576, 598), 'random.randint', 'random.randint', (['(10)', '(20)'], {}), '(10, 20)\n', (590, 598), False, 'import random\n'), ((783, 804), 'random.randint', 'random.randint', (['(5)', '(10)'], {}), '(5, 10)\n', (797, 804), False, 'import random\n'), ((990, 1010), 'random.randint', 'random.randint', (['(2)', '(5)'], {}), '(2, 5)\n', (1004, 1010), False, 'import random\n'), ((1167, 1188), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (1181, 1188), False, 'import random\n'), ((1214, 1235), 'random.randint', 'random.randint', (['(0)', '(50)'], {}), '(0, 50)\n', (1228, 1235), False, 'import random\n'), ((1385, 1407), 'random.randint', 'random.randint', (['(-50)', '(0)'], {}), '(-50, 0)\n', (1399, 1407), False, 'import random\n')] |
import cv2 as cv
import matplotlib.pyplot as plt
import random as rd
import pandas as pd
from emotion_icon import load_emotion_icon
angry_man = None
all_image = load_emotion_icon()
# images = pd.DataFrame(all_image)
# print(all_image['angry_man'])
# load
# angry_man = cv.imread("./img/angry_man.jpg",-1)
# print(angry_man.shape)
# plt.imshow(all_image['angry_man'],'gray')
# cv.imshow("123",all_image['angry_man'])
# cv.waitKey(0);
rgb_image = cv.imread("./img/123.jpg",-1)
print(rgb_image.shape)
s_img = all_image["happy_man"]
# print(face_coordinates[:2])
x,y = rgb_image[:2]
print(s_img.shape)
x = 221
y = 80
x_offset = 0 +x
y_offset = -45 +y
y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]
alpha_s = s_img[:, :, 2] / 255.0
cv.imshow('alpha_s',alpha_s)
# cv.waitKey (0)
alpha_l = 1.0 - alpha_s
cv.imshow('alpha_l',alpha_l)
# cv.waitKey (0)
print(alpha_l.shape)
print(x_offset,y_offset)
for c in range(0, 3):
rgb_image[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
alpha_l * rgb_image[y1:y2, x1:x2, c])
cv.imshow('rgb_image',rgb_image)
cv.waitKey (0) | [
"emotion_icon.load_emotion_icon",
"cv2.waitKey",
"cv2.imread",
"cv2.imshow"
] | [((175, 194), 'emotion_icon.load_emotion_icon', 'load_emotion_icon', ([], {}), '()\n', (192, 194), False, 'from emotion_icon import load_emotion_icon\n'), ((473, 503), 'cv2.imread', 'cv.imread', (['"""./img/123.jpg"""', '(-1)'], {}), "('./img/123.jpg', -1)\n", (482, 503), True, 'import cv2 as cv\n'), ((813, 842), 'cv2.imshow', 'cv.imshow', (['"""alpha_s"""', 'alpha_s'], {}), "('alpha_s', alpha_s)\n", (822, 842), True, 'import cv2 as cv\n'), ((890, 919), 'cv2.imshow', 'cv.imshow', (['"""alpha_l"""', 'alpha_l'], {}), "('alpha_l', alpha_l)\n", (899, 919), True, 'import cv2 as cv\n'), ((1130, 1163), 'cv2.imshow', 'cv.imshow', (['"""rgb_image"""', 'rgb_image'], {}), "('rgb_image', rgb_image)\n", (1139, 1163), True, 'import cv2 as cv\n'), ((1164, 1177), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (1174, 1177), True, 'import cv2 as cv\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module handles API endpoints"""
# Import builtin python libraries
import json
import logging
import os
import sys
# Import external python libraries
import click
# Import custom (local) python packages
from . import dnac_handler as dnac
# Source code meta data
__author__ = "<NAME>"
__email__ = "<EMAIL>"
# Define API URL generator
def generate_api_url(host=None, api_type=None):
"""
This function creates appropriate API URL based on vendor and api call type
:param host: (str) IP or FQDN of DNAC
:param api_type: (str) API call type (name) e.g. generate-token, import-device
:return: (str) API endpoint
"""
if host is None:
host = dnac.host
api_collection = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "endpoints.json"
)
logging.debug(f"Endpoint file: {api_collection}")
if os.path.isfile(api_collection):
if os.access(api_collection, os.F_OK) and os.access(api_collection, os.R_OK):
logging.debug(f"[$] Reading API collection for [{api_type}].....")
with open(api_collection, "r") as collection:
api_collection = json.load(collection)
api_components = api_collection[api_type]
else:
click.secho(f"[X] Read permission error", fg="red")
sys.exit(1)
else:
click.secho(f"[x] Can't find API collection!", fg="red")
sys.exit(1)
protocol = api_components["protocol"]
api = api_components["api"]
method = api_components["method"]
parameters = api_components["parameters"]
api_url = f"{protocol}://{host}{api}"
logging.debug(f"[#] API endpoint URL created!")
return method, api_url, parameters
| [
"logging.debug",
"click.secho",
"os.access",
"os.path.isfile",
"os.path.realpath",
"sys.exit",
"json.load"
] | [((858, 907), 'logging.debug', 'logging.debug', (['f"""Endpoint file: {api_collection}"""'], {}), "(f'Endpoint file: {api_collection}')\n", (871, 907), False, 'import logging\n'), ((915, 945), 'os.path.isfile', 'os.path.isfile', (['api_collection'], {}), '(api_collection)\n', (929, 945), False, 'import os\n'), ((1680, 1727), 'logging.debug', 'logging.debug', (['f"""[#] API endpoint URL created!"""'], {}), "(f'[#] API endpoint URL created!')\n", (1693, 1727), False, 'import logging\n'), ((1399, 1455), 'click.secho', 'click.secho', (['f"""[x] Can\'t find API collection!"""'], {'fg': '"""red"""'}), '(f"[x] Can\'t find API collection!", fg=\'red\')\n', (1410, 1455), False, 'import click\n'), ((1464, 1475), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1472, 1475), False, 'import sys\n'), ((802, 828), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (818, 828), False, 'import os\n'), ((958, 992), 'os.access', 'os.access', (['api_collection', 'os.F_OK'], {}), '(api_collection, os.F_OK)\n', (967, 992), False, 'import os\n'), ((997, 1031), 'os.access', 'os.access', (['api_collection', 'os.R_OK'], {}), '(api_collection, os.R_OK)\n', (1006, 1031), False, 'import os\n'), ((1045, 1111), 'logging.debug', 'logging.debug', (['f"""[$] Reading API collection for [{api_type}]....."""'], {}), "(f'[$] Reading API collection for [{api_type}].....')\n", (1058, 1111), False, 'import logging\n'), ((1305, 1356), 'click.secho', 'click.secho', (['f"""[X] Read permission error"""'], {'fg': '"""red"""'}), "(f'[X] Read permission error', fg='red')\n", (1316, 1356), False, 'import click\n'), ((1369, 1380), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1377, 1380), False, 'import sys\n'), ((1203, 1224), 'json.load', 'json.load', (['collection'], {}), '(collection)\n', (1212, 1224), False, 'import json\n')] |
from django.shortcuts import redirect
def home(request):
return redirect('/ResumeParser') | [
"django.shortcuts.redirect"
] | [((66, 91), 'django.shortcuts.redirect', 'redirect', (['"""/ResumeParser"""'], {}), "('/ResumeParser')\n", (74, 91), False, 'from django.shortcuts import redirect\n')] |
"""
Module For the ScreenOptionsParser
"""
from conjur.version import __version__
from conjur.argument_parser.parser_utils import conjur_copyright
# pylint: disable=too-few-public-methods
class ScreenOptionsParser:
"""Partial class of the ArgParseBuilder.
This class add the ScreenOptions subparser to the ArgParseBuilder parser."""
def __init__(self):
self.parser = None # here to reduce warnings on parser not exist
raise NotImplementedError("this is partial class of ArgParseBuilder")
def add_main_screen_options(self):
"""
Method adds main screen options functionality to parser
"""
global_optional = self.parser.add_argument_group("Global options")
global_optional.add_argument('-h', '--help', action='help', help="Display help list")
global_optional.add_argument('-v', '--version', action='version',
help="Display version number",
version='Conjur CLI version ' + __version__ + "\n"
+ conjur_copyright())
global_optional.add_argument('-d', '--debug',
help='Enable debugging output',
action='store_true')
global_optional.add_argument('-i', '--insecure',
help='Skip verification of server certificate '
'(not recommended for production).\nThis makes your '
'system vulnerable to security attacks!\n',
dest='ssl_verify',
action='store_false')
return self
| [
"conjur.argument_parser.parser_utils.conjur_copyright"
] | [((1094, 1112), 'conjur.argument_parser.parser_utils.conjur_copyright', 'conjur_copyright', ([], {}), '()\n', (1110, 1112), False, 'from conjur.argument_parser.parser_utils import conjur_copyright\n')] |
# -*- coding: utf8 -*-
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="fledgling",
version="0.0.1",
author="Liutos",
author_email="<EMAIL>",
description="Client of nest",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/Liutos/fledgling",
project_urls={
"Bug Tracker": "https://github.com/Liutos/fledgling/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
packages=setuptools.find_packages(),
python_requires=">=3.6",
scripts=[
"bin/fledgling",
],
include_package_data=True,
install_requires=[
"click",
"cryptography",
"python-daemon",
"requests",
"tabulate",
"wcwidth",
"xdg",
],
)
| [
"setuptools.find_packages"
] | [((686, 712), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (710, 712), False, 'import setuptools\n')] |
import pyautogui
import time
def increase_volume():
i = 0
while i < 5:
pyautogui.press("volumeup")
i = i + 1
def decrease_volume():
i = 0
while i < 5:
pyautogui.press("volumedown")
i = i + 1
def switch_window():
pyautogui.keyDown('alt')
pyautogui.press('tab')
pyautogui.keyUp('alt')
def restore_down():
pyautogui.keyDown('win')
pyautogui.press('down')
pyautogui.keyUp('win')
def minimize_window():
pyautogui.keyDown('win')
pyautogui.press('down')
pyautogui.press('down')
pyautogui.keyUp('win')
def maximize_window():
pyautogui.keyDown('win')
pyautogui.press('up')
pyautogui.keyUp('win')
def copy():
pyautogui.keyDown('ctrl')
pyautogui.press('c')
pyautogui.keyUp('ctrl')
def cut():
pyautogui.keyDown('ctrl')
pyautogui.press('x')
pyautogui.keyUp('ctrl')
def paste():
pyautogui.keyDown('ctrl')
pyautogui.press('v')
pyautogui.keyUp('ctrl')
def select_all():
pyautogui.keyDown('ctrl')
pyautogui.press('a')
pyautogui.keyUp('ctrl')
def save():
pyautogui.keyDown('ctrl')
pyautogui.press('s')
pyautogui.keyUp('ctrl')
def save_as():
pyautogui.keyDown('ctrl')
pyautogui.keyDown('shift')
pyautogui.press('s')
pyautogui.keyUp('shift')
pyautogui.keyUp('ctrl')
def close_current_program():
pyautogui.keyDown('alt')
pyautogui.press('f4')
pyautogui.keyUp('alt')
def open_settings():
pyautogui.keyDown('win')
pyautogui.press('i')
pyautogui.keyUp('win')
| [
"pyautogui.press",
"pyautogui.keyDown",
"pyautogui.keyUp"
] | [((283, 307), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""alt"""'], {}), "('alt')\n", (300, 307), False, 'import pyautogui\n'), ((313, 335), 'pyautogui.press', 'pyautogui.press', (['"""tab"""'], {}), "('tab')\n", (328, 335), False, 'import pyautogui\n'), ((341, 363), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""alt"""'], {}), "('alt')\n", (356, 363), False, 'import pyautogui\n'), ((392, 416), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""win"""'], {}), "('win')\n", (409, 416), False, 'import pyautogui\n'), ((422, 445), 'pyautogui.press', 'pyautogui.press', (['"""down"""'], {}), "('down')\n", (437, 445), False, 'import pyautogui\n'), ((451, 473), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""win"""'], {}), "('win')\n", (466, 473), False, 'import pyautogui\n'), ((505, 529), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""win"""'], {}), "('win')\n", (522, 529), False, 'import pyautogui\n'), ((535, 558), 'pyautogui.press', 'pyautogui.press', (['"""down"""'], {}), "('down')\n", (550, 558), False, 'import pyautogui\n'), ((564, 587), 'pyautogui.press', 'pyautogui.press', (['"""down"""'], {}), "('down')\n", (579, 587), False, 'import pyautogui\n'), ((593, 615), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""win"""'], {}), "('win')\n", (608, 615), False, 'import pyautogui\n'), ((647, 671), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""win"""'], {}), "('win')\n", (664, 671), False, 'import pyautogui\n'), ((677, 698), 'pyautogui.press', 'pyautogui.press', (['"""up"""'], {}), "('up')\n", (692, 698), False, 'import pyautogui\n'), ((704, 726), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""win"""'], {}), "('win')\n", (719, 726), False, 'import pyautogui\n'), ((747, 772), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""ctrl"""'], {}), "('ctrl')\n", (764, 772), False, 'import pyautogui\n'), ((778, 798), 'pyautogui.press', 'pyautogui.press', (['"""c"""'], {}), "('c')\n", (793, 798), False, 'import pyautogui\n'), ((804, 827), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""ctrl"""'], {}), "('ctrl')\n", (819, 827), False, 'import pyautogui\n'), ((847, 872), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""ctrl"""'], {}), "('ctrl')\n", (864, 872), False, 'import pyautogui\n'), ((878, 898), 'pyautogui.press', 'pyautogui.press', (['"""x"""'], {}), "('x')\n", (893, 898), False, 'import pyautogui\n'), ((904, 927), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""ctrl"""'], {}), "('ctrl')\n", (919, 927), False, 'import pyautogui\n'), ((949, 974), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""ctrl"""'], {}), "('ctrl')\n", (966, 974), False, 'import pyautogui\n'), ((980, 1000), 'pyautogui.press', 'pyautogui.press', (['"""v"""'], {}), "('v')\n", (995, 1000), False, 'import pyautogui\n'), ((1006, 1029), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""ctrl"""'], {}), "('ctrl')\n", (1021, 1029), False, 'import pyautogui\n'), ((1056, 1081), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""ctrl"""'], {}), "('ctrl')\n", (1073, 1081), False, 'import pyautogui\n'), ((1087, 1107), 'pyautogui.press', 'pyautogui.press', (['"""a"""'], {}), "('a')\n", (1102, 1107), False, 'import pyautogui\n'), ((1113, 1136), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""ctrl"""'], {}), "('ctrl')\n", (1128, 1136), False, 'import pyautogui\n'), ((1157, 1182), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""ctrl"""'], {}), "('ctrl')\n", (1174, 1182), False, 'import pyautogui\n'), ((1188, 1208), 'pyautogui.press', 'pyautogui.press', (['"""s"""'], {}), "('s')\n", (1203, 1208), False, 'import pyautogui\n'), ((1214, 1237), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""ctrl"""'], {}), "('ctrl')\n", (1229, 1237), False, 'import pyautogui\n'), ((1261, 1286), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""ctrl"""'], {}), "('ctrl')\n", (1278, 1286), False, 'import pyautogui\n'), ((1292, 1318), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""shift"""'], {}), "('shift')\n", (1309, 1318), False, 'import pyautogui\n'), ((1324, 1344), 'pyautogui.press', 'pyautogui.press', (['"""s"""'], {}), "('s')\n", (1339, 1344), False, 'import pyautogui\n'), ((1350, 1374), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""shift"""'], {}), "('shift')\n", (1365, 1374), False, 'import pyautogui\n'), ((1380, 1403), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""ctrl"""'], {}), "('ctrl')\n", (1395, 1403), False, 'import pyautogui\n'), ((1441, 1465), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""alt"""'], {}), "('alt')\n", (1458, 1465), False, 'import pyautogui\n'), ((1471, 1492), 'pyautogui.press', 'pyautogui.press', (['"""f4"""'], {}), "('f4')\n", (1486, 1492), False, 'import pyautogui\n'), ((1498, 1520), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""alt"""'], {}), "('alt')\n", (1513, 1520), False, 'import pyautogui\n'), ((1550, 1574), 'pyautogui.keyDown', 'pyautogui.keyDown', (['"""win"""'], {}), "('win')\n", (1567, 1574), False, 'import pyautogui\n'), ((1580, 1600), 'pyautogui.press', 'pyautogui.press', (['"""i"""'], {}), "('i')\n", (1595, 1600), False, 'import pyautogui\n'), ((1606, 1628), 'pyautogui.keyUp', 'pyautogui.keyUp', (['"""win"""'], {}), "('win')\n", (1621, 1628), False, 'import pyautogui\n'), ((94, 121), 'pyautogui.press', 'pyautogui.press', (['"""volumeup"""'], {}), "('volumeup')\n", (109, 121), False, 'import pyautogui\n'), ((205, 234), 'pyautogui.press', 'pyautogui.press', (['"""volumedown"""'], {}), "('volumedown')\n", (220, 234), False, 'import pyautogui\n')] |
"""
Run MESS calculations
"""
import os
import mess_io
from mechlib.amech_io import printer as ioprinter
def output(formulastr, final_pf, mess_path, filename='pf.dat'):
""" Write a mess output file for a pf file
"""
mess_out_str = mess_io.writer.pf_output(formulastr, *final_pf)
ioprinter.messpf('write_output', mess_path)
if not os.path.exists(mess_path):
os.makedirs(mess_path)
with open(os.path.join(mess_path, filename), 'w') as mess_file:
mess_file.write(mess_out_str)
| [
"os.path.exists",
"os.makedirs",
"mechlib.amech_io.printer.messpf",
"mess_io.writer.pf_output",
"os.path.join"
] | [((251, 298), 'mess_io.writer.pf_output', 'mess_io.writer.pf_output', (['formulastr', '*final_pf'], {}), '(formulastr, *final_pf)\n', (275, 298), False, 'import mess_io\n'), ((304, 347), 'mechlib.amech_io.printer.messpf', 'ioprinter.messpf', (['"""write_output"""', 'mess_path'], {}), "('write_output', mess_path)\n", (320, 347), True, 'from mechlib.amech_io import printer as ioprinter\n'), ((359, 384), 'os.path.exists', 'os.path.exists', (['mess_path'], {}), '(mess_path)\n', (373, 384), False, 'import os\n'), ((394, 416), 'os.makedirs', 'os.makedirs', (['mess_path'], {}), '(mess_path)\n', (405, 416), False, 'import os\n'), ((431, 464), 'os.path.join', 'os.path.join', (['mess_path', 'filename'], {}), '(mess_path, filename)\n', (443, 464), False, 'import os\n')] |
"""
This module is used to generate correlation (R) and regression (b)
coefficients for relationships between the 2015 Census,
2018 Yale Climate Opinion Maps (YCOM) and land area datasets,
as well as p values for these relationships.
"""
import numpy as np
import pandas as pd
from scipy.stats import linregress
def calculate_stats_outputs(n_ycom, n_census, ycom_county, census):
"""
Function to estimate regression coefficients correlation between YCOM data variables and US
Census variables.
Inputs: n_ycom, a full list of names for ycom variables,
n_census, a full list of names for census variables
Outputs: a matrix of correlation values between each variable each dataset
"""
stats_outputs = np.zeros((len(n_ycom), len(n_census), 5))
for yind, yvar in enumerate(n_ycom):
for cind, cvar in enumerate(n_census):
ycom_notnull = ycom_county[yvar][census[cvar].notnull()]
census_notnull = census[cvar][census[cvar].notnull()]
stats_outputs[yind, cind, 0:5] = linregress(ycom_notnull, census_notnull)
return stats_outputs
def calculate_stats_outputs_standard(n_ycom, n_census, ycom_county, census):
"""
Function to estimate regression coefficients between YCOM data variables and US
Census variables on standardized variables
standardized_column = (column - mean(column)) / std(column)
Inputs: n_ycom, a full list of names for ycom variables,
n_census, a full list of names for census variables
Outputs: a matrix of correlation values between each variable each dataset
"""
stats_outputs_standard = np.zeros((len(n_ycom), len(n_census), 5))
for yind, yvar in enumerate(n_ycom):
for cind, cvar in enumerate(n_census):
ycom_notnull = ycom_county[yvar][census[cvar].notnull()]
census_notnull = census[cvar][census[cvar].notnull()]
#also doing calculations on standardized variables
census_standard = (census_notnull - np.mean(census_notnull)) / np.std(census_notnull)
stats_outputs_standard[yind, cind, 0:5] = linregress(ycom_notnull, census_standard)
return stats_outputs_standard
def get_regs_df(stats_outputs_standard, n_census, n_ycom):
"""
making dataframe of regression coefficients
these are kinda standardized -they show what % change in an opinion is given
a 1 standard deviation change in a census variable
"""
regs = pd.DataFrame(stats_outputs_standard[:, :, 0], columns=n_census, index=n_ycom)
return regs
def get_cors_df(stats_outputs, n_census, n_ycom):
"""
making dataframe of correlation coefficients
"""
cors = pd.DataFrame(stats_outputs[:, :, 2], columns=n_census, index=n_ycom)
return cors
def get_pvalues_df(stats_outputs, n_census, n_ycom):
"""
making dataframes of pvalues
"""
pval = pd.DataFrame(stats_outputs[:, :, 3], columns=n_census, index=n_ycom)
return pval
| [
"pandas.DataFrame",
"scipy.stats.linregress",
"numpy.mean",
"numpy.std"
] | [((2469, 2546), 'pandas.DataFrame', 'pd.DataFrame', (['stats_outputs_standard[:, :, 0]'], {'columns': 'n_census', 'index': 'n_ycom'}), '(stats_outputs_standard[:, :, 0], columns=n_census, index=n_ycom)\n', (2481, 2546), True, 'import pandas as pd\n'), ((2691, 2759), 'pandas.DataFrame', 'pd.DataFrame', (['stats_outputs[:, :, 2]'], {'columns': 'n_census', 'index': 'n_ycom'}), '(stats_outputs[:, :, 2], columns=n_census, index=n_ycom)\n', (2703, 2759), True, 'import pandas as pd\n'), ((2891, 2959), 'pandas.DataFrame', 'pd.DataFrame', (['stats_outputs[:, :, 3]'], {'columns': 'n_census', 'index': 'n_ycom'}), '(stats_outputs[:, :, 3], columns=n_census, index=n_ycom)\n', (2903, 2959), True, 'import pandas as pd\n'), ((1051, 1091), 'scipy.stats.linregress', 'linregress', (['ycom_notnull', 'census_notnull'], {}), '(ycom_notnull, census_notnull)\n', (1061, 1091), False, 'from scipy.stats import linregress\n'), ((2121, 2162), 'scipy.stats.linregress', 'linregress', (['ycom_notnull', 'census_standard'], {}), '(ycom_notnull, census_standard)\n', (2131, 2162), False, 'from scipy.stats import linregress\n'), ((2044, 2066), 'numpy.std', 'np.std', (['census_notnull'], {}), '(census_notnull)\n', (2050, 2066), True, 'import numpy as np\n'), ((2017, 2040), 'numpy.mean', 'np.mean', (['census_notnull'], {}), '(census_notnull)\n', (2024, 2040), True, 'import numpy as np\n')] |
import unittest
from pyramid import testing
class Test_parse_settings(unittest.TestCase):
def _callFUT(self, settings):
from pyramid_debugtoolbar import parse_settings
return parse_settings(settings)
def test_it(self):
panels = ('pyramid_debugtoolbar.tests.test_init.DummyPanel\n'
'pyramid_debugtoolbar.tests.test_init.DummyPanel')
global_panels = ('pyramid_debugtoolbar.tests.test_init.DummyPanel\n'
'pyramid_debugtoolbar.tests.test_init.DummyPanel')
settings = {'debugtoolbar.enabled':'false',
'debugtoolbar.intercept_exc':'false',
'debugtoolbar.intercept_redirects': 'false',
'debugtoolbar.panels': panels,
'debugtoolbar.global_panels': global_panels,
'debugtoolbar.hosts': '127.0.0.1',
'debugtoolbar.exclude_prefixes': '/excluded\n/e2',
}
result = self._callFUT(settings)
self.assertEqual(result,
{'debugtoolbar.enabled':False,
'debugtoolbar.intercept_exc': False,
'debugtoolbar.intercept_redirects': False,
'debugtoolbar.panels': [DummyPanel, DummyPanel],
'debugtoolbar.global_panels': [DummyPanel, DummyPanel],
'debugtoolbar.exclude_prefixes': ['/excluded', '/e2'],
'debugtoolbar.hosts': ['127.0.0.1'],
}
)
class Test_includeme(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def _callFUT(self, config):
from pyramid_debugtoolbar import includeme
return includeme(config)
def test_it(self):
self._callFUT(self.config)
self.assertEqual(self.config.registry.settings['debugtoolbar.hosts'],
['127.0.0.1', '::1'])
def test_it_with_complex_hosts(self):
s = self.config.registry.settings
s['debugtoolbar.hosts'] ='127.0.0.1 192.168.1.1 \n 192.168.1.2'
self._callFUT(self.config)
self.assertEqual(self.config.registry.settings['debugtoolbar.hosts'],
['127.0.0.1', '192.168.1.1', '192.168.1.2'])
class DummyPanel(object):
pass
| [
"pyramid.testing.setUp",
"pyramid_debugtoolbar.parse_settings",
"pyramid_debugtoolbar.includeme"
] | [((196, 220), 'pyramid_debugtoolbar.parse_settings', 'parse_settings', (['settings'], {}), '(settings)\n', (210, 220), False, 'from pyramid_debugtoolbar import parse_settings\n'), ((1672, 1687), 'pyramid.testing.setUp', 'testing.setUp', ([], {}), '()\n', (1685, 1687), False, 'from pyramid import testing\n'), ((1795, 1812), 'pyramid_debugtoolbar.includeme', 'includeme', (['config'], {}), '(config)\n', (1804, 1812), False, 'from pyramid_debugtoolbar import includeme\n')] |
import subprocess
from vuln_server.outputgrabber import OutputGrabber
from flask import request, redirect, render_template
class SubprocessVuln():
def bypass(self):
if request.method == 'POST':
# Check if data is not empty, post forms has all params defined
# which may be empty and cause unexpected behaviour.
if request.form['input_data'] != '':
try:
# Instanciate a different stdout grabber for subprocess
output = OutputGrabber()
with output:
# Execute system command with an unsafe input parameter
subprocess.call("ping -c1 " +
request.form['input_data'], shell=True)
return output.capturedtext
except Exception as e:
return "Server Error: {}:".format(str(e))
else:
return redirect(request.url)
return render_template('subprocess.html')
| [
"flask.render_template",
"vuln_server.outputgrabber.OutputGrabber",
"flask.redirect",
"subprocess.call"
] | [((1015, 1049), 'flask.render_template', 'render_template', (['"""subprocess.html"""'], {}), "('subprocess.html')\n", (1030, 1049), False, 'from flask import request, redirect, render_template\n'), ((978, 999), 'flask.redirect', 'redirect', (['request.url'], {}), '(request.url)\n', (986, 999), False, 'from flask import request, redirect, render_template\n'), ((526, 541), 'vuln_server.outputgrabber.OutputGrabber', 'OutputGrabber', ([], {}), '()\n', (539, 541), False, 'from vuln_server.outputgrabber import OutputGrabber\n'), ((679, 748), 'subprocess.call', 'subprocess.call', (["('ping -c1 ' + request.form['input_data'])"], {'shell': '(True)'}), "('ping -c1 ' + request.form['input_data'], shell=True)\n", (694, 748), False, 'import subprocess\n')] |
import pytest
from pyramid_resource import Resource
def test_default_lookup():
class SubResource(Resource):
pass
class MyResource(Resource):
__children__ = {
"sub": SubResource,
}
root = MyResource("request")
sub = root["sub"]
assert isinstance(sub, SubResource)
assert sub.request == "request"
assert sub.__name__ == "sub"
assert sub.__parent__ is root
with pytest.raises(KeyError):
root["sub2"]
def test_custom_lookup_subclass():
class SubResource(Resource):
pass
class MyResource(Resource):
def get_child(self, key):
assert key == "sub"
return SubResource
root = MyResource("request")
sub = root["sub"]
assert isinstance(sub, SubResource)
assert sub.request == "request"
assert sub.__name__ == "sub"
assert sub.__parent__ is root
def test_custom_lookup_tuple():
class SubResource(Resource):
pass
class MyResource(Resource):
def get_child(self, key):
assert key == "sub"
return SubResource, {"foo": "bar"}
root = MyResource("request")
sub = root["sub"]
assert isinstance(sub, SubResource)
assert sub.request == "request"
assert sub.__name__ == "sub"
assert sub.__parent__ is root
assert sub.foo == "bar"
def test_getattr():
class SubResource(Resource):
pass
class MyResource(Resource):
subfoo = "subbar"
@property
def prop(self):
return "myprop"
parent = MyResource("request")
child = SubResource("request", "sub", parent, foo="bar")
grandchild = SubResource("request", "sub", child)
with pytest.raises(AttributeError):
assert parent.foo
assert parent.subfoo == "subbar"
assert parent.prop == "myprop"
assert child.foo == "bar"
assert child.subfoo == "subbar"
assert child.prop == "myprop"
assert grandchild.foo == "bar"
assert grandchild.subfoo == "subbar"
assert grandchild.prop == "myprop"
| [
"pytest.raises"
] | [((437, 460), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (450, 460), False, 'import pytest\n'), ((1706, 1735), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (1719, 1735), False, 'import pytest\n')] |
#!/usr/bin/env python3
"""Planningpoker project setup."""
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
# Requirements specified up to the minor version to allow bugfixes to be automatically applied.
REQUIREMENTS = [
'aiohttp==0.21.5',
'aiohttp_session[secure]==0.5.0',
'simplejson==3.8', # A JSON library that does not fear Decimals.
'click==6.6',
]
# Versions of test requirements kept exact to avoid broken builds due to API breakage in updates.
TEST_REQUIREMENTS = [
'pylama==6.3.4',
'pytest==2.8.2',
'requests==2.8.1', # A synchronous HTTP client to use in tests.
'mirakuru==0.6.1', # Process executor.
'port-for==0.3.1',
]
setup(
name='planningpoker',
version='0.0.1',
description='Planning poker web application',
long_description=README,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Framework :: aiohttp',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3 :: Only',
],
keywords='planning poker web app',
author='<NAME>',
author_email='@'.join(['unittestablecode', 'gmail.com']),
license='MIT',
packages=find_packages(exclude=['test']),
install_requires=REQUIREMENTS,
tests_require=TEST_REQUIREMENTS,
extras_require={'tests': TEST_REQUIREMENTS},
cmdclass={},
entry_points={
'console_scripts': 'planningpoker=planningpoker.app:cli_entry'
},
)
| [
"os.path.dirname",
"setuptools.find_packages",
"os.path.join"
] | [((137, 162), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (152, 162), False, 'import os\n'), ((175, 207), 'os.path.join', 'os.path.join', (['here', '"""README.rst"""'], {}), "(here, 'README.rst')\n", (187, 207), False, 'import os\n'), ((1585, 1616), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['test']"}), "(exclude=['test'])\n", (1598, 1616), False, 'from setuptools import setup, find_packages\n')] |
"""
爬取原网页的html,过滤新闻内容并重新拼接,保留原网页样式。
"""
import pymysql
import datetime
import requests
from lxml import etree
import pdfkit
import os
import time
import json
import re
# 敏感词过滤类,AC自动机
import Ac_auto
# 任务id
task_id = 2
# 爬取的地址和名称
spider_url = 'https://news.cqu.edu.cn/newsv2/'
spider_name = '重大新闻网'
# 爬虫程序爬取主页和首页的运行日期
spider_month = [1, 7]
spider_day = [1]
# 睡眠时间
sleep_time = 0.1
# mysql登录信息
conn = pymysql.connect(
host='localhost',
port=3307,
user='root',
passwd='<PASSWORD>',
db='spider_test',
use_unicode=True,
charset="utf8mb4"
)
# mysql 插入
# 插入spider结果表
insert_result = '''
INSERT INTO t_spider_result VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NULL)
'''
# 全局字典变量,以键值对(键:对应URL,值:标题)形式存储爬取的数据记录。
dict_data = dict()
# pdfkit配置及设置
confg = pdfkit.configuration(wkhtmltopdf=r'/usr/local/bin/wkhtmltopdf')
options = {
'page-size': 'A4',
'viewport-size': 1920*1080
}
# 伪装http请求头部
headers = {
'User-Agent':
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;'
}
# 从数据库配置表里获取xpath, 并解析获取内容
def get_xpath_content(html, xpath_name):
# 去掉空格字符串函数
def not_empty(s):
return s and s.strip()
cur.execute("SELECT xpath FROM t_spider_config_xpath WHERE name = %s", xpath_name)
xpath = cur.fetchone()
xpath = xpath[0]
content = html.xpath(xpath)
# 对content做处理, 元素小于2的处理成字符串, 并去掉首尾多余的空格, 大于2的去掉空格字符串
if len(content) < 2:
content = ''.join(content)
content = content.strip()
else:
content = list(filter(not_empty, content))
return content
# 获取配置表的id,赋值给结果表
def get_conf_id(module_name=None):
if module_name:
cur.execute("SELECT id FROM t_spider_conf WHERE moduleName like %s ", '%' + module_name + '%')
conf_id = cur.fetchone()
conf_id = conf_id[0]
return conf_id
# 查找所有栏目的url(板块url),并保存
def all_urls_list(f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
heading = '新闻网'
# 根据时间需求爬取主页及各级首页,需求:1月1日和7月1日各爬取一次,其他时间不做爬取
run_date = datetime.date.today()
if run_date.month in spider_month and run_date.day in spider_day:
print('正在爬取 {} 主页。'.format(spider_name))
# 存储index的记录,放进字典和数据库,如果已经存在,则不存储
judge = spider_url in dict_data.keys()
if not judge:
dict_data[spider_url] = heading
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + heading + '首页'
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
res = requests.get(spider_url, headers=headers)
res.encoding = 'UTF-8'
raw_html = res.text
html_filter = sensitive_word_filter(raw_html)
html_filter = path_rewrite(html_filter)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id('所有栏目')
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cur.execute(insert_result, (conf_id, 'index', spider_url, html_filter, html_file, pdf_file, time_now, heading, run_date, ''))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
try:
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(spider_url, pdf_file, configuration=confg, options=options)
print('《{}》 的首页已储存,转换pdf格式已成功。'.format(heading))
time.sleep(sleep_time)
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
else:
print('{} 首页记录已爬取过且保存在数据库中!'.format(heading))
else:
print('爬虫程序启动日期并非 ', end='')
for month in spider_month:
for day in spider_day:
print('{} 月 {} 日, '.format(month, day), end='')
print('{} 主页不做爬取!'.format(spider_name))
r = requests.get(spider_url, headers=headers)
r.encoding = 'UTF-8'
html = etree.HTML(r.text)
news_heading_url_list = []
try:
news_heading_url_list = get_xpath_content(html, '所有栏目URL的xpath')
# 将主页的url去掉
news_heading_url_list.remove(news_heading_url_list[0])
# 增加快讯,专题两个板块
news_heading_url_list.append('https://news.cqu.edu.cn/newsv2/list-15.html')
news_heading_url_list.append('http://news.cqu.edu.cn/kjcd/')
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
# print(news_heading_url_list)
return news_heading_url_list
# 查找每个栏目/板块下的每一页的url(列表url),并保存
# 适用于第一大类:新闻模块,第二大类:媒体重大,第三大类:通知公告简报,第四大类:学术预告, 第五大类:快讯
def get_url_list(url, all_urls, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
url_list = []
r = requests.get(url, headers=headers)
r.encoding = 'UTF-8'
html = etree.HTML(r.text)
news_heading = ''
# 获取板块在news_heading_url_list的序号,并获取板块名称以及板块下总的新闻数目
# 对 快讯板块做处理:
if url == 'https://news.cqu.edu.cn/newsv2/list-15.html':
try:
news_heading = get_xpath_content(html, '快讯类栏目标题xpath')
news_heading = ''.join(news_heading)
# print(news_heading)
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
temp_url = url
else:
cur.execute("SELECT xpath from t_spider_config_xpath where name = %s", '新闻类栏目标题xpath')
xpath = cur.fetchone()
xpath = xpath[0]
# 根据不同的栏目指定不同的xpath
index = all_urls.index(url)
xpath = xpath.replace('?', str(index + 2))
try:
news_heading = html.xpath(xpath)
news_heading = ''.join(news_heading)
# print(news_heading)
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
temp_url = url + '?page=1'
# 查找最大页数
page = html.xpath('/html/body/div[@class="row"]/div/div[@class="lists"]/div[@class="page"]/a[12]/text()')
page = ''.join(page)
# print(page)
max_page = int(page)
# 根据时间需求爬取主页及各级首页,需求:1月1日和7月1日各爬取一次,其他时间不做爬取
run_date = datetime.date.today()
if run_date.month in spider_month and run_date.day in spider_day:
list_heading = '各级首页'
print('正在爬取 {} 栏目首页。'.format(news_heading))
# 存储list第一页的记录,放进字典和数据库,如果已经存在,则不存储
judge = temp_url in dict_data.keys()
if not judge:
dict_data[temp_url] = list_heading
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
res = requests.get(temp_url, headers=headers)
res.encoding = 'UTF-8'
raw_html = res.text
html_filter = sensitive_word_filter(raw_html)
html_filter = path_rewrite(html_filter)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id(news_heading)
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cur.execute(insert_result, (conf_id, 'list', temp_url, html_filter, html_file, pdf_file, time_now, list_heading, run_date, ''))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
try:
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(temp_url, pdf_file, configuration=confg, options=options)
print('栏目 《{}》 的首页已储存,转换pdf格式已成功。'.format(news_heading))
time.sleep(sleep_time)
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
else:
print('{} 栏目 首页记录已爬取过且保存在数据库中!'.format(news_heading))
else:
print('爬虫程序启动日期并非 ', end='')
for month in spider_month:
for day in spider_day:
print('{} 月 {} 日, '.format(month, day), end='')
print('{} 栏目首页不做爬取!'.format(news_heading))
# 对 快讯板块做处理:
if url == 'https://news.cqu.edu.cn/newsv2/list-15.html':
for i in range(1, max_page + 1):
temp_url = url[:-5] + '-' + str(i) + '.html'
url_list.append(temp_url)
else:
for i in range(1, max_page + 1):
# print('爬取网上新闻的第{}页......'.format(i))
temp_url = url + '?page=' + str(i)
url_list.append(temp_url)
# print(url_list)
return url_list
# 查找专题 栏目下的每一页的url(列表url),并保存, 返回一个字典文件。
def get_topic_url_list(url, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
url_dict = dict()
r = requests.get(url, headers=headers)
r.encoding = 'UTF-8'
html = etree.HTML(r.text)
news_heading = '专题'
# 根据时间需求爬取主页及各级首页,需求:1月1日和7月1日各爬取一次,其他时间不做爬取
run_date = datetime.date.today()
if run_date.month in spider_month and run_date.day in spider_day:
list_heading = '各级首页'
print('正在爬取 {} 栏目首页。'.format(news_heading))
# 存储专题list的记录,放进字典和数据库,如果已经存在,则不存储
judge = url in dict_data.keys()
if not judge:
dict_data[url] = list_heading
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
res = requests.get(url, headers=headers)
res.encoding = 'UTF-8'
raw_html = res.text
html_filter = sensitive_word_filter(raw_html)
html_filter = path_rewrite(html_filter)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id(news_heading)
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cur.execute(insert_result, (conf_id, 'list', url, html_filter, html_file, pdf_file, time_now, list_heading, run_date, ''))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
try:
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(url, pdf_file, configuration=confg, options=options)
print('栏目 《{}》 的主页已储存,转换pdf格式已成功。'.format(news_heading))
time.sleep(sleep_time)
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
else:
print('{} 栏目 主页记录已爬取过且保存在数据库中!'.format(news_heading))
else:
print('爬虫程序启动日期并非 ', end='')
for month in spider_month:
for day in spider_day:
print('{} 月 {} 日, '.format(month, day), end='')
print('{} 栏目首页不做爬取!'.format(news_heading))
try:
topic_urls_list = get_xpath_content(html, '专题网址xpath')
topic_names_list = get_xpath_content(html, '专题标题xpath')
# print(topic_urls_list)
# print(topic_names_list)
# 首页4个专题的URL添加进topic_urls_list, 将四个专题标题名添加进topic_names_list
topic_name = ['毕业季|青春不落幕 友谊不散场', '辉煌70年•追梦重大人', '不忘初心 牢记使命', '一带一路年会']
for i in range(4, 8):
topic_urls_list.append('http://news.cqu.edu.cn/newsv2/index.php?m=special&c=index&specialid=8' + str(i))
topic_names_list.append(topic_name[(i - 4)])
# 给每个专题标题名添加’专题_‘进行区分
temp_list = []
for each in topic_names_list:
temp_list.append('专题_' + each)
topic_names_list = temp_list
url_dict = dict(zip(topic_names_list, topic_urls_list))
# 字典key:专题标题,value:专题链接
# print(url_dict)
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
return url_dict
# 读取新闻模块每个页面的url,获取新闻模块的每条新闻的归档元数据,并将页面转成pdf格式保存
def get_news_info(url_list, module_url, all_urls, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id('新闻模块')
# 新闻模块新闻数累加器
sum_i = 0
# 新闻模块页数计数器
page = 1
# 获取栏目名称
news_heading = ''
dict_news = dict()
dict_news = {'网站名称': spider_name, '网站域名': spider_url}
r = requests.get(module_url, headers=headers)
r.encoding = 'UTF-8'
html = etree.HTML(r.text)
cur.execute("SELECT xpath from t_spider_config_xpath where name = %s", '新闻类栏目标题xpath')
xpath = cur.fetchone()
xpath = xpath[0]
# 根据不同的栏目指定不同的xpath
index = all_urls.index(module_url)
xpath = xpath.replace('?', str(index + 2))
try:
news_heading = html.xpath(xpath)
news_heading = ''.join(news_heading)
# print(news_heading)
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
# 每一页的url
for url in url_list:
r = requests.get(url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
links_list = get_xpath_content(html, '新闻模块网址xpath')
title_list = get_xpath_content(html, '新闻模块标题xpath')
# 每一条新闻的url + 每一个标题
for each_url, title in zip(links_list, title_list):
print('正在爬取 {} 栏目下,第 {} 页 总第 {} 条新闻。'.format(news_heading, page, sum_i + 1))
# 存储每一个新闻模块链接URL的记录,放进字典和数据库,如果已经存在,则不存储
judge = each_url in dict_data.keys()
try:
if not judge:
dict_data[each_url] = title
r = requests.get(each_url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
html_filter = sensitive_word_filter(raw_html)
html_filter = path_rewrite(html_filter)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
dict_news['所属栏目'] = news_heading
try:
cur.execute("SELECT name from t_spider_config_xpath where name like %s", '新闻模块' + '%')
xpath_name = cur.fetchall()
for each in xpath_name:
dict_news[each[0][4:-5]] = get_xpath_content(html, each[0])
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
dict_news['标题'] = title
dict_news['网址'] = each_url
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dict_news['采集时间'] = time_now
dict_news['采集人'] = '档案馆'
if dict_news['发布时间']:
release_time = dict_news['发布时间']
else:
release_time = None
json_dict = json.dumps(dict_news, ensure_ascii=False, indent=4)
print(json_dict)
judge_identifier = not_found_judge(raw_html, r)
# 判断网页是不是404 not found
if judge_identifier:
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, html_file, pdf_file,
time_now, news_heading, release_time, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
sum_i += 1
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(each_url, pdf_file, configuration=confg, options=options)
print('该新闻《{}》pdf格式已转换成功。'.format(title))
time.sleep(sleep_time)
else:
# 将404 not found 记录进数据库
html_filter = '404 not found'
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, '', '',
time_now, news_heading, None, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
print('该新闻《{}》网页不存在, 以‘404 not found’为网页内容存入数据库。'.format(title))
sum_i += 1
else:
sum_i += 1
print('{} 栏目 的 第 {} 条新闻 已爬取过且保存在数据库中!'.format(news_heading, sum_i))
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
except IndexError:
print("该栏目《{}》下的新闻已全部爬取完!".format(news_heading))
break
print('第{}页已经爬取完'.format(page))
page += 1
print('{} 栏目下 共有{}页 {}条新闻'.format(news_heading, page - 1, sum_i))
# 读取媒体重大每个页面的url,获取媒体重大的每条新闻的归档元数据,并将页面转成pdf格式保存
def get_media_info(url_list, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
# 媒体重大新闻数累加器
sum_i = 0
# 媒体重大页数计数器
page = 1
# 媒体重大发布时间处理计数器
i = 0
news_heading = '媒体重大'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id(news_heading)
dict_media = dict()
dict_media = {'网站名称': spider_name, '网站域名': spider_url}
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
# 每一页的url
for url in url_list:
r = requests.get(url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
links_list = get_xpath_content(html, '媒体重大网址xpath')
title_list = get_xpath_content(html, '媒体重大标题xpath')
release_time_list = get_xpath_content(html, '媒体重大发布时间xpath')
# 格式化发布时间
temp_list = []
for each in release_time_list:
each = each.strip()
# print(each)
temp_list.append(each)
release_time_list = []
while i < len(temp_list) - 1:
release_time = temp_list[i] + '月' + temp_list[i + 1] + '日'
release_time_list.append(release_time)
i += 2
# 将计数器清零
i = 0
# 每一条新闻的url + 每一条发布时间 + 每一个标题
for each_url, release_time, title in zip(links_list, release_time_list, title_list):
print('正在爬取 {} 栏目下,第 {} 页 总第 {} 条新闻。'.format(news_heading, page, sum_i + 1))
# 存储每一个媒体重大链接URL的记录,放进字典和数据库,如果已经存在,则不存储
judge = each_url in dict_data.keys()
try:
if not judge:
dict_data[each_url] = title
r = requests.get(each_url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
html_filter = sensitive_word_filter(raw_html)
html_filter = path_rewrite(html_filter)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
resource = ''
dict_media['所属栏目'] = news_heading
# 从数据库获取xpath, 并根据xpath获取内容
try:
cur.execute("SELECT name from t_spider_config_xpath where name like %s", news_heading + '%')
xpath_name = cur.fetchall()
for each in xpath_name:
# [4:-5]表示去掉开头‘媒体重大’四个字符和结尾‘xpath’五个字符
if each[0][4:-5] == '具体新闻内容':
resource = get_xpath_content(html, each[0])[-1]
if each[0][4:-5] == '作者所属单位':
department = get_xpath_content(html, each[0])[:-4]
dict_media[each[0][4:-5]] = department
else:
dict_media[each[0][4:-5]] = get_xpath_content(html, each[0])
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
dict_media['标题'] = title
dict_media['发布时间'] = release_time
dict_media['来源(转载来源)'] = resource
dict_media['网址'] = each_url
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dict_media['采集时间'] = time_now
dict_media['采集人'] = '档案馆'
json_dict = json.dumps(dict_media, ensure_ascii=False, indent=4)
print(json_dict)
judge_identifier = not_found_judge(raw_html, r)
# 判断网页是不是404 not found
if judge_identifier:
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, html_file, pdf_file,
time_now, news_heading, None, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
sum_i += 1
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(each_url, pdf_file, configuration=confg, options=options)
print('该新闻《{}》pdf格式已转换成功。'.format(title))
time.sleep(sleep_time)
else:
# 将404 not found 记录进数据库
html_filter = '404 not found'
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, '', '',
time_now, news_heading, None, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
print('该新闻《{}》网页不存在, 以‘404 not found’为网页内容存入数据库。'.format(title))
sum_i += 1
else:
sum_i += 1
print('{} 栏目 的 第 {} 条新闻 已爬取过且保存在数据库中!'.format(news_heading, sum_i))
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
except IndexError:
print("该栏目《{}》下的媒体新闻已全部爬取完!".format(news_heading))
break
print('第{}页已经爬取完'.format(page))
page += 1
print('{} 栏目下 共有{}页 {}条媒体新闻'.format(news_heading, page - 1, sum_i))
# 读取通知公告简报每个页面的url,获取通知公告简报的每条新闻的归档元数据,并将页面转成pdf格式保存
def get_notice_info(url_list, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
# 通知公告数累加器
sum_i = 0
# 通知公告简报页数计数器
page = 1
news_heading = '通知公告简报'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id(news_heading)
# 通知公告简报
dict_notice = dict()
dict_notice = {'网站名称': spider_name, '网站域名': spider_url}
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
# 每一页的url
for url in url_list:
r = requests.get(url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
links_list = get_xpath_content(html, '通知公告简报网址xpath')
title_list = get_xpath_content(html, '通知公告简报标题xpath')
# 每一条通知的url + 每一个标题
for each_url, title in zip(links_list, title_list):
print('正在爬取 {} 栏目下,第 {} 页 总第 {} 条通知公告。'.format(news_heading, page, sum_i + 1))
# 存储每一个学术预告链接URL的记录,放进字典和数据库,如果已经存在,则不存储
judge = each_url in dict_data.keys()
try:
if not judge:
dict_data[each_url] = title
r = requests.get(each_url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
html_filter = sensitive_word_filter(raw_html)
html_filter = path_rewrite(html_filter)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
# 对跳转微信公众号文章的链接做处理
if 'weixin' in each_url:
title = html.xpath('//h2[@class="rich_media_title"]/text()')
title = ''.join(title)
title = title.strip()
dict_notice['所属栏目'] = news_heading
# 从数据库获取xpath, 并根据xpath获取内容
try:
cur.execute("SELECT name from t_spider_config_xpath where name like %s",
news_heading + '%')
xpath_name = cur.fetchall()
for each in xpath_name:
# [6:-5]表示去掉开头‘通知公告简报’四个字符和结尾‘xpath’五个字符
dict_notice[each[0][6:-5]] = get_xpath_content(html, each[0])
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
dict_notice['标题'] = title
dict_notice['网址'] = each_url
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dict_notice['采集时间'] = time_now
dict_notice['采集人'] = '档案馆'
if dict_notice['发布时间']:
release_time = dict_notice['发布时间']
else:
release_time = None
json_dict = json.dumps(dict_notice, ensure_ascii=False, indent=4)
print(json_dict)
judge_identifier = not_found_judge(raw_html, r)
# 判断网页是不是404 not found
if judge_identifier:
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, html_file, pdf_file,
time_now, news_heading, release_time, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
sum_i += 1
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(each_url, pdf_file, configuration=confg, options=options)
print('该通知《{}》pdf格式已转换成功。'.format(title))
time.sleep(sleep_time)
else:
# 将404 not found 记录进数据库
html_filter = '404 not found'
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, '', '',
time_now, news_heading, None, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
print('该通知《{}》网页不存在, 以‘404 not found’为网页内容存入数据库。'.format(title))
sum_i += 1
else:
sum_i += 1
print('{} 栏目 的 第 {} 条通知 已爬取过且保存在数据库中!'.format(news_heading, sum_i))
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
except IndexError:
print("该栏目《{}》下的通知公告简报已全部爬取完!".format(news_heading))
break
print('第{}页已经爬取完'.format(page))
page += 1
print('{} 栏目下 共有{}页 {}条通知公告简报'.format(news_heading, page - 1, sum_i))
# 读取学术预告每个页面的url,获取学术预告的每条新闻的归档元数据,并将页面转成pdf格式保存
def get_academic_info(url_list, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
# 讲座数累加器
sum_i = 0
# 学术预告页数计数器
page = 1
news_heading = '学术预告'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id(news_heading)
dict_academic = dict()
dict_academic = {'网站名称': spider_name, '网站域名': spider_url}
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
# 每一页的url
for url in url_list:
r = requests.get(url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
# 筛选处理讲座链接
links_list = get_xpath_content(html, '学术预告网址xpath')
temp = []
for each in links_list:
if 'http' in each:
temp.append(each)
links_list = temp
title_list = get_xpath_content(html, '学术预告标题xpath')
# 每一条讲座的url + 每一个标题
for each_url, title in zip(links_list, title_list):
print('正在爬取 {} 栏目下,第 {} 页 总第 {} 条讲座。'.format(news_heading, page, sum_i + 1))
# 存储每一个学术预告链接URL的记录,放进字典和数据库,如果已经存在,则不存储
judge = each_url in dict_data.keys()
try:
if not judge:
dict_data[each_url] = title
r = requests.get(each_url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
html_filter = sensitive_word_filter(raw_html)
html_filter = path_rewrite(html_filter)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
dict_academic['所属栏目'] = news_heading
# 从数据库获取xpath, 并根据xpath获取内容
try:
cur.execute("SELECT name from t_spider_config_xpath where name like %s", news_heading + '%')
xpath_name = cur.fetchall()
for each in xpath_name:
# [4:-5]表示去掉开头‘学术预告’四个字符和结尾‘xpath’五个字符
dict_academic[each[0][4:-5]] = get_xpath_content(html, each[0])
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
dict_academic['标题'] = title
dict_academic['网址'] = each_url
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dict_academic['采集时间'] = time_now
dict_academic['采集人'] = '档案馆'
json_dict = json.dumps(dict_academic, ensure_ascii=False, indent=4)
print(json_dict)
judge_identifier = not_found_judge(raw_html)
# 判断网页是不是404 not found
if judge_identifier:
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, html_file, pdf_file,
time_now, news_heading, None, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
sum_i += 1
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(each_url, pdf_file, configuration=confg, options=options)
print('该讲座预告《{}》pdf格式已转换成功。'.format(title))
time.sleep(sleep_time)
else:
# 将404 not found 记录进数据库
html_filter = '404 not found'
cur.execute(insert_result, (conf_id, 'detail', each_url, html_filter, '', '',
time_now, news_heading, None, json_dict))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
print('该讲座预告《{}》网页不存在, 以‘404 not found’为网页内容存入数据库。'.format(title))
sum_i += 1
else:
sum_i += 1
print('{} 栏目 的 第 {} 条讲座预告 已爬取过且保存在数据库中!'.format(news_heading, sum_i))
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
except IndexError:
print("该栏目《{}》下的讲座预告已全部爬取完!".format(news_heading))
break
print('第{}页已经爬取完'.format(page))
page += 1
print('{} 栏目下 共有{}页 {}条讲座预告'.format(news_heading, page - 1, sum_i))
# 读取快讯每个页面的url,获取快讯的每条新闻的归档元数据,并将页面转成pdf格式保存
def get_express_info(url_list, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
# 快讯新闻数累加器
sum_i = 0
# 快讯新闻页数计数器
page = 1
# 快讯发布时间处理计数器
i = 0
news_heading = '快讯'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id(news_heading)
dict_express = dict()
dict_express = {'网站名称': spider_name, '网站域名': spider_url}
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
for url in url_list:
# 存储每一个快讯链接URL的记录,放进数据库,如果已经存在,则不存储
judge = url in dict_data.keys()
try:
if not judge:
# 存储快讯链接及页数名
express_title = '快讯第' + str(page) + '页'
dict_data[url] = express_title
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
r = requests.get(url, headers=headers)
r.encoding = 'UTF-8'
raw_html = r.text
html = etree.HTML(raw_html)
html_filter = sensitive_word_filter(raw_html)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
# 解析快讯发布时间,标题,内容
release_time_list, title_list, content_list = [], [], []
try:
cur.execute("SELECT name from t_spider_config_xpath where name like %s", '快讯' + '%')
xpath_name = cur.fetchall()
for each in xpath_name:
# [2:-5]表示去掉开头‘快讯’两个字符和结尾‘xpath’五个字符
dict_key = each[0][2:-5]
if dict_key == '标题':
title_list = get_xpath_content(html, each[0])
if dict_key == '发布时间':
release_time_list = get_xpath_content(html, each[0])
if dict_key == '具体内容':
content_list = get_xpath_content(html, each[0])
if dict_key != '类栏目标题':
dict_express[dict_key] = ''
except IndexError:
print("xpath配置错误!")
except etree.XPathEvalError:
print("数据库里未找到记录!")
# 格式化发布时间
temp_list = []
for each in release_time_list:
each = each.strip()
# print(each)
temp_list.append(each)
release_time_list = []
while i < len(temp_list)-1:
release_time = temp_list[i] + '月' + temp_list[i+1] + '日'
release_time_list.append(release_time)
i += 2
# 将计数器清零
i = 0
# 格式化快讯内容
temp_list = []
for each in content_list:
each = each.strip()
temp_list.append(each)
content_list = temp_list
for release_time, title, content in zip(release_time_list, title_list, content_list):
print('正在爬取 {} 栏目下,第 {} 页 总第 {} 条快讯。'.format(news_heading, page, sum_i + 1))
print('发布时间:{}, 快讯标题:{}, 快讯内容:{}'.format(release_time, title, content))
# 更新字典,并转成json格式
dict_express['所属栏目'] = news_heading
dict_express['标题'] = title
dict_express['发布时间'] = release_time
dict_express['具体内容'] = content
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dict_express['采集时间'] = time_now
dict_express['采集人'] = '档案馆'
json_dict = json.dumps(dict_express, ensure_ascii=False, indent=4)
print(json_dict)
cur.execute(insert_result, (conf_id, 'detail', url, html_filter, html_file, pdf_file,
time_now, news_heading, None, json_dict))
conn.commit()
sum_i += 1
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_string(html_filter, pdf_file, configuration=confg, options=options)
print('快讯第 {} 页pdf格式已转换成功。'.format(page))
time.sleep(sleep_time)
else:
print('{} 栏目 第{}页快讯 已爬取过且保存在数据库中!'.format(news_heading, page))
sum_i += 20
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
except IndexError:
print("该栏目《{}》下的新闻已全部爬取完!".format(news_heading))
break
print('第{}页已经爬取完'.format(page))
page += 1
print('{} 栏目下 共有{}页 {}条快讯'.format(news_heading, page - 1, sum_i))
# 获取专题的各个详细页面html,并转成pdf格式保存
def get_topic_info(url_dict, f_data):
global dict_data
# 读取字典中的数据
f_data.seek(0, 0)
content = f_data.read()
if content:
dict_data = json.loads(content)
# 专题数累加器
sum_i = 0
news_heading = '专题'
# 获取配置表的id,赋值给结果表
conf_id = get_conf_id(news_heading)
dict_topic = dict()
dict_topic = {'网站名称': spider_name, '网站域名': spider_url}
# 创建文件夹
# 先判断文件夹是否存在,不存在则创建文件夹
now_dir = os.getcwd()
new_dir = now_dir + '/' + news_heading
dir_judge = os.path.exists(new_dir)
if not dir_judge:
os.mkdir(new_dir)
# key: 专题标题, value:专题链接
for key, value in url_dict.items():
print('正在爬取 {} 栏目下,第 {} 个专题。'.format(news_heading, sum_i + 1))
# 存储每一个专题链接URL的记录,放进字典和数据库,如果已经存在,则不存储
judge = value in dict_data.keys()
try:
if not judge:
dict_data[value] = key
res = requests.get(value, headers=headers)
res.encoding = 'UTF-8'
raw_html = res.text
# 判断网页是不是‘404 not found’
judge_identifier = not_found_judge(raw_html)
if judge_identifier:
html_filter = sensitive_word_filter(raw_html)
timestamp = round(time.time())
html_file = new_dir + '/' + str(timestamp) + '.html'
pdf_file = new_dir + '/' + str(timestamp) + '.pdf'
# 更新字典,并转成json格式
dict_topic['所属栏目'] = news_heading
dict_topic['标题'] = key
dict_topic['网址'] = value
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dict_topic['采集时间'] = time_now
json_dict = json.dumps(dict_topic, ensure_ascii=False, indent=4)
print(json_dict)
cur.execute(insert_result, (conf_id, 'detail', value, html_filter, html_file, pdf_file,
time_now, news_heading, None, json_dict))
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
conn.commit()
with open(html_file, 'w+', encoding='UTF-8') as f1:
f1.write(html_filter)
# html转pdf
pdfkit.from_url(value, pdf_file, configuration=confg, options=options)
print('该专题《{}》pdf格式已转换成功。'.format(key))
time.sleep(sleep_time)
else:
# 将404 not found 记录进数据库
html_filter = '404 not found'
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cur.execute(insert_result,
(conf_id, 'detail', value, html_filter, '', '', time_now, news_heading, None, ''))
conn.commit()
json_data = json.dumps(dict_data)
f_data.seek(0, 0)
f_data.write(json_data)
print('该专题《{}》网页不存在, 以‘404 not found’为网页内容存入数据库。'.format(key))
else:
print('{} 栏目 {} 专题已爬取过且保存在数据库中!'.format(news_heading, key))
except IOError:
print("Warning: wkhtmltopdf读取文件失败, 可能是网页无法打开或者图片/css样式丢失。")
except IndexError:
print("该栏目《{}》下的新闻已全部爬取完!".format(news_heading))
break
sum_i += 1
print('{} 栏目下 共有{}条专题'.format(news_heading, sum_i))
# 判断网页是否是404_not_found, 并返回一个判断标识, 0为空网页,1为正常网页
def not_found_judge(html, r=None):
judge_identifier = 1
# temp/temp_2,3,4 找到'404 not found'/'页面不存在'返回下标,找不到为-1
# 如果网页编码为gb2312,则对网页重新编码解析
if r:
encode_judge = html.find('gb2312')
if encode_judge:
r.encoding = 'gb2312'
html = r.text
temp = html.find('404 Not Found')
temp_2 = html.find('页面不存在')
temp_3 = html.find('页面未找到')
temp_4 = html.find('Page Not Found')
temp_5 = html.find('<div class="content guery" style="display:inline-block;display:-moz-inline-stack;zoom:1;*display:inline; max-width:280px">')
if temp != -1 or temp_2 != -1 or temp_3 != -1 or temp_4 != -1 or temp_5 != -1:
judge_identifier = 0
print('该网页目前无法访问!')
return judge_identifier
# 敏感词过滤
def sensitive_word_filter(content):
ah = Ac_auto.ac_automation()
path = 'sensitive_words.txt'
ah.parse(path)
content = ah.words_replace(content)
# text1 = "新疆骚乱苹果新品发布会"
# text2 = ah.words_replace(text1)
# print(text1)
# print(text2)
return content
# 网页图片相对路径转绝对路径
# 读入一个html原码,修正图片路径后return一个新的html代码
def path_rewrite(html):
new_html = re.sub('="/uploadfile/', '="http://news.cqu.edu.cn/uploadfile/', html)
return new_html
def main():
"""
获取所有的栏目链接
all_news_urls[0-4]: 爬取的第一大类:新闻模块(包括综合新闻、教学科研、招生就业、交流合作、校园生活栏目)
all_news_urls[5]:爬取的第二大类:媒体重大
all_news_urls[6]:爬取的第三大类:通知公告简报
all_news_urls[7]:爬取的第四大类:学术预告
all_news_urls[8]:爬取的第五大类:快讯
all_news_urls[9]:爬取的第六大类:专题
"""
with open('dict_data.txt', 'r+') as f_data:
all_news_urls = all_urls_list(f_data)
# 获取每个栏目下每页的链接
# 爬取的第一大类:新闻模块(包括综合新闻、教学科研、招生就业、交流合作、校园生活栏目)
for url in all_news_urls[:5]:
url_list = get_url_list(url, all_news_urls, f_data)
get_news_info(url_list, url, all_news_urls, f_data)
time.sleep(sleep_time)
# 爬取的第二大类:媒体重大
url = all_news_urls[5]
url_list = get_url_list(url, all_news_urls, f_data)
get_media_info(url_list, f_data)
time.sleep(sleep_time)
# 爬取的第三大类:通知公告简报
url = all_news_urls[6]
url_list = get_url_list(url, all_news_urls, f_data)
get_notice_info(url_list, f_data)
time.sleep(sleep_time)
# 爬取的第四大类:学术预告
url = all_news_urls[7]
url_list = get_url_list(url, all_news_urls, f_data)
get_academic_info(url_list, f_data)
time.sleep(sleep_time)
# 爬取的第五大类:快讯
url = all_news_urls[8]
url_list = get_url_list(url, all_news_urls, f_data)
get_express_info(url_list, f_data)
time.sleep(sleep_time)
# 爬取的第六大类:专题。
url = all_news_urls[9]
url_dict = get_topic_url_list(url, f_data)
get_topic_info(url_dict, f_data)
time.sleep(sleep_time)
print('{} {} 的爬虫任务已完成!'.format(spider_name, spider_url))
cur = conn.cursor()
if __name__ == '__main__':
main()
# 爬虫结束,更新爬虫状态为-1,停止
cur.execute("UPDATE t_spider_task SET status = -1 WHERE id = %s", task_id)
cur.close()
conn.commit()
conn.close()
| [
"Ac_auto.ac_automation",
"os.path.exists",
"json.loads",
"pdfkit.from_url",
"pdfkit.from_string",
"json.dumps",
"pymysql.connect",
"requests.get",
"os.getcwd",
"time.sleep",
"datetime.datetime.now",
"lxml.etree.HTML",
"os.mkdir",
"time.time",
"re.sub",
"datetime.date.today",
"pdfkit.... | [((404, 542), 'pymysql.connect', 'pymysql.connect', ([], {'host': '"""localhost"""', 'port': '(3307)', 'user': '"""root"""', 'passwd': '"""<PASSWORD>"""', 'db': '"""spider_test"""', 'use_unicode': '(True)', 'charset': '"""utf8mb4"""'}), "(host='localhost', port=3307, user='root', passwd=\n '<PASSWORD>', db='spider_test', use_unicode=True, charset='utf8mb4')\n", (419, 542), False, 'import pymysql\n'), ((789, 851), 'pdfkit.configuration', 'pdfkit.configuration', ([], {'wkhtmltopdf': '"""/usr/local/bin/wkhtmltopdf"""'}), "(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')\n", (809, 851), False, 'import pdfkit\n'), ((2115, 2136), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (2134, 2136), False, 'import datetime\n'), ((4269, 4310), 'requests.get', 'requests.get', (['spider_url'], {'headers': 'headers'}), '(spider_url, headers=headers)\n', (4281, 4310), False, 'import requests\n'), ((4347, 4365), 'lxml.etree.HTML', 'etree.HTML', (['r.text'], {}), '(r.text)\n', (4357, 4365), False, 'from lxml import etree\n'), ((5221, 5255), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (5233, 5255), False, 'import requests\n'), ((5292, 5310), 'lxml.etree.HTML', 'etree.HTML', (['r.text'], {}), '(r.text)\n', (5302, 5310), False, 'from lxml import etree\n'), ((6622, 6643), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (6641, 6643), False, 'import datetime\n'), ((9521, 9555), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (9533, 9555), False, 'import requests\n'), ((9592, 9610), 'lxml.etree.HTML', 'etree.HTML', (['r.text'], {}), '(r.text)\n', (9602, 9610), False, 'from lxml import etree\n'), ((9701, 9722), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (9720, 9722), False, 'import datetime\n'), ((13362, 13403), 'requests.get', 'requests.get', (['module_url'], {'headers': 'headers'}), '(module_url, headers=headers)\n', (13374, 13403), False, 'import requests\n'), ((13440, 13458), 'lxml.etree.HTML', 'etree.HTML', (['r.text'], {}), '(r.text)\n', (13450, 13458), False, 'from lxml import etree\n'), ((14003, 14014), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (14012, 14014), False, 'import os\n'), ((14074, 14097), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (14088, 14097), False, 'import os\n'), ((19099, 19110), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (19108, 19110), False, 'import os\n'), ((19170, 19193), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (19184, 19193), False, 'import os\n'), ((25195, 25206), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (25204, 25206), False, 'import os\n'), ((25266, 25289), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (25280, 25289), False, 'import os\n'), ((30717, 30728), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (30726, 30728), False, 'import os\n'), ((30788, 30811), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (30802, 30811), False, 'import os\n'), ((35945, 35956), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (35954, 35956), False, 'import os\n'), ((36016, 36039), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (36030, 36039), False, 'import os\n'), ((41084, 41095), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (41093, 41095), False, 'import os\n'), ((41155, 41178), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (41169, 41178), False, 'import os\n'), ((45063, 45086), 'Ac_auto.ac_automation', 'Ac_auto.ac_automation', ([], {}), '()\n', (45084, 45086), False, 'import Ac_auto\n'), ((45397, 45467), 're.sub', 're.sub', (['"""="/uploadfile/"""', '"""="http://news.cqu.edu.cn/uploadfile/"""', 'html'], {}), '(\'="/uploadfile/\', \'="http://news.cqu.edu.cn/uploadfile/\', html)\n', (45403, 45467), False, 'import re\n'), ((47049, 47071), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (47059, 47071), False, 'import time\n'), ((2009, 2028), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (2019, 2028), False, 'import json\n'), ((5174, 5193), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (5184, 5193), False, 'import json\n'), ((9470, 9489), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (9480, 9489), False, 'import json\n'), ((13095, 13114), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (13105, 13114), False, 'import json\n'), ((14128, 14145), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (14136, 14145), False, 'import os\n'), ((14199, 14233), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (14211, 14233), False, 'import requests\n'), ((14304, 14324), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (14314, 14324), False, 'from lxml import etree\n'), ((18757, 18776), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (18767, 18776), False, 'import json\n'), ((19224, 19241), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (19232, 19241), False, 'import os\n'), ((19295, 19329), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (19307, 19329), False, 'import requests\n'), ((19400, 19420), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (19410, 19420), False, 'from lxml import etree\n'), ((24868, 24887), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (24878, 24887), False, 'import json\n'), ((25320, 25337), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (25328, 25337), False, 'import os\n'), ((25391, 25425), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (25403, 25425), False, 'import requests\n'), ((25496, 25516), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (25506, 25516), False, 'from lxml import etree\n'), ((30405, 30424), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (30415, 30424), False, 'import json\n'), ((30842, 30859), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (30850, 30859), False, 'import os\n'), ((30913, 30947), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (30925, 30947), False, 'import requests\n'), ((31018, 31038), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (31028, 31038), False, 'from lxml import etree\n'), ((35605, 35624), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (35615, 35624), False, 'import json\n'), ((36070, 36087), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (36078, 36087), False, 'import os\n'), ((40809, 40828), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (40819, 40828), False, 'import json\n'), ((41209, 41226), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (41217, 41226), False, 'import os\n'), ((46305, 46327), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (46315, 46327), False, 'import time\n'), ((46496, 46518), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (46506, 46518), False, 'import time\n'), ((46687, 46709), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (46697, 46709), False, 'import time\n'), ((46875, 46897), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (46885, 46897), False, 'import time\n'), ((2489, 2500), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2498, 2500), False, 'import os\n'), ((2578, 2601), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (2592, 2601), False, 'import os\n'), ((2685, 2726), 'requests.get', 'requests.get', (['spider_url'], {'headers': 'headers'}), '(spider_url, headers=headers)\n', (2697, 2726), False, 'import requests\n'), ((3415, 3436), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (3425, 3436), False, 'import json\n'), ((7032, 7043), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7041, 7043), False, 'import os\n'), ((7119, 7142), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (7133, 7142), False, 'import os\n'), ((7226, 7265), 'requests.get', 'requests.get', (['temp_url'], {'headers': 'headers'}), '(temp_url, headers=headers)\n', (7238, 7265), False, 'import requests\n'), ((7962, 7983), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (7972, 7983), False, 'import json\n'), ((10100, 10111), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10109, 10111), False, 'import os\n'), ((10187, 10210), 'os.path.exists', 'os.path.exists', (['new_dir'], {}), '(new_dir)\n', (10201, 10210), False, 'import os\n'), ((10294, 10328), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (10306, 10328), False, 'import requests\n'), ((11020, 11041), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (11030, 11041), False, 'import json\n'), ((46117, 46139), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (46127, 46139), False, 'import time\n'), ((2648, 2665), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (2656, 2665), False, 'import os\n'), ((2935, 2946), 'time.time', 'time.time', ([], {}), '()\n', (2944, 2946), False, 'import time\n'), ((3674, 3749), 'pdfkit.from_url', 'pdfkit.from_url', (['spider_url', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(spider_url, pdf_file, configuration=confg, options=options)\n', (3689, 3749), False, 'import pdfkit\n'), ((3831, 3853), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (3841, 3853), False, 'import time\n'), ((7189, 7206), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (7197, 7206), False, 'import os\n'), ((7474, 7485), 'time.time', 'time.time', ([], {}), '()\n', (7483, 7485), False, 'import time\n'), ((8221, 8294), 'pdfkit.from_url', 'pdfkit.from_url', (['temp_url', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(temp_url, pdf_file, configuration=confg, options=options)\n', (8236, 8294), False, 'import pdfkit\n'), ((8384, 8406), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (8394, 8406), False, 'import time\n'), ((10257, 10274), 'os.mkdir', 'os.mkdir', (['new_dir'], {}), '(new_dir)\n', (10265, 10274), False, 'import os\n'), ((10537, 10548), 'time.time', 'time.time', ([], {}), '()\n', (10546, 10548), False, 'import time\n'), ((11279, 11347), 'pdfkit.from_url', 'pdfkit.from_url', (['url', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(url, pdf_file, configuration=confg, options=options)\n', (11294, 11347), False, 'import pdfkit\n'), ((11437, 11459), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (11447, 11459), False, 'import time\n'), ((36397, 36418), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (36407, 36418), False, 'import json\n'), ((36514, 36548), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (36526, 36548), False, 'import requests\n'), ((36643, 36663), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (36653, 36663), False, 'from lxml import etree\n'), ((39984, 40063), 'pdfkit.from_string', 'pdfkit.from_string', (['html_filter', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(html_filter, pdf_file, configuration=confg, options=options)\n', (40002, 40063), False, 'import pdfkit\n'), ((40138, 40160), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (40148, 40160), False, 'import time\n'), ((41556, 41592), 'requests.get', 'requests.get', (['value'], {'headers': 'headers'}), '(value, headers=headers)\n', (41568, 41592), False, 'import requests\n'), ((3173, 3196), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3194, 3196), False, 'import datetime\n'), ((7718, 7741), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (7739, 7741), False, 'import datetime\n'), ((10781, 10804), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10802, 10804), False, 'import datetime\n'), ((14847, 14886), 'requests.get', 'requests.get', (['each_url'], {'headers': 'headers'}), '(each_url, headers=headers)\n', (14859, 14886), False, 'import requests\n'), ((14993, 15013), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (15003, 15013), False, 'from lxml import etree\n'), ((16365, 16416), 'json.dumps', 'json.dumps', (['dict_news'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(dict_news, ensure_ascii=False, indent=4)\n', (16375, 16416), False, 'import json\n'), ((20469, 20508), 'requests.get', 'requests.get', (['each_url'], {'headers': 'headers'}), '(each_url, headers=headers)\n', (20481, 20508), False, 'import requests\n'), ((20615, 20635), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (20625, 20635), False, 'from lxml import etree\n'), ((22474, 22526), 'json.dumps', 'json.dumps', (['dict_media'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(dict_media, ensure_ascii=False, indent=4)\n', (22484, 22526), False, 'import json\n'), ((26043, 26082), 'requests.get', 'requests.get', (['each_url'], {'headers': 'headers'}), '(each_url, headers=headers)\n', (26055, 26082), False, 'import requests\n'), ((26189, 26209), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (26199, 26209), False, 'from lxml import etree\n'), ((28000, 28053), 'json.dumps', 'json.dumps', (['dict_notice'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(dict_notice, ensure_ascii=False, indent=4)\n', (28010, 28053), False, 'import json\n'), ((31720, 31759), 'requests.get', 'requests.get', (['each_url'], {'headers': 'headers'}), '(each_url, headers=headers)\n', (31732, 31759), False, 'import requests\n'), ((31866, 31886), 'lxml.etree.HTML', 'etree.HTML', (['raw_html'], {}), '(raw_html)\n', (31876, 31886), False, 'from lxml import etree\n'), ((33213, 33268), 'json.dumps', 'json.dumps', (['dict_academic'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(dict_academic, ensure_ascii=False, indent=4)\n', (33223, 33268), False, 'import json\n'), ((36761, 36772), 'time.time', 'time.time', ([], {}), '()\n', (36770, 36772), False, 'import time\n'), ((39476, 39530), 'json.dumps', 'json.dumps', (['dict_express'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(dict_express, ensure_ascii=False, indent=4)\n', (39486, 39530), False, 'import json\n'), ((42416, 42468), 'json.dumps', 'json.dumps', (['dict_topic'], {'ensure_ascii': '(False)', 'indent': '(4)'}), '(dict_topic, ensure_ascii=False, indent=4)\n', (42426, 42468), False, 'import json\n'), ((42736, 42757), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (42746, 42757), False, 'import json\n'), ((43044, 43114), 'pdfkit.from_url', 'pdfkit.from_url', (['value', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(value, pdf_file, configuration=confg, options=options)\n', (43059, 43114), False, 'import pdfkit\n'), ((43195, 43217), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (43205, 43217), False, 'import time\n'), ((43648, 43669), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (43658, 43669), False, 'import json\n'), ((15179, 15190), 'time.time', 'time.time', ([], {}), '()\n', (15188, 15190), False, 'import time\n'), ((16898, 16919), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (16908, 16919), False, 'import json\n'), ((17231, 17304), 'pdfkit.from_url', 'pdfkit.from_url', (['each_url', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(each_url, pdf_file, configuration=confg, options=options)\n', (17246, 17304), False, 'import pdfkit\n'), ((17395, 17417), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (17405, 17417), False, 'import time\n'), ((17817, 17838), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (17827, 17838), False, 'import json\n'), ((20801, 20812), 'time.time', 'time.time', ([], {}), '()\n', (20810, 20812), False, 'import time\n'), ((23000, 23021), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (23010, 23021), False, 'import json\n'), ((23333, 23406), 'pdfkit.from_url', 'pdfkit.from_url', (['each_url', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(each_url, pdf_file, configuration=confg, options=options)\n', (23348, 23406), False, 'import pdfkit\n'), ((23497, 23519), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (23507, 23519), False, 'import time\n'), ((23919, 23940), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (23929, 23940), False, 'import json\n'), ((26375, 26386), 'time.time', 'time.time', ([], {}), '()\n', (26384, 26386), False, 'import time\n'), ((28535, 28556), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (28545, 28556), False, 'import json\n'), ((28868, 28941), 'pdfkit.from_url', 'pdfkit.from_url', (['each_url', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(each_url, pdf_file, configuration=confg, options=options)\n', (28883, 28941), False, 'import pdfkit\n'), ((29032, 29054), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (29042, 29054), False, 'import time\n'), ((29454, 29475), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (29464, 29475), False, 'import json\n'), ((32052, 32063), 'time.time', 'time.time', ([], {}), '()\n', (32061, 32063), False, 'import time\n'), ((33738, 33759), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (33748, 33759), False, 'import json\n'), ((34072, 34145), 'pdfkit.from_url', 'pdfkit.from_url', (['each_url', 'pdf_file'], {'configuration': 'confg', 'options': 'options'}), '(each_url, pdf_file, configuration=confg, options=options)\n', (34087, 34145), False, 'import pdfkit\n'), ((34238, 34260), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (34248, 34260), False, 'import time\n'), ((34659, 34680), 'json.dumps', 'json.dumps', (['dict_data'], {}), '(dict_data)\n', (34669, 34680), False, 'import json\n'), ((41912, 41923), 'time.time', 'time.time', ([], {}), '()\n', (41921, 41923), False, 'import time\n'), ((16014, 16037), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (16035, 16037), False, 'import datetime\n'), ((22292, 22315), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (22313, 22315), False, 'import datetime\n'), ((27641, 27664), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (27662, 27664), False, 'import datetime\n'), ((33025, 33048), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (33046, 33048), False, 'import datetime\n'), ((39290, 39313), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (39311, 39313), False, 'import datetime\n'), ((42280, 42303), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (42301, 42303), False, 'import datetime\n'), ((43366, 43389), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (43387, 43389), False, 'import datetime\n')] |
import pandas as pd
import os
import shutil
def get_list_zips_file_path(folder_path):
list_file_path_zip = []
for root, _, files in os.walk(folder_path):
for file_ in files:
file_lower = file_.lower()
if file_lower.endswith(tuple(['.zip', '.rar', '.7z'])):
file_path_zip = os.path.join(root, file_)
list_file_path_zip.append(file_path_zip)
return list_file_path_zip
def get_list_dict(list_file_path_zip, document_hashtag):
l = []
for index, file_path in enumerate(list_file_path_zip):
d = {}
index_str = f'{index+1:03}'
file_name = os.path.basename(file_path)
d['file_output'] = file_path
d['description'] = f'#{document_hashtag}{index_str}\n\n{file_name}'
d['warning'] = ''
l.append(d)
return l
def get_df_desc_docs(dict_description_docs):
df = pd.DataFrame(dict_description_docs)
return df
def get_df_description_original(folder_path_output):
path_file_description = os.path.join(folder_path_output,
'descriptions.xlsx')
df_desc = pd.read_excel(path_file_description, engine='openpyxl')
return df_desc
def save_desc_updated(folder_path_output, df_desc_update):
path_file_description = os.path.join(folder_path_output,
'descriptions.xlsx')
# backup
path_file_description_to = os.path.join(folder_path_output,
'descriptions-only_videos.xlsx')
shutil.copy(path_file_description, path_file_description_to)
# save
df_desc_update.to_excel(path_file_description, index=False)
def descriptions_report_update_with_docs(folder_path_output,
list_file_path_zip,
document_hashtag):
dict_description_docs = get_list_dict(list_file_path_zip, document_hashtag)
df_desc_docs = get_df_desc_docs(dict_description_docs)
df_desc = get_df_description_original(folder_path_output)
df_desc_update = pd.concat([df_desc_docs, df_desc],
axis=0).reset_index(drop=True)
save_desc_updated(folder_path_output, df_desc_update)
def get_list_file_path_zip(folder_path_output):
folder_path_output_files = os.path.join(folder_path_output,
'output_videos')
list_file_path_zip = get_list_zips_file_path(folder_path_output_files)
return list_file_path_zip
| [
"os.path.join",
"os.path.basename",
"shutil.copy",
"pandas.read_excel",
"pandas.DataFrame",
"pandas.concat",
"os.walk"
] | [((143, 163), 'os.walk', 'os.walk', (['folder_path'], {}), '(folder_path)\n', (150, 163), False, 'import os\n'), ((903, 938), 'pandas.DataFrame', 'pd.DataFrame', (['dict_description_docs'], {}), '(dict_description_docs)\n', (915, 938), True, 'import pandas as pd\n'), ((1037, 1090), 'os.path.join', 'os.path.join', (['folder_path_output', '"""descriptions.xlsx"""'], {}), "(folder_path_output, 'descriptions.xlsx')\n", (1049, 1090), False, 'import os\n'), ((1146, 1201), 'pandas.read_excel', 'pd.read_excel', (['path_file_description'], {'engine': '"""openpyxl"""'}), "(path_file_description, engine='openpyxl')\n", (1159, 1201), True, 'import pandas as pd\n'), ((1311, 1364), 'os.path.join', 'os.path.join', (['folder_path_output', '"""descriptions.xlsx"""'], {}), "(folder_path_output, 'descriptions.xlsx')\n", (1323, 1364), False, 'import os\n'), ((1455, 1520), 'os.path.join', 'os.path.join', (['folder_path_output', '"""descriptions-only_videos.xlsx"""'], {}), "(folder_path_output, 'descriptions-only_videos.xlsx')\n", (1467, 1520), False, 'import os\n'), ((1569, 1629), 'shutil.copy', 'shutil.copy', (['path_file_description', 'path_file_description_to'], {}), '(path_file_description, path_file_description_to)\n', (1580, 1629), False, 'import shutil\n'), ((2350, 2399), 'os.path.join', 'os.path.join', (['folder_path_output', '"""output_videos"""'], {}), "(folder_path_output, 'output_videos')\n", (2362, 2399), False, 'import os\n'), ((646, 673), 'os.path.basename', 'os.path.basename', (['file_path'], {}), '(file_path)\n', (662, 673), False, 'import os\n'), ((2113, 2155), 'pandas.concat', 'pd.concat', (['[df_desc_docs, df_desc]'], {'axis': '(0)'}), '([df_desc_docs, df_desc], axis=0)\n', (2122, 2155), True, 'import pandas as pd\n'), ((332, 357), 'os.path.join', 'os.path.join', (['root', 'file_'], {}), '(root, file_)\n', (344, 357), False, 'import os\n')] |
# Authors: <NAME> <<EMAIL>>
# + All contributors to <https://github.com/smarie/python-pytest-cases>
#
# License: 3-clause BSD, <https://github.com/smarie/python-pytest-cases/blob/master/LICENSE>
import pytest
from pytest_cases import parametrize_with_cases
def case_sum_one_plus_two():
a = 1
b = 2
c = 3
return a, b, c
@parametrize_with_cases(argnames=["a", "b", "c"], cases=".")
def test_argnames_as_list(a, b, c):
assert a + b == c
@parametrize_with_cases(argnames=("a", "b", "c"), cases=".")
def test_argnames_as_tuple(a, b, c):
assert a + b == c
def test_argnames_from_invalid_type():
with pytest.raises(
TypeError, match="^argnames should be a string, list or a tuple$"
):
parametrize_with_cases(argnames=42, cases=".")(lambda _: None)
def test_argnames_element_from_invalid_type():
with pytest.raises(
TypeError, match="^all argnames should be strings$"
):
parametrize_with_cases(argnames=["a", 2, "c"], cases=".")(lambda _: None)
| [
"pytest_cases.parametrize_with_cases",
"pytest.raises"
] | [((350, 409), 'pytest_cases.parametrize_with_cases', 'parametrize_with_cases', ([], {'argnames': "['a', 'b', 'c']", 'cases': '"""."""'}), "(argnames=['a', 'b', 'c'], cases='.')\n", (372, 409), False, 'from pytest_cases import parametrize_with_cases\n'), ((471, 530), 'pytest_cases.parametrize_with_cases', 'parametrize_with_cases', ([], {'argnames': "('a', 'b', 'c')", 'cases': '"""."""'}), "(argnames=('a', 'b', 'c'), cases='.')\n", (493, 530), False, 'from pytest_cases import parametrize_with_cases\n'), ((640, 725), 'pytest.raises', 'pytest.raises', (['TypeError'], {'match': '"""^argnames should be a string, list or a tuple$"""'}), "(TypeError, match='^argnames should be a string, list or a tuple$'\n )\n", (653, 725), False, 'import pytest\n'), ((869, 935), 'pytest.raises', 'pytest.raises', (['TypeError'], {'match': '"""^all argnames should be strings$"""'}), "(TypeError, match='^all argnames should be strings$')\n", (882, 935), False, 'import pytest\n'), ((748, 794), 'pytest_cases.parametrize_with_cases', 'parametrize_with_cases', ([], {'argnames': '(42)', 'cases': '"""."""'}), "(argnames=42, cases='.')\n", (770, 794), False, 'from pytest_cases import parametrize_with_cases\n'), ((963, 1020), 'pytest_cases.parametrize_with_cases', 'parametrize_with_cases', ([], {'argnames': "['a', 2, 'c']", 'cases': '"""."""'}), "(argnames=['a', 2, 'c'], cases='.')\n", (985, 1020), False, 'from pytest_cases import parametrize_with_cases\n')] |
"""Contains functions to handle roles and permissions"""
import ast
import configparser
import globvars
Config = configparser.ConfigParser()
Config.read("config.INI")
LOBBY_CHANNEL_ID = Config["user"]["LOBBY_CHANNEL_ID"]
SERVER_ID = Config["user"]["SERVER_ID"]
ALIVE_ROLE_ID = Config["user"]["ALIVE_ROLE_ID"]
DEAD_ROLE_ID = Config["user"]["DEAD_ROLE_ID"]
ADMINS_ROLE_ID = Config["user"]["ADMINS_ROLE_ID"]
LOCK_ROLES_ID = ast.literal_eval(Config["user"]["LOCK_ROLES_ID"])
async def add_admin_role(user):
"""Grant the admin role to a member"""
role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(ADMINS_ROLE_ID))
member_obj = globvars.client.get_guild(int(SERVER_ID)).get_member(user.id)
await member_obj.add_roles(role)
async def remove_admin_role(user):
"""Remove the admin role from a member"""
role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(ADMINS_ROLE_ID))
member_obj = globvars.client.get_guild(int(SERVER_ID)).get_member(user.id)
await member_obj.remove_roles(role)
async def add_alive_role(member_obj):
"""Grant the alive role to a player"""
alive_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(ALIVE_ROLE_ID))
add_roles = [alive_role]
remove_roles = []
for (normal_role_id, ingame_role_id) in LOCK_ROLES_ID:
normal_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(normal_role_id))
ingame_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(ingame_role_id))
if normal_role in member_obj.roles:
add_roles.append(ingame_role)
remove_roles.append(normal_role)
await member_obj.add_roles(*add_roles)
await member_obj.remove_roles(*remove_roles)
async def remove_alive_role(member_obj, unlock=False):
"""Remove the alive role from a player"""
alive_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(ALIVE_ROLE_ID))
add_roles = []
remove_roles = [alive_role]
if unlock:
for (normal_role_id, ingame_role_id) in LOCK_ROLES_ID:
normal_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(normal_role_id))
ingame_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(ingame_role_id))
if ingame_role in member_obj.roles:
add_roles.append(normal_role)
remove_roles.append(ingame_role)
await member_obj.add_roles(*add_roles)
await member_obj.remove_roles(*remove_roles)
async def add_dead_role(member_obj):
"""Grant the dead role to a player"""
dead_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(DEAD_ROLE_ID))
await member_obj.add_roles(dead_role)
async def remove_dead_role(member_obj, unlock=False):
"""Remove the dead role from a player"""
dead_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(DEAD_ROLE_ID))
add_roles = []
remove_roles = [dead_role]
if unlock:
for (normal_role_id, ingame_role_id) in LOCK_ROLES_ID:
normal_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(normal_role_id))
ingame_role = globvars.client.get_guild(int(SERVER_ID)).get_role(int(ingame_role_id))
if ingame_role in member_obj.roles:
add_roles.append(normal_role)
remove_roles.append(ingame_role)
await member_obj.add_roles(*add_roles)
await member_obj.remove_roles(*remove_roles)
async def remove_all_alive_roles_pregame():
"""Remove the alive roles from all players during pregame"""
for userid in globvars.master_state.pregame:
member_obj = globvars.client.get_guild(int(SERVER_ID)).get_member(int(userid))
await remove_alive_role(member_obj, unlock=True)
async def remove_all_alive_dead_roles_after_game():
"""Remove the alive and the dead roles from all players after the game is over"""
for player in globvars.master_state.game.sitting_order:
await remove_alive_role(player.user, unlock=True)
await remove_dead_role(player.user, unlock=True)
async def lock_lobby():
"""Lock the lobby channel from non players"""
server = globvars.client.get_guild(int(SERVER_ID))
lobby_channel = globvars.client.get_channel(int(LOBBY_CHANNEL_ID))
await lobby_channel.set_permissions(server.default_role, send_messages=False)
async def unlock_lobby():
"""Unlock the lobby channel to non players"""
server = globvars.client.get_guild(int(SERVER_ID))
lobby_channel = globvars.client.get_channel(int(LOBBY_CHANNEL_ID))
await lobby_channel.set_permissions(server.default_role, send_messages=True)
| [
"ast.literal_eval",
"configparser.ConfigParser"
] | [((115, 142), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (140, 142), False, 'import configparser\n'), ((424, 473), 'ast.literal_eval', 'ast.literal_eval', (["Config['user']['LOCK_ROLES_ID']"], {}), "(Config['user']['LOCK_ROLES_ID'])\n", (440, 473), False, 'import ast\n')] |
# -*- coding: utf-8 -*-
from settings import *
from messages import *
from functions import *
import time
import random
import sqlite3
from aiogram import asyncio
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from aiogram.utils.helper import Helper, HelperMode, ListItem
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.types import ReplyKeyboardMarkup, \
KeyboardButton, InlineKeyboardMarkup, \
InlineKeyboardButton, ReplyKeyboardRemove
from aiogram.utils.exceptions import BotBlocked
import asyncio
from aiogram.utils.exceptions import Unauthorized
from aiogram.dispatcher import DEFAULT_RATE_LIMIT
from aiogram.dispatcher.handler import CancelHandler, current_handler
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.utils.exceptions import Throttled
loop = asyncio.get_event_loop()
bot = Bot(token = token, loop = loop)
dp = Dispatcher(bot, storage = MemoryStorage())
dp.middleware.setup(LoggingMiddleware())
class UserStates(Helper):
GET_CHANNEL_TO_UP = ListItem()
GET_SUB_COUNT = ListItem()
CONFIRMATION = ListItem()
GET_MSG_FOR_MAIL = ListItem()
GET_USER_FOR_UBAN = ListItem()
GET_USER_FOR_CHB = ListItem()
main_menu = ReplyKeyboardMarkup(resize_keyboard = True)
main_menu.add('✔️ Подписаться на канал', '➕ Получить подписчиков')
main_menu.add('👤 Профиль', '👣 Партнёрская программа')
admin_menu = InlineKeyboardMarkup()
statistics_bt = InlineKeyboardButton(text = '📊 Статистика', callback_data = 'stat')
mail_bt = InlineKeyboardButton(text = '✉️ Рассылка', callback_data = 'mail')
give_uban_bt = InlineKeyboardButton(text = '🚷 Выдать бан/разбан', callback_data = 'uban')
change_balance_bt = InlineKeyboardButton(text = '💳 Изменить баланс', callback_data = 'chb')
admin_menu.add(statistics_bt, mail_bt)
admin_menu.add(give_uban_bt, change_balance_bt)
cancel_menu = InlineKeyboardMarkup()
cancel_bt = InlineKeyboardButton(text = '🚫 Отмена', callback_data = 'cancel')
cancel_menu.add(cancel_bt)
#==============
async def user_in_channel_checker():
last_check = get_last_check()
if last_check == None and count_of_channels() >= 1:
global check_user_in_ch
async def check_user_in_ch():
channels = get_channels_for_check()
for x in channels:
my_id = await bot.get_me()
try:
status_bot_in_channel = await bot.get_chat_member(chat_id = x[1], user_id = my_id.id)
status_bot_in_channel = status_bot_in_channel.status
except (Unauthorized, BotBlocked):
status_bot_in_channel = 'left'
if status_bot_in_channel == 'administrator':
subs = x[2]
checked_users = eval(x[-1])
for user in subs:
if user not in checked_users:
get_user = await bot.get_chat_member(chat_id = x[1], user_id = user)
time_from_subs = x[2][user]
if get_user.status == 'left' and ((time_from_subs - datetime.datetime.now()).days < SUBSCRIPTION_TERM) and user_was_fine(x[0], user) == False:
add_user_to_fined(x[0], user)
change_balance(user, FINE_FOR_UNSUBSCRIBING)
increase_fine_count(user)
username = await bot.get_chat(chat_id = x[1])
await bot.send_message(user, SUBSCRIPTION_VIOLATION(username.username, SUBSCRIPTION_TERM, FINE_FOR_UNSUBSCRIBING))
elif get_user.status == 'left' and ((time_from_subs - datetime.datetime.now()).days >= SUBSCRIPTION_TERM) and user_was_fine(x[0], user) == False:
add_member_to_checked(x[0], user)
else:
writer = edit_promotion_status(x[0], 0)
id = x[1]
add_promotion_to_uncheck(x[0])
await bot.send_message(writer, CHANNEL_WAS_DEL_FROM_CHANNEL(id, LINK_TO_INTRODUCTION_AND_RULES), parse_mode = 'Markdown')
set_last_check()
await check_user_in_ch()
elif last_check != None and count_of_channels >= 1:
now_time = datetime.datetime.now()
delta = last_check - now_time
if delta.seconds >= 3600:
await check_user_in_ch()
#==============
@dp.message_handler(lambda m: user_banned(m.from_user.id) == False, commands = ['start'])
async def start_commands_handle(m: types.Message):
if is_user_in_db(m.from_user.id) < 1:
argument = m.get_args()
if (argument is not None) and (argument.isdigit() == True) and (is_user_in_db(argument)) == 1:
add_user_to_db(m.from_user.id, ref_father = argument)
await m.reply(START, reply = False, parse_mode = 'Markdown', reply_markup = main_menu)
await bot.send_message(text = NEW_REFERAL(argument), chat_id = argument)
else:
add_user_to_db(m.from_user.id)
await m.reply(START, reply = False, parse_mode = 'Markdown', reply_markup = main_menu)
else:
await m.reply(UPDATE, reply = False, parse_mode = 'Markdown', reply_markup = main_menu)
@dp.message_handler(lambda m: m.from_user.id in admins, commands = ['admin'])
async def admin_command_handle(m: types.Message):
await m.reply(SELECT_ADMIN_MENU_BUTTON, reply = False, reply_markup = admin_menu)
@dp.message_handler(lambda m: m.from_user.id not in admins, commands = ['admin'])
async def handle_not_admin(m: types.Message):
await m.reply(YOU_WAS_HACK_ME, reply = False)
@dp.message_handler(lambda m: m.text == '👤 Профиль' and user_banned(m.from_user.id) == False)
async def profile_button_handle(m: types.Message):
await m.reply(PROFILE(m), reply = False, parse_mode = 'Markdown')
@dp.message_handler(lambda m: m.text == '➕ Получить подписчиков' and user_banned(m.from_user.id) == False)
async def add_channel_handle(m: types.Message):
if user_balance(m.from_user.id) >= LITTLE_SUBCOIN_TO_GET_SUBS:
state = dp.current_state(user = m.from_user.id)
await state.set_state('GET_CHANNEL_TO_UP')
await m.reply(GIVE_CHANNEL_LINK, reply = False, parse_mode = 'Markdown', reply_markup = cancel_menu)
else:
await m.reply(LITTLE_SUBCOIN_1, reply = False)
@dp.message_handler(state = 'GET_CHANNEL_TO_UP')
async def channel_to_up_handle(m: types.Message):
try:
if m.content_type == 'text':
my_id = await bot.get_me()
get_channel= await bot.get_chat(m.text)
if get_channel.type == 'channel':
status_bot_in_channel = await bot.get_chat_member(chat_id = m.text, user_id = my_id.id)
if check_channel_in_db(get_channel.id) == 1:
if status_bot_in_channel.status == 'administrator':
number = save_channel(channel_id = get_channel.id, writer = m.from_user.id)
cancel_promotion = InlineKeyboardMarkup()
cancel_promotion.add(InlineKeyboardButton(text = '🚫 Отмена', callback_data = 'cancel_' + str(number)))
await bot.delete_message(message_id = m.message_id - 1, chat_id = m.from_user.id)
await m.reply(SEND_SUB_COUNT_1(m), reply = False, parse_mode = 'Markdown', reply_markup = cancel_promotion)
state = dp.current_state(user = m.from_user.id)
await state.set_state('GET_SUB_COUNT')
else:
await bot.delete_message(message_id = m.message_id - 1, chat_id = m.from_user.id)
await m.reply(BOT_NOT_IN_CHANNEL, parse_mode = 'Markdown', reply_markup = cancel_menu)
elif check_channel_in_db(get_channel.id) == 0:
await m.reply(CHANNEL_ON_PROMOTION_2, reply = False, reply_markup = cancel_menu)
else:
await bot.delete_message(message_id = m.message_id - 1, chat_id = m.from_user.id)
await m.reply(THIS_IS_NOT_CHANNEL, parse_mode = 'Markdown', reply_markup = cancel_menu)
else:
await m.reply(THIS_IS_NOT_TEXT, parse_mode = 'Markdown', reply_markup = cancel_menu)
except Exception as e:
await m.reply(e, reply_markup = cancel_menu)
@dp.message_handler(state = 'GET_SUB_COUNT')
async def handle_get_sub_count(m: types.Message):
if (m.content_type == 'text') and (m.text.isdigit() == True) and (int(m.text) >= LITTLE_SUBCOIN_TO_GET_SUBS) and user_balance(m.from_user.id) >= int(m.text):
save_channel(subs_count = int(m.text), writer = m.from_user.id)
channel_stat = get_channel_stat(m.from_user.id)
username = await bot.get_chat(channel_stat[0][0][1])
username = username.username
confirmation_menu = InlineKeyboardMarkup()
confirmation_menu.add(InlineKeyboardButton(text = '🚫 Отмена', callback_data = 'cancel_' + str(channel_stat[-1])), InlineKeyboardButton(text = '✅ Подтвердить', callback_data = 'confirm_' + str(channel_stat[-1])))
state = dp.current_state(user = m.from_user.id)
await state.set_state('CONFIRMATION')
await bot.delete_message(message_id = m.message_id - 1, chat_id = m.from_user.id)
await m.reply(CONFIRM_ADDING_CHANNEL(username, channel_stat[0][0][0], channel_stat[0][0][0]), reply = False, reply_markup = confirmation_menu)
else:
channel_stat = get_channel_stat(m.from_user.id)
username = await bot.get_chat(channel_stat[0][0][1])
username = username.username
cancel_wnum_menu= InlineKeyboardMarkup()
cancel_wnum_menu.add(InlineKeyboardButton(text = '🚫 Отмена', callback_data = 'cancel_' + str(channel_stat[-1])))
await m.reply(LITTLE_SUBCOIN_2, reply = False, reply_markup = cancel_wnum_menu)
@dp.message_handler(lambda m: m.text == '✔️ Подписаться на канал' and user_banned(m.from_user.id) == False)
async def sent_instruction_for_subscribe(m: types.Message):
black_list = []
while True:
channels_list = channel_for_subscribe(m.from_user.id)
if channels_list != 0 and len(channels_list) > len(black_list):
channel_to_subscribe = random.choice(list(channels_list))
if channel_to_subscribe not in black_list:
my_id = await bot.get_me()
try:
bot_status = await bot.get_chat_member(chat_id = channel_to_subscribe, user_id = my_id.id)
bot_status = bot_status.status
except (Unauthorized, BotBlocked):
bot_status = 'left'
if bot_status == "administrator":
status_of_user = await bot.get_chat_member(chat_id = channel_to_subscribe, user_id = m.from_user.id)
if status_of_user.status == 'left':
username = await bot.get_chat(chat_id = channel_to_subscribe)
subscribe_menu = InlineKeyboardMarkup()
subscribe_menu.add(InlineKeyboardButton(text = 'Перейти к каналу', url = 'tg://resolve?domain=' + username.username))
subscribe_menu.add(InlineKeyboardButton(text = 'Проверить подписку', callback_data = 'sub_' + str(channels_list[channel_to_subscribe])))
await m.reply(SUBSCRIBE_ON_THIS_CHANNEL, reply_markup = subscribe_menu, reply = False)
break
else:
black_list.append(channel_to_subscribe)
else:
writer = edit_promotion_status(channels_list[channel_to_subscribe], 0)
id = channel_to_subscribe
await bot.send_message(writer, CHANNEL_WAS_DEL_FROM_CHANNEL(id, LINK_TO_INTRODUCTION_AND_RULES))
else:
await m.reply(NO_HAVE_CHANNELS_FOR_SUBSCRIBE, reply = False)
break
@dp.message_handler(content_types = ['text', 'video', 'photo', 'document', 'animation'], state = 'GET_MSG_FOR_MAIL')
async def send_mail(m: types.Message):
state = dp.current_state(user = m.from_user.id)
await state.reset_state()
users = get_users_for_mailing()
if m.content_type == 'text':
all_users = 0
blocked_users = 0
for x in users:
try:
await bot.send_message(x[0], m.html_text, parse_mode = 'HTML')
all_users += 1
await asyncio.sleep(0.3)
except BotBlocked:
blocked_users += 1
await m.reply(MAILING_END(all_users, blocked_users), reply = False)
if m.content_type == 'photo':
all_users = 0
blocked_users = 0
for x in users:
try:
await bot.send_photo(x[0], photo = m.photo[-1].file_id, caption = m.html_text, parse_mode = 'HTML')
all_users += 1
await asyncio.sleep(0.3)
except BotBlocked:
blocked_users += 1
await m.reply(MAILING_END(all_users, blocked_users), reply = False)
if m.content_type == 'video':
all_users = 0
blocked_users = 0
for x in users:
try:
await bot.send_video(x[0], video = m.video.file_id, caption = m.html_text, parse_mode = 'HTML')
all_users += 1
await asyncio.sleep(0.3)
except BotBlocked:
blocked_users += 1
await m.reply(MAILING_END(all_users, blocked_users), reply = False)
if m.content_type == 'animation':
all_users = 0
blocked_users = 0
for x in users:
try:
await bot.send_animation(x[0], animation = m.animation.file_id)
all_users += 1
await asyncio.sleep(0.3)
except BotBlocked:
blocked_users += 1
await m.reply(MAILING_END(all_users, blocked_users), reply = False)
if m.content_type == 'document':
all_users = 0
blocked_users = 0
for x in users:
try:
await bot.send_document(x[0], document = m.document.file_id)
all_users += 1
await asyncio.sleep(0.3)
except BotBlocked:
blocked_users += 1
await m.reply(MAILING_END(all_users, blocked_users), reply = False)
@dp.message_handler(lambda m: m.text == '👣 Партнёрская программа' and user_banned(m.from_user.id) == False)
async def referal_button_handle(m: types.Message):
get_bot = await bot.get_me()
await m.reply(PARTNER_PROGRAM(get_bot.username, m.from_user.id, referals(m.from_user.id)), reply = False, parse_mode = 'Markdown')
@dp.callback_query_handler(lambda c: c.data == 'cancel', state = UserStates.all())
async def cancel_button_handle(c: types.callback_query):
state = dp.current_state(user = c.from_user.id)
await state.reset_state()
await c.message.edit_text(CANCEL_TEXT)
@dp.message_handler(lambda m: m.from_user.id in admins, content_types = ['text'], state = 'GET_USER_FOR_CHB')
async def handle_user_for_chb(m: types.Message):
list = m.text.split(' ')
if len(list) == 2:
id = list[0]
value = list[1]
if id.isdigit() and value.lstrip('-').isdigit():
result = change_balance(id, value)
await m.reply(result, reply = False)
else:
await m.reply(NOT_INTEGER, reply = False)
else:
await m.reply(LITTLE_VALUE, reply = False)
state = dp.current_state(user = m.from_user.id)
await state.reset_state()
@dp.message_handler(lambda m: m.from_user.id in admins, content_types = ['text'], state = 'GET_USER_FOR_UBAN')
async def handle_user_for_uban(m: types.Message):
list = m.text.split(' ')
if len(list) == 2:
id = list[0]
decision = list[1]
if id.isdigit() and decision.isdigit():
result = uban_user(id, decision)
await m.reply(result, reply = False)
if int(decision) == 0:
await bot.send_message(id, YOU_WAS_BANNED)
else:
await m.reply(NOT_INTEGER, reply = False)
else:
await m.reply(LITTLE_VALUE, reply = False)
state = dp.current_state(user = m.from_user.id)
await state.reset_state()
@dp.callback_query_handler(lambda c: 'cancel_' in c.data, state = ['CONFIRMATION', 'GET_SUB_COUNT'])
async def cancel_wnum_button_handler(c: types.callback_query):
number = c.data.replace('cancel_', '')
status = delete_channel_from_db(number)
if status == 0:
await c.message.edit_text(CHANNEL_ON_PROMOTION)
state = dp.current_state(user = c.from_user.id)
await state.reset_state()
else:
await c.message.edit_text(CANCEL_TEXT)
state = dp.current_state(user = c.from_user.id)
await state.reset_state()
@dp.callback_query_handler(lambda c: 'confirm_' in c.data, state = 'CONFIRMATION')
async def confirm_button_handler(c :types.callback_query):
number = c.data.replace('confirm_', '')
luck = confirm_order(number)
if luck == 1:
await c.message.edit_text(CHANNEL_SUCCESSFULLY_ADED)
state = dp.current_state(user = c.from_user.id)
await state.reset_state()
else:
await c.message.edit_text(luck)
state = dp.current_state(user = c.from_user.id)
await state.reset_state()
@dp.callback_query_handler(lambda c: 'sub_' in c.data)
async def check_user_in_channel(c: types.CallbackQuery):
number = c.data.replace('sub_', '')
info = promotion_info(number)
if check_user_to_do_this(number, info[1]) == False:
if info[0] == 1:
my_id = await bot.get_me()
try:
bot_status = await bot.get_chat_member(chat_id = info[1], user_id = my_id.id)
bot_status = bot_status.status
except (Unauthorized, BotBlocked):
bot_status = 'left'
if bot_status == "administrator":
status_of_user = await bot.get_chat_member(chat_id = info[1], user_id = c.from_user.id)
if status_of_user.status != 'left':
add_to_subs = add_user_to_subscribers(number, c.from_user.id)
username = await bot.get_chat(chat_id = add_to_subs[1])
if add_to_subs[0] == 1:
await c.message.edit_text(SUBSCRIBE_IS_SUCCESSFULLY(username.username))
else:
await c.message.edit_text(YOU_ARE_LATE_FOR_SUBS(username.username))
else:
await c.answer(text = YOU_DONT_COMPLETE_SUBS, show_alert = True)
else:
writer = edit_promotion_status(number, 0)
add_promotion_to_uncheck(number)
await bot.send_message(writer, CHANNEL_WAS_DEL_FROM_CHANNEL(add_to_subs[1], LINK_TO_INTRODUCTION_AND_RULES))
else:
await c.message.edit_text(YOU_ARE_LATE_FOR_SUBS(username.username))
else:
await c.message.edit_text(YOU_DID_THIS)
@dp.callback_query_handler(lambda c: c.data == 'stat')
async def handle_stat_button(c: types.CallbackQuery):
await c.message.edit_text(START_COLLECT_STAT)
users = get_users_for_mailing()
all_users = 0
blocked_users = 0
for x in users:
try:
await bot.send_chat_action(chat_id = x[0], action = 'typing')
all_users += 1
except BotBlocked:
blocked_users += 1
await asyncio.sleep(0.1)
await bot.send_message(c.from_user.id, STATISTICS(all_users, blocked_users))
@dp.callback_query_handler(lambda c: c.data == 'mail')
async def handle_mail_button(c: types.CallbackQuery):
await c.message.edit_text(SEND_MESSAGE_FOR_SEND, parse_mode = 'Markdown', reply_markup = cancel_menu)
state = dp.current_state(user = c.from_user.id)
await state.set_state('GET_MSG_FOR_MAIL')
@dp.callback_query_handler(lambda c: c.data == 'uban')
async def handle_uban_button(c: types.CallbackQuery):
await c.message.edit_text(SEND_USER_FOR_UBAN, reply_markup = cancel_menu)
state = dp.current_state(user = c.from_user.id)
await state.set_state('GET_USER_FOR_UBAN')
@dp.callback_query_handler(lambda c: c.data == 'chb')
async def handle_chb_button(c: types.CallbackQuery):
await c.message.edit_text(SEND_USER_FOR_CHANGE_BALANCE)
state = dp.current_state(user = c.from_user.id)
await state.set_state('GET_USER_FOR_CHB')
async def on_shutdown(dispatcher: Dispatcher):
await dispatcher.storage.close()
await dispatcher.storage.wait_closed()
if __name__ == '__main__':
executor.start_polling(dp, skip_updates = True, on_shutdown = on_shutdown, loop = loop)
| [
"aiogram.utils.helper.ListItem",
"aiogram.contrib.fsm_storage.memory.MemoryStorage",
"aiogram.types.InlineKeyboardButton",
"aiogram.types.ReplyKeyboardMarkup",
"aiogram.contrib.middlewares.logging.LoggingMiddleware",
"aiogram.types.InlineKeyboardMarkup",
"asyncio.sleep",
"aiogram.Bot",
"asyncio.get_... | [((946, 970), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (968, 970), False, 'import asyncio\n'), ((978, 1005), 'aiogram.Bot', 'Bot', ([], {'token': 'token', 'loop': 'loop'}), '(token=token, loop=loop)\n', (981, 1005), False, 'from aiogram import Bot, types\n'), ((1348, 1389), 'aiogram.types.ReplyKeyboardMarkup', 'ReplyKeyboardMarkup', ([], {'resize_keyboard': '(True)'}), '(resize_keyboard=True)\n', (1367, 1389), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((1527, 1549), 'aiogram.types.InlineKeyboardMarkup', 'InlineKeyboardMarkup', ([], {}), '()\n', (1547, 1549), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((1566, 1629), 'aiogram.types.InlineKeyboardButton', 'InlineKeyboardButton', ([], {'text': '"""📊 Статистика"""', 'callback_data': '"""stat"""'}), "(text='📊 Статистика', callback_data='stat')\n", (1586, 1629), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((1644, 1706), 'aiogram.types.InlineKeyboardButton', 'InlineKeyboardButton', ([], {'text': '"""✉️ Рассылка"""', 'callback_data': '"""mail"""'}), "(text='✉️ Рассылка', callback_data='mail')\n", (1664, 1706), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((1726, 1796), 'aiogram.types.InlineKeyboardButton', 'InlineKeyboardButton', ([], {'text': '"""🚷 Выдать бан/разбан"""', 'callback_data': '"""uban"""'}), "(text='🚷 Выдать бан/разбан', callback_data='uban')\n", (1746, 1796), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((1821, 1888), 'aiogram.types.InlineKeyboardButton', 'InlineKeyboardButton', ([], {'text': '"""💳 Изменить баланс"""', 'callback_data': '"""chb"""'}), "(text='💳 Изменить баланс', callback_data='chb')\n", (1841, 1888), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((1995, 2017), 'aiogram.types.InlineKeyboardMarkup', 'InlineKeyboardMarkup', ([], {}), '()\n', (2015, 2017), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((2030, 2091), 'aiogram.types.InlineKeyboardButton', 'InlineKeyboardButton', ([], {'text': '"""🚫 Отмена"""', 'callback_data': '"""cancel"""'}), "(text='🚫 Отмена', callback_data='cancel')\n", (2050, 2091), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((1081, 1100), 'aiogram.contrib.middlewares.logging.LoggingMiddleware', 'LoggingMiddleware', ([], {}), '()\n', (1098, 1100), False, 'from aiogram.contrib.middlewares.logging import LoggingMiddleware\n'), ((1154, 1164), 'aiogram.utils.helper.ListItem', 'ListItem', ([], {}), '()\n', (1162, 1164), False, 'from aiogram.utils.helper import Helper, HelperMode, ListItem\n'), ((1185, 1195), 'aiogram.utils.helper.ListItem', 'ListItem', ([], {}), '()\n', (1193, 1195), False, 'from aiogram.utils.helper import Helper, HelperMode, ListItem\n'), ((1215, 1225), 'aiogram.utils.helper.ListItem', 'ListItem', ([], {}), '()\n', (1223, 1225), False, 'from aiogram.utils.helper import Helper, HelperMode, ListItem\n'), ((1249, 1259), 'aiogram.utils.helper.ListItem', 'ListItem', ([], {}), '()\n', (1257, 1259), False, 'from aiogram.utils.helper import Helper, HelperMode, ListItem\n'), ((1284, 1294), 'aiogram.utils.helper.ListItem', 'ListItem', ([], {}), '()\n', (1292, 1294), False, 'from aiogram.utils.helper import Helper, HelperMode, ListItem\n'), ((1318, 1328), 'aiogram.utils.helper.ListItem', 'ListItem', ([], {}), '()\n', (1326, 1328), False, 'from aiogram.utils.helper import Helper, HelperMode, ListItem\n'), ((21311, 21397), 'aiogram.utils.executor.start_polling', 'executor.start_polling', (['dp'], {'skip_updates': '(True)', 'on_shutdown': 'on_shutdown', 'loop': 'loop'}), '(dp, skip_updates=True, on_shutdown=on_shutdown, loop\n =loop)\n', (21333, 21397), False, 'from aiogram.utils import executor\n'), ((1043, 1058), 'aiogram.contrib.fsm_storage.memory.MemoryStorage', 'MemoryStorage', ([], {}), '()\n', (1056, 1058), False, 'from aiogram.contrib.fsm_storage.memory import MemoryStorage\n'), ((9342, 9364), 'aiogram.types.InlineKeyboardMarkup', 'InlineKeyboardMarkup', ([], {}), '()\n', (9362, 9364), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((10119, 10141), 'aiogram.types.InlineKeyboardMarkup', 'InlineKeyboardMarkup', ([], {}), '()\n', (10139, 10141), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((20152, 20170), 'asyncio.sleep', 'asyncio.sleep', (['(0.1)'], {}), '(0.1)\n', (20165, 20170), False, 'import asyncio\n'), ((12985, 13003), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (12998, 13003), False, 'import asyncio\n'), ((13438, 13456), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (13451, 13456), False, 'import asyncio\n'), ((13887, 13905), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (13900, 13905), False, 'import asyncio\n'), ((14308, 14326), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (14321, 14326), False, 'import asyncio\n'), ((14725, 14743), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (14738, 14743), False, 'import asyncio\n'), ((7427, 7449), 'aiogram.types.InlineKeyboardMarkup', 'InlineKeyboardMarkup', ([], {}), '()\n', (7447, 7449), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((11511, 11533), 'aiogram.types.InlineKeyboardMarkup', 'InlineKeyboardMarkup', ([], {}), '()\n', (11531, 11533), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n'), ((11577, 11674), 'aiogram.types.InlineKeyboardButton', 'InlineKeyboardButton', ([], {'text': '"""Перейти к каналу"""', 'url': "('tg://resolve?domain=' + username.username)"}), "(text='Перейти к каналу', url='tg://resolve?domain=' +\n username.username)\n", (11597, 11674), False, 'from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove\n')] |
import asyncio
import time
import itertools
from . import pipeline
from . import protocol
class Splitter(pipeline.Element):
def __init__(self, downstream=None, logger=None):
super().__init__(downstream=downstream, logger=logger)
self.buffer = bytes()
self.buffer_length = 0
self.start_index = 0
self.message_size = None
# only for profiling - TODO: remove
self.counter = 0
self.start = None
@asyncio.coroutine
def _process(self, new_data):
# This could be written much shorter, but the Pi performance is very deficient.
# The used operations are chosen considerately.
new_data_length = len(new_data)
buffer_length = self.buffer_length
start_index = self.start_index
message_size = self.message_size
# profiling only
if self.start is None:
self.start = time.time()
self.counter += new_data_length
buffer = self.buffer[start_index:buffer_length] + new_data
buffer_length = buffer_length - start_index + new_data_length
start_index = 0
messages = []
# parse everything we received
while True:
if message_size is None and buffer_length - start_index >= 4: # message_size to parse
message_size = int.from_bytes(buffer[start_index:start_index + 4], byteorder='big')
start_index += 4
elif message_size and buffer_length - start_index >= message_size: # message to parse
message = buffer[start_index:start_index + message_size]
messages.append(message)
start_index += message_size
message_size = None
else: # neither -> need more data
break
if self.counter == 95000:
duration = (time.time() - self.start) * 1000
print("received %d bytes in %.0f ms" % (self.counter, duration))
self.counter = 0
self.start = None
self.buffer_length = buffer_length
self.start_index = start_index
self.message_size = message_size
self.buffer = buffer
return messages
class Parser(pipeline.Element):
@asyncio.coroutine
def _process_single(self, data):
message = protocol.Message()
message.ParseFromString(data)
self._profile('parse', message)
return message
class TypeFilter(pipeline.Element):
def __init__(self, message_type, downstream=None, logger=None):
super().__init__(downstream=downstream, logger=logger)
self.message_type = message_type
self.attribute_name = protocol.Message.MessageType.Name(self.message_type).lower()
@asyncio.coroutine
def _process(self, messages):
message_type = self.message_type
attribute_name = self.attribute_name
def should_include(container):
return container.type == message_type
def extract_message(container):
return getattr(container, attribute_name)
return map(extract_message, filter(should_include, messages))
class DeprecatedFilter(pipeline.Element):
def __init__(self, downstream=None, logger=None):
super().__init__(downstream=downstream, logger=logger)
@asyncio.coroutine
def _process(self, vibration_messages):
result = {}
for vibration in vibration_messages:
key = vibration.priority * 10000 + vibration.target_region * 100 + vibration.actor_index
result[key] = vibration
result = result.values()
return result
| [
"time.time"
] | [((913, 924), 'time.time', 'time.time', ([], {}), '()\n', (922, 924), False, 'import time\n'), ((1883, 1894), 'time.time', 'time.time', ([], {}), '()\n', (1892, 1894), False, 'import time\n')] |
import numpy as np
from mindspore import context
import mindspore as ms
import mindspore.nn as nn
from mindspore.ops import operations as P
from mindspore import Tensor
from mindspore.common.api import _executor
from tests.ut.python.ops.test_math_ops import VirtualLoss
from mindspore.parallel import set_algo_parameters
from mindspore.parallel._utils import _reset_op_id as reset_op_id
import re
class NetWithLoss(nn.Cell):
def __init__(self, network):
super(NetWithLoss, self).__init__()
self.loss = VirtualLoss()
self.network = network
def construct(self, x):
predict = self.network(x)
return self.loss(predict)
class Blockcell(nn.Cell):
def __init__(self):
super(Blockcell, self).__init__()
self.bn = nn.BatchNorm2d(64, momentum=0.9)
def construct(self, x):
out = self.bn(x)
return out
def getBlock():
return Blockcell()
def test_two_bn():
class Net(nn.Cell):
def __init__(self):
super().__init__()
self.block1 = getBlock()
self.block2 = getBlock()
self.relu = P.ReLU()
self.add = P.TensorAdd()
self.bias = Tensor(np.ones([64, 64]), dtype=ms.float32)
def construct(self, x):
out = self.block1(x)
out = self.relu(out)
out = self.add(out, self.bias)
out = self.block2(out)
return out
net = NetWithLoss(Net())
x = Tensor(np.ones([64, 64]), dtype=ms.float32)
context.set_context(save_graphs=True)
context.set_auto_parallel_context(device_num=8, global_rank=0)
context.set_auto_parallel_context(parallel_mode="auto_parallel")
set_algo_parameters(elementwise_op_strategy_follow=True)
reset_op_id()
_executor.compile(net, x, phase='train')
strategies = _executor._get_strategy(net)
assert len(strategies) == 4
for (k, v) in strategies.items():
if re.search('BatchNorm-op', k) is not None:
assert v == [[8, 1], [1], [1], [1], [1]]
elif re.search('TensorAdd-op', k) is not None:
assert v == [[8, 1], [8, 1]]
elif re.search('ReLU-op', k) is not None:
assert v == [[8, 1]]
| [
"mindspore.common.api._executor._get_strategy",
"numpy.ones",
"mindspore.ops.operations.ReLU",
"mindspore.context.set_context",
"mindspore.nn.BatchNorm2d",
"mindspore.parallel.set_algo_parameters",
"tests.ut.python.ops.test_math_ops.VirtualLoss",
"mindspore.parallel._utils._reset_op_id",
"mindspore.... | [((1523, 1560), 'mindspore.context.set_context', 'context.set_context', ([], {'save_graphs': '(True)'}), '(save_graphs=True)\n', (1542, 1560), False, 'from mindspore import context\n'), ((1565, 1627), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(8)', 'global_rank': '(0)'}), '(device_num=8, global_rank=0)\n', (1598, 1627), False, 'from mindspore import context\n'), ((1632, 1696), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'parallel_mode': '"""auto_parallel"""'}), "(parallel_mode='auto_parallel')\n", (1665, 1696), False, 'from mindspore import context\n'), ((1701, 1757), 'mindspore.parallel.set_algo_parameters', 'set_algo_parameters', ([], {'elementwise_op_strategy_follow': '(True)'}), '(elementwise_op_strategy_follow=True)\n', (1720, 1757), False, 'from mindspore.parallel import set_algo_parameters\n'), ((1762, 1775), 'mindspore.parallel._utils._reset_op_id', 'reset_op_id', ([], {}), '()\n', (1773, 1775), True, 'from mindspore.parallel._utils import _reset_op_id as reset_op_id\n'), ((1781, 1821), 'mindspore.common.api._executor.compile', '_executor.compile', (['net', 'x'], {'phase': '"""train"""'}), "(net, x, phase='train')\n", (1798, 1821), False, 'from mindspore.common.api import _executor\n'), ((1839, 1867), 'mindspore.common.api._executor._get_strategy', '_executor._get_strategy', (['net'], {}), '(net)\n', (1862, 1867), False, 'from mindspore.common.api import _executor\n'), ((523, 536), 'tests.ut.python.ops.test_math_ops.VirtualLoss', 'VirtualLoss', ([], {}), '()\n', (534, 536), False, 'from tests.ut.python.ops.test_math_ops import VirtualLoss\n'), ((776, 808), 'mindspore.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(64)'], {'momentum': '(0.9)'}), '(64, momentum=0.9)\n', (790, 808), True, 'import mindspore.nn as nn\n'), ((1482, 1499), 'numpy.ones', 'np.ones', (['[64, 64]'], {}), '([64, 64])\n', (1489, 1499), True, 'import numpy as np\n'), ((1123, 1131), 'mindspore.ops.operations.ReLU', 'P.ReLU', ([], {}), '()\n', (1129, 1131), True, 'from mindspore.ops import operations as P\n'), ((1155, 1168), 'mindspore.ops.operations.TensorAdd', 'P.TensorAdd', ([], {}), '()\n', (1166, 1168), True, 'from mindspore.ops import operations as P\n'), ((1950, 1978), 're.search', 're.search', (['"""BatchNorm-op"""', 'k'], {}), "('BatchNorm-op', k)\n", (1959, 1978), False, 'import re\n'), ((1200, 1217), 'numpy.ones', 'np.ones', (['[64, 64]'], {}), '([64, 64])\n', (1207, 1217), True, 'import numpy as np\n'), ((2058, 2086), 're.search', 're.search', (['"""TensorAdd-op"""', 'k'], {}), "('TensorAdd-op', k)\n", (2067, 2086), False, 'import re\n'), ((2154, 2177), 're.search', 're.search', (['"""ReLU-op"""', 'k'], {}), "('ReLU-op', k)\n", (2163, 2177), False, 'import re\n')] |
import random
from card import Card, CardType
class Pile:
def __init__(self, cards):
self.cards = cards
def __getitem__(self, key):
return self.cards[key]
def __str__(self):
representation = f'Pile with {len(self.cards)} cards:\n'
for card in self.cards:
representation += f'{card}\n'
return representation
@staticmethod
def from_config_file(path_to_file):
new_cards = [
Card(None, CardType.WILDCARD),
Card(None, CardType.WILDCARD)
]
with open(path_to_file) as f:
card_count = int(f.readline().strip())
for _ in range(card_count):
territory = f.readline().strip()
card_type = f.readline().strip()
new_cards.append(Card(territory, CardType[card_type]))
return Pile(new_cards)
def shuffle(self):
random.shuffle(self.cards)
def remove_card(self, card):
self.cards.remove(card)
def remove_card_with_index(self, index):
self.cards.remove(self.cards[index])
def add_card(self, card):
self.cards.append(card)
def draw_card(self):
return self.cards.pop(0)
| [
"card.Card",
"random.shuffle"
] | [((916, 942), 'random.shuffle', 'random.shuffle', (['self.cards'], {}), '(self.cards)\n', (930, 942), False, 'import random\n'), ((471, 500), 'card.Card', 'Card', (['None', 'CardType.WILDCARD'], {}), '(None, CardType.WILDCARD)\n', (475, 500), False, 'from card import Card, CardType\n'), ((514, 543), 'card.Card', 'Card', (['None', 'CardType.WILDCARD'], {}), '(None, CardType.WILDCARD)\n', (518, 543), False, 'from card import Card, CardType\n'), ((815, 851), 'card.Card', 'Card', (['territory', 'CardType[card_type]'], {}), '(territory, CardType[card_type])\n', (819, 851), False, 'from card import Card, CardType\n')] |
from flask import Flask
from config import DevelopmentConfig
app = Flask(__name__)
app.config.from_object(DevelopmentConfig)
from app import routes,errors | [
"flask.Flask"
] | [((68, 83), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (73, 83), False, 'from flask import Flask\n')] |
import tensorflow as tf
import numpy as np
tf.set_random_seed(777)
data = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32)
x_data = data[:, 0:-1]
y_data = data[:, [-1]]
x = tf.placeholder(dtype=tf.float32, shape=[None, 16])
y = tf.placeholder(dtype=tf.int32, shape=[None, 1])
y_ont_hot = tf.one_hot(y, 7)
print(y_ont_hot.get_shape())
y_ont_hot = tf.reshape(y_ont_hot, [-1, 7])
print(y_ont_hot.get_shape())
w = tf.Variable(tf.random_normal([16, 7]), name='weight')
b = tf.Variable(tf.random_normal([7]), name='bias')
logit = tf.matmul(x, w) + b
hypothesis = tf.nn.softmax(logit)
cost_i = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logit, labels=y_ont_hot)
cost = tf.reduce_mean(cost_i)
train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
prediction = tf.argmax(hypothesis, axis=1)
accuracy = tf.reduce_mean(tf.cast(tf.equal(prediction, tf.argmax(y_ont_hot, axis=1)), dtype=tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(2000):
_, _cost, _a, _p = sess.run([train, cost, accuracy, prediction], feed_dict={x:x_data, y:y_data})
if step % 100 == 0:
print("step:{}\nprediction:\n{}\n\ncost:{}\naccuracy:{}".format(step, _p, _cost, _a))
_p = sess.run(prediction, feed_dict={x:x_data})
for p, y in zip(_p, y_data):
print('prediction:{} target:{}'.format(p, y)) | [
"tensorflow.one_hot",
"tensorflow.random_normal",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.global_variables_initializer",
"tensorflow.argmax",
"tensorflow.matmul",
"tensorflow.nn.s... | [((43, 66), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(777)'], {}), '(777)\n', (61, 66), True, 'import tensorflow as tf\n'), ((75, 137), 'numpy.loadtxt', 'np.loadtxt', (['"""data-04-zoo.csv"""'], {'delimiter': '""","""', 'dtype': 'np.float32'}), "('data-04-zoo.csv', delimiter=',', dtype=np.float32)\n", (85, 137), True, 'import numpy as np\n'), ((189, 239), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, 16]'}), '(dtype=tf.float32, shape=[None, 16])\n', (203, 239), True, 'import tensorflow as tf\n'), ((244, 291), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None, 1]'}), '(dtype=tf.int32, shape=[None, 1])\n', (258, 291), True, 'import tensorflow as tf\n'), ((304, 320), 'tensorflow.one_hot', 'tf.one_hot', (['y', '(7)'], {}), '(y, 7)\n', (314, 320), True, 'import tensorflow as tf\n'), ((362, 392), 'tensorflow.reshape', 'tf.reshape', (['y_ont_hot', '[-1, 7]'], {}), '(y_ont_hot, [-1, 7])\n', (372, 392), True, 'import tensorflow as tf\n'), ((575, 595), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logit'], {}), '(logit)\n', (588, 595), True, 'import tensorflow as tf\n'), ((605, 679), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'logits': 'logit', 'labels': 'y_ont_hot'}), '(logits=logit, labels=y_ont_hot)\n', (647, 679), True, 'import tensorflow as tf\n'), ((687, 709), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['cost_i'], {}), '(cost_i)\n', (701, 709), True, 'import tensorflow as tf\n'), ((801, 830), 'tensorflow.argmax', 'tf.argmax', (['hypothesis'], {'axis': '(1)'}), '(hypothesis, axis=1)\n', (810, 830), True, 'import tensorflow as tf\n'), ((439, 464), 'tensorflow.random_normal', 'tf.random_normal', (['[16, 7]'], {}), '([16, 7])\n', (455, 464), True, 'import tensorflow as tf\n'), ((497, 518), 'tensorflow.random_normal', 'tf.random_normal', (['[7]'], {}), '([7])\n', (513, 518), True, 'import tensorflow as tf\n'), ((542, 557), 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), '(x, w)\n', (551, 557), True, 'import tensorflow as tf\n'), ((942, 954), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (952, 954), True, 'import tensorflow as tf\n'), ((719, 771), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': '(0.1)'}), '(learning_rate=0.1)\n', (752, 771), True, 'import tensorflow as tf\n'), ((977, 1010), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1008, 1010), True, 'import tensorflow as tf\n'), ((886, 914), 'tensorflow.argmax', 'tf.argmax', (['y_ont_hot'], {'axis': '(1)'}), '(y_ont_hot, axis=1)\n', (895, 914), True, 'import tensorflow as tf\n')] |
# USAGE
# python dlib_face_detector.py --images dataset/gray/test/images --detector models/dlib_face_detector.svm
# import the necessary packages
from imutils import face_utils
from imutils import paths
import numpy as np
import imutils
import argparse
import imutils
import time
import dlib
import cv2
import os
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required=True,
help="path to the images")
ap.add_argument("-d", "--detector", required=True,
help="path to the face detection model")
ap.add_argument("-u", "--upsample", type=int, default=1,
help="# of upsampling times")
args = vars(ap.parse_args())
# load the face detector (HOG-SVM)
print("[INFO] loading dlib thermal face detector...")
detector = dlib.simple_object_detector(args["detector"])
# grab paths to the images
imagePaths = list(paths.list_files(args["images"]))
# loop over the images
for ind, imagePath in enumerate(imagePaths, 1):
print("[INFO] Processing image: {}/{}".format(ind, len(imagePaths)))
# load the image
image = cv2.imread(imagePath)
# resize the image
image = imutils.resize(image, width=300)
# copy the image
image_copy = image.copy()
# convert the image to grayscale
image = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
# detect faces in the image
rects = detector(image, upsample_num_times=args["upsample"])
for rect in rects:
# convert the dlib rectangle into an OpenCV bounding box and
# draw a bounding box surrounding the face
(x, y, w, h) = face_utils.rect_to_bb(rect)
cv2.rectangle(image_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
# show the image
cv2.imshow("Image", image_copy)
key = cv2.waitKey(0) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
| [
"cv2.rectangle",
"argparse.ArgumentParser",
"imutils.face_utils.rect_to_bb",
"dlib.simple_object_detector",
"cv2.imshow",
"imutils.resize",
"imutils.paths.list_files",
"cv2.waitKey",
"cv2.cvtColor",
"cv2.imread"
] | [((378, 403), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (401, 403), False, 'import argparse\n'), ((792, 837), 'dlib.simple_object_detector', 'dlib.simple_object_detector', (["args['detector']"], {}), "(args['detector'])\n", (819, 837), False, 'import dlib\n'), ((884, 916), 'imutils.paths.list_files', 'paths.list_files', (["args['images']"], {}), "(args['images'])\n", (900, 916), False, 'from imutils import paths\n'), ((1087, 1108), 'cv2.imread', 'cv2.imread', (['imagePath'], {}), '(imagePath)\n', (1097, 1108), False, 'import cv2\n'), ((1139, 1171), 'imutils.resize', 'imutils.resize', (['image'], {'width': '(300)'}), '(image, width=300)\n', (1153, 1171), False, 'import imutils\n'), ((1262, 1302), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGRA2GRAY'], {}), '(image, cv2.COLOR_BGRA2GRAY)\n', (1274, 1302), False, 'import cv2\n'), ((1660, 1691), 'cv2.imshow', 'cv2.imshow', (['"""Image"""', 'image_copy'], {}), "('Image', image_copy)\n", (1670, 1691), False, 'import cv2\n'), ((1544, 1571), 'imutils.face_utils.rect_to_bb', 'face_utils.rect_to_bb', (['rect'], {}), '(rect)\n', (1565, 1571), False, 'from imutils import face_utils\n'), ((1574, 1639), 'cv2.rectangle', 'cv2.rectangle', (['image_copy', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(2)'], {}), '(image_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)\n', (1587, 1639), False, 'import cv2\n'), ((1699, 1713), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1710, 1713), False, 'import cv2\n')] |
from inliner import inline
class SillyGetterSetter(object):
def __init__(self, stuff):
self.stuff = stuff
@inline
def setStuff(self, obj):
self.stuff = obj
@inline
def getStuff(self):
return self.stuff
@inline
def add_stuff(x, y):
return x + y
def add_lots_of_numbers():
for i in xrange(10):
add_stuff(i, i+1)
import dis
dis.dis(add_lots_of_numbers) | [
"dis.dis"
] | [((389, 417), 'dis.dis', 'dis.dis', (['add_lots_of_numbers'], {}), '(add_lots_of_numbers)\n', (396, 417), False, 'import dis\n')] |
import ctypes
class CDLL_errno(ctypes.CDLL):
class _FuncPtr(ctypes._CFuncPtr):
_flags_ = ctypes._FUNCFLAG_CDECL | ctypes._FUNCFLAG_USE_ERRNO
_restype_ = ctypes.c_int
def __call__(self, *args):
ctypes.set_errno(0)
try:
return ctypes._CFuncPtr.__call__(self, *args)
finally:
errno = ctypes.get_errno()
if errno:
import os
raise IOError(errno, os.strerror(errno))
def __init__(self, *args, **kw):
ctypes.CDLL.__init__(self, *args, **kw)
del self._FuncPtr
| [
"ctypes._CFuncPtr.__call__",
"ctypes.set_errno",
"ctypes.get_errno",
"os.strerror",
"ctypes.CDLL.__init__"
] | [((562, 601), 'ctypes.CDLL.__init__', 'ctypes.CDLL.__init__', (['self', '*args'], {}), '(self, *args, **kw)\n', (582, 601), False, 'import ctypes\n'), ((236, 255), 'ctypes.set_errno', 'ctypes.set_errno', (['(0)'], {}), '(0)\n', (252, 255), False, 'import ctypes\n'), ((296, 334), 'ctypes._CFuncPtr.__call__', 'ctypes._CFuncPtr.__call__', (['self', '*args'], {}), '(self, *args)\n', (321, 334), False, 'import ctypes\n'), ((380, 398), 'ctypes.get_errno', 'ctypes.get_errno', ([], {}), '()\n', (396, 398), False, 'import ctypes\n'), ((496, 514), 'os.strerror', 'os.strerror', (['errno'], {}), '(errno)\n', (507, 514), False, 'import os\n')] |
from cmx import doc
import gym
import numpy as np
from env_wrappers.flat_env import FlatGoalEnv
from sawyer.misc import space2dict, obs2dict
def test_start():
doc @ """
# Sawyer Blocks Environment
## To-do
- [ ] automatically generate the environment table
We include the following domains in this test:
"""
doc.csv @ """
Name, goal_keys, Action Space, Observation Space
Reach-v0, "hand"
Push-v0, "obj_0"
PushMove-v0, "hand", "obj_0"
"""
def test_reach_reward():
doc @ """
## sawyer:Reach-v0
"""
with doc:
env = gym.make("sawyer:Reach-v0")
env.seed(100)
frames = []
obs = env.reset()
for step in range(100):
# gripper dimension does not matter
act = env.goal['hand'] - obs['hand']
obs, r, done, info = env.step(np.array([*act, 0]) * 10)
img = env.render('rgb')
frames.append(img)
if done:
break
else:
raise RuntimeError("Reach failed to terminate")
doc.video(frames, f"videos/reach.gif")
doc.flush()
def test_reach_flat_goal():
doc @ """
### Using FlatGoalEnv Wrapper
"""
with doc:
env = gym.make("sawyer:Reach-v0")
env.seed(100)
env = FlatGoalEnv(env)
obs = env.reset()
with doc("Make sure that the spec agrees with what it returns"):
doc.yaml(space2dict(env.observation_space))
with doc:
doc.yaml(obs2dict(obs))
def test_push():
doc @ """
## sawyer:Push-v0
"""
with doc:
env = gym.make("sawyer:Push-v0")
env.seed(100)
obs = env.reset()
with doc("Make sure that the spec agrees with what it returns"):
doc.yaml(space2dict(env.observation_space))
with doc:
doc.yaml(obs2dict(obs))
def test_push_flat_goal():
doc @ """
### with FlatGoalEnv Wrapper
"""
with doc:
env = gym.make("sawyer:Push-v0")
env.seed(100)
env = FlatGoalEnv(env, )
obs = env.reset()
with doc("Make sure that the spec agrees with what it returns"):
doc.yaml(space2dict(env.observation_space))
with doc:
doc.yaml(obs2dict(obs))
def test_push_move():
doc @ """
## sawyer:PushMove-v0 Domain
This is different from the push domain by the
additional goal key that specifies the final
position for the hand.
"""
with doc:
env = gym.make("sawyer:PushMove-v0")
env.seed(100)
env = FlatGoalEnv(env, )
obs = env.reset()
with doc("Make sure that the spec agrees with what it returns"):
doc.yaml(space2dict(env.observation_space))
with doc:
doc.yaml(obs2dict(obs))
def test_pick_place():
doc @ """
## sawyer:PickPlace-v0 Domain
"""
with doc:
env = gym.make("sawyer:PickPlace-v0")
env.seed(100)
env = FlatGoalEnv(env, )
obs = env.reset()
with doc("Make sure that the spec agrees with what it returns"):
doc.yaml(space2dict(env.observation_space))
with doc:
doc.yaml(obs2dict(obs))
def test_pick_place_reward():
doc @ """
## sawyer:PickPlace-v0
We set the goal_key to ['hand',] (the same as the reaching
task) to test the termination.
"""
with doc:
env = gym.make("sawyer:PickPlace-v0", goal_keys=["hand"])
env.seed(100)
frames = []
obs = env.reset()
for step in range(100):
act = env.goal['hand'] - obs['hand']
obs, r, done, info = env.step(np.array([*act, 0]) * 10)
img = env.render('rgb')
frames.append(img)
if done:
break
else:
# raise RuntimeError("Reach failed to terminate")
print('failed')
pass
doc.video(frames, f"videos/pick_place.gif")
doc.flush()
def test_block_distribution():
doc @ """
Show the distribution of the block after initialization
"""
with doc:
env = gym.make("sawyer:PickPlace-v0", width=240, height=160)
env.seed(100)
frames = []
for step in range(20):
obs = env.reset()
frames.append(env.render('rgb'))
doc.image(np.min(frames, axis=0))
doc.flush()
# def test_fetch():
# with doc:
# import gym
# env = gym.make("FetchReach-v1")
#
# assert env.compute_reward is not None
| [
"env_wrappers.flat_env.FlatGoalEnv",
"cmx.doc",
"numpy.array",
"cmx.doc.video",
"sawyer.misc.space2dict",
"numpy.min",
"sawyer.misc.obs2dict",
"cmx.doc.flush",
"gym.make"
] | [((1064, 1102), 'cmx.doc.video', 'doc.video', (['frames', 'f"""videos/reach.gif"""'], {}), "(frames, f'videos/reach.gif')\n", (1073, 1102), False, 'from cmx import doc\n'), ((1107, 1118), 'cmx.doc.flush', 'doc.flush', ([], {}), '()\n', (1116, 1118), False, 'from cmx import doc\n'), ((3801, 3844), 'cmx.doc.video', 'doc.video', (['frames', 'f"""videos/pick_place.gif"""'], {}), "(frames, f'videos/pick_place.gif')\n", (3810, 3844), False, 'from cmx import doc\n'), ((3849, 3860), 'cmx.doc.flush', 'doc.flush', ([], {}), '()\n', (3858, 3860), False, 'from cmx import doc\n'), ((4231, 4242), 'cmx.doc.flush', 'doc.flush', ([], {}), '()\n', (4240, 4242), False, 'from cmx import doc\n'), ((633, 660), 'gym.make', 'gym.make', (['"""sawyer:Reach-v0"""'], {}), "('sawyer:Reach-v0')\n", (641, 660), False, 'import gym\n'), ((1233, 1260), 'gym.make', 'gym.make', (['"""sawyer:Reach-v0"""'], {}), "('sawyer:Reach-v0')\n", (1241, 1260), False, 'import gym\n'), ((1297, 1313), 'env_wrappers.flat_env.FlatGoalEnv', 'FlatGoalEnv', (['env'], {}), '(env)\n', (1308, 1313), False, 'from env_wrappers.flat_env import FlatGoalEnv\n'), ((1349, 1407), 'cmx.doc', 'doc', (['"""Make sure that the spec agrees with what it returns"""'], {}), "('Make sure that the spec agrees with what it returns')\n", (1352, 1407), False, 'from cmx import doc\n'), ((1598, 1624), 'gym.make', 'gym.make', (['"""sawyer:Push-v0"""'], {}), "('sawyer:Push-v0')\n", (1606, 1624), False, 'import gym\n'), ((1682, 1740), 'cmx.doc', 'doc', (['"""Make sure that the spec agrees with what it returns"""'], {}), "('Make sure that the spec agrees with what it returns')\n", (1685, 1740), False, 'from cmx import doc\n'), ((1953, 1979), 'gym.make', 'gym.make', (['"""sawyer:Push-v0"""'], {}), "('sawyer:Push-v0')\n", (1961, 1979), False, 'import gym\n'), ((2016, 2032), 'env_wrappers.flat_env.FlatGoalEnv', 'FlatGoalEnv', (['env'], {}), '(env)\n', (2027, 2032), False, 'from env_wrappers.flat_env import FlatGoalEnv\n'), ((2071, 2129), 'cmx.doc', 'doc', (['"""Make sure that the spec agrees with what it returns"""'], {}), "('Make sure that the spec agrees with what it returns')\n", (2074, 2129), False, 'from cmx import doc\n'), ((2468, 2498), 'gym.make', 'gym.make', (['"""sawyer:PushMove-v0"""'], {}), "('sawyer:PushMove-v0')\n", (2476, 2498), False, 'import gym\n'), ((2535, 2551), 'env_wrappers.flat_env.FlatGoalEnv', 'FlatGoalEnv', (['env'], {}), '(env)\n', (2546, 2551), False, 'from env_wrappers.flat_env import FlatGoalEnv\n'), ((2590, 2648), 'cmx.doc', 'doc', (['"""Make sure that the spec agrees with what it returns"""'], {}), "('Make sure that the spec agrees with what it returns')\n", (2593, 2648), False, 'from cmx import doc\n'), ((2863, 2894), 'gym.make', 'gym.make', (['"""sawyer:PickPlace-v0"""'], {}), "('sawyer:PickPlace-v0')\n", (2871, 2894), False, 'import gym\n'), ((2931, 2947), 'env_wrappers.flat_env.FlatGoalEnv', 'FlatGoalEnv', (['env'], {}), '(env)\n', (2942, 2947), False, 'from env_wrappers.flat_env import FlatGoalEnv\n'), ((2986, 3044), 'cmx.doc', 'doc', (['"""Make sure that the spec agrees with what it returns"""'], {}), "('Make sure that the spec agrees with what it returns')\n", (2989, 3044), False, 'from cmx import doc\n'), ((3351, 3402), 'gym.make', 'gym.make', (['"""sawyer:PickPlace-v0"""'], {'goal_keys': "['hand']"}), "('sawyer:PickPlace-v0', goal_keys=['hand'])\n", (3359, 3402), False, 'import gym\n'), ((4004, 4058), 'gym.make', 'gym.make', (['"""sawyer:PickPlace-v0"""'], {'width': '(240)', 'height': '(160)'}), "('sawyer:PickPlace-v0', width=240, height=160)\n", (4012, 4058), False, 'import gym\n'), ((4203, 4225), 'numpy.min', 'np.min', (['frames'], {'axis': '(0)'}), '(frames, axis=0)\n', (4209, 4225), True, 'import numpy as np\n'), ((1426, 1459), 'sawyer.misc.space2dict', 'space2dict', (['env.observation_space'], {}), '(env.observation_space)\n', (1436, 1459), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((1492, 1505), 'sawyer.misc.obs2dict', 'obs2dict', (['obs'], {}), '(obs)\n', (1500, 1505), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((1759, 1792), 'sawyer.misc.space2dict', 'space2dict', (['env.observation_space'], {}), '(env.observation_space)\n', (1769, 1792), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((1825, 1838), 'sawyer.misc.obs2dict', 'obs2dict', (['obs'], {}), '(obs)\n', (1833, 1838), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((2148, 2181), 'sawyer.misc.space2dict', 'space2dict', (['env.observation_space'], {}), '(env.observation_space)\n', (2158, 2181), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((2214, 2227), 'sawyer.misc.obs2dict', 'obs2dict', (['obs'], {}), '(obs)\n', (2222, 2227), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((2667, 2700), 'sawyer.misc.space2dict', 'space2dict', (['env.observation_space'], {}), '(env.observation_space)\n', (2677, 2700), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((2733, 2746), 'sawyer.misc.obs2dict', 'obs2dict', (['obs'], {}), '(obs)\n', (2741, 2746), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((3063, 3096), 'sawyer.misc.space2dict', 'space2dict', (['env.observation_space'], {}), '(env.observation_space)\n', (3073, 3096), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((3129, 3142), 'sawyer.misc.obs2dict', 'obs2dict', (['obs'], {}), '(obs)\n', (3137, 3142), False, 'from sawyer.misc import space2dict, obs2dict\n'), ((873, 892), 'numpy.array', 'np.array', (['[*act, 0]'], {}), '([*act, 0])\n', (881, 892), True, 'import numpy as np\n'), ((3571, 3590), 'numpy.array', 'np.array', (['[*act, 0]'], {}), '([*act, 0])\n', (3579, 3590), True, 'import numpy as np\n')] |
from colorhash import ColorHash
from discord import Embed, Colour
from requests import get
from ics import Calendar
import arrow
URL = "https://cloud.timeedit.net/chalmers/web/public/ri6Y73QQZ55Zn6Q14854Q8Z85640y.ics"
def get_timeline():
c = Calendar(get(URL).text)
return c.timeline
def day(offset):
"""Return the schedule for a given day"""
date = arrow.utcnow().shift(days=+offset)
date_str = date.to('local').format('dddd, D MMMM', locale="sv")
events = list(get_timeline().on(date))
if len(events) <= 0:
return (f"Det finns inget planerat för {date_str}!", [])
msg = f"\n**Schema för {date_str}:**\n"
return (msg, list(map(gen_event, events)))
def get_current():
"""Get all current events"""
events = list(get_timeline().now())
if len(events) <= 0:
return ("Just nu pågår det ingen händelse!", [])
return ("Just nu sker detta", list(map(gen_event, events)))
def get_next():
"""Get the next event"""
t = get_timeline()
now = arrow.utcnow()
try:
event = next(t.start_after(now))
except StopIteration:
return ("Det ser inte ut att finnas några kommande händelser", None)
when = event.begin.humanize(locale="sv")
return (f"Nästa händelse inträffar {when}", gen_event(event))
def gen_event(event):
"""Generate an embeded item from an event"""
# Generate start and end dates
begin = event.begin.to('local').format("HH:mm")
end = event.end.to('local').format("HH:mm")
time = f"Tid: {begin} - {end}"
title = f"{emoji(event)} **{event.name}**"
if len(title) > 210:
title = title[0:200]
desc = f"{event.description}"
# generate a color:
color = Colour.from_rgb(*ColorHash(title).rgb)
# add a location and link if there is one
location = ""
if event.location:
location = f"Plats: {event.location}\n"
link = ""
if "TMV170" in event.name:
link = "https://chalmers.zoom.us/j/65949195103"
elif "Datakommunikation" in event.name:
link = "https://chalmers.zoom.us/j/67775432479"
# create an embeded item
embed = Embed(title=title,
description=location + "\n" + desc,
url=link,
colour=color)
embed.set_footer(text=time)
return embed
def emoji(event):
if "DAT043" in event.name:
return "<:thinkingAboutJava2:800667732973453312>"
elif "TMV170" in event.name:
return "<:anvand_kompendiet:800665026981265438>"
elif "Maskinorienterad programmering" in event.name:
return "<:thinkingAboutMOP:823829306563100672>"
elif "Datatekniskt projekt" in event.name:
return "<:thinkingAboutMOP:823829306563100672>"
elif "Datakommunikation" in event.name:
return "<:HELO:823486677774237707>"
else:
return "<:rolf_poggers:794227500464209930>" | [
"arrow.utcnow",
"colorhash.ColorHash",
"discord.Embed",
"requests.get"
] | [((1018, 1032), 'arrow.utcnow', 'arrow.utcnow', ([], {}), '()\n', (1030, 1032), False, 'import arrow\n'), ((2144, 2222), 'discord.Embed', 'Embed', ([], {'title': 'title', 'description': "(location + '\\n' + desc)", 'url': 'link', 'colour': 'color'}), "(title=title, description=location + '\\n' + desc, url=link, colour=color)\n", (2149, 2222), False, 'from discord import Embed, Colour\n'), ((258, 266), 'requests.get', 'get', (['URL'], {}), '(URL)\n', (261, 266), False, 'from requests import get\n'), ((370, 384), 'arrow.utcnow', 'arrow.utcnow', ([], {}), '()\n', (382, 384), False, 'import arrow\n'), ((1738, 1754), 'colorhash.ColorHash', 'ColorHash', (['title'], {}), '(title)\n', (1747, 1754), False, 'from colorhash import ColorHash\n')] |
import numpy as np
import pandas as pa
import time
from sklearn.metrics import pairwise_distances
from scipy.sparse import csr_matrix
class Kmeans:
def __init__(self,data,k,geneNames,cellNames,cluster_label=None,seed=None):
self.data=data
self.k=k
self.geneNames=geneNames
self.cellNames=cellNames
self.seed=seed
self.centroids=None
self.cluster_assignment=None
self.cluster_label=cluster_label
self.heterogeneity=0.0
self.get_initial_centroids()
self.heterogeneities=None
def getCentroids(self):
return self.centroids
def getCluster_assignment(self):
return self.cluster_assignment
def getHeterogenity(self):
return self.heterogeneity
def getHetrogenities(self):
return self.heterogeneities
def get_initial_centroids(self):
'''Randomly choose k data points as initial centroids'''
if self.seed is not None: # useful for obtaining consistent results
np.random.seed(self.seed)
n = self.data.shape[0] # number of data points
# Pick K indices from range [0, N).
rand_indices = np.random.randint(0, n, self.k)
# Keep centroids as dense format, as many entries will be nonzero due to averaging.
# As long as at least one document in a cluster contains a word,
# it will carry a nonzero weight in the TF-IDF vector of the centroid.
centroids = self.data[rand_indices,:].toarray()
self.centroids=centroids
return centroids
def smart_initialize(self):
'''Use k-means++ to initialize a good set of centroids'''
if self.seed is not None: # useful for obtaining consistent results
np.random.seed(self.seed)
centroids = np.zeros((self.k, self.data.shape[1]))
# Randomly choose the first centroid.
# Since we have no prior knowledge, choose uniformly at random
idx = np.random.randint(self.data.shape[0])
centroids[0] = self.data[idx,:].toarray()
# Compute distances from the first centroid chosen to all the other data points
squared_distances = pairwise_distances(self.data, centroids[0:1], metric='euclidean').flatten()**2
for i in range(1, self.k):
# Choose the next centroid randomly, so that the probability for each data point to be chosen
# is directly proportional to its squared distance from the nearest centroid.
# Roughtly speaking, a new centroid should be as far as from ohter centroids as possible.
idx = np.random.choice(self.data.shape[0], 1, p=squared_distances/sum(squared_distances))
centroids[i] = self.data[idx,:].toarray()
# Now compute distances from the centroids to all data points
squared_distances = np.min(pairwise_distances(self.data, centroids[0:i+1], metric='euclidean')**2,axis=1)
self.centroids=centroids
return centroids
def assign_clusters(self):
# Compute distances between each data point and the set of centroids:
# Fill in the blank (RHS only)
distances_from_centroids = pairwise_distances(self.data,self.centroids,metric='euclidean')
# Compute cluster assignments for each data point:
# Fill in the blank (RHS only)
cluster_assignment = np.apply_along_axis(np.argmin, 1, distances_from_centroids)
self.cluster_assignment=cluster_assignment
return cluster_assignment
def revise_centroids(self):
new_centroids = []
for i in range(self.k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = self.data[self.cluster_assignment==i]
# Compute the mean of the data points. Fill in the blank (RHS only)
centroid = member_data_points.mean(axis=0)
# Convert numpy.matrix type to numpy.ndarray type
centroid = centroid.A1
new_centroids.append(centroid)
new_centroids = np.array(new_centroids)
self.centroids=new_centroids
return new_centroids
def kmeans(self, maxiter, record_heterogeneity=None, verbose=False):
'''This function runs k-means on given data and initial set of centroids.
maxiter: maximum number of iterations to run.
record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations
if None, do not store the history.
verbose: if True, print how many data points changed their cluster labels in each iteration'''
centroids = self.centroids[:]
prev_cluster_assignment = None
for itr in range(int(maxiter)):
if verbose:
print(itr)
# 1. Make cluster assignments using nearest centroids
# YOUR CODE HERE
cluster_assignment = self.assign_clusters()
# 2. Compute a new centroid for each of the k clusters, averaging all data points assigned to that cluster.
# YOUR CODE HERE
centroids = self.revise_centroids()
# Check for convergence: if none of the assignments changed, stop
if prev_cluster_assignment is not None and \
(prev_cluster_assignment==self.cluster_assignment).all():
break
# Print number of new assignments
if prev_cluster_assignment is not None:
num_changed = np.sum(prev_cluster_assignment!=self.cluster_assignment)
if verbose:
print(' {0:5d} elements changed their cluster assignment.'.format(num_changed))
# Record heterogeneity convergence metric
if record_heterogeneity is not None:
# YOUR CODE HERE
score = compute_heterogeneity(self.data, self.k, centroids, cluster_assignment)
record_heterogeneity.append(score)
prev_cluster_assignment = cluster_assignment[:]
self.centroids=centroids
self.cluster_assignment=cluster_assignment
return centroids, cluster_assignment
def kmeans_multiple_runs(self, maxiter, num_runs, seed_list=None, verbose=False):
heterogeneity = {}
min_heterogeneity_achieved = float('inf')
best_seed = None
final_centroids = None
final_cluster_assignment = None
for i in range(num_runs):
# Use UTC time if no seeds are provided
if seed_list is not None:
seed = seed_list[i]
np.random.seed(seed)
else:
seed = int(time.time())
np.random.seed(seed)
# Use k-means++ initialization
self.initial_centroids = self.smart_initialize()
# Run k-means
centroids, cluster_assignment = self.kmeans(maxiter, record_heterogeneity=None, verbose=False)
# To save time, compute heterogeneity only once in the end
heterogeneity[seed] = self.compute_heterogeneity()
if verbose:
print('seed={0:06d}, heterogeneity={1:.5f}'.format(seed, heterogeneity[seed]))
sys.stdout.flush()
# if current measurement of heterogeneity is lower than previously seen,
# update the minimum record of heterogeneity.
if heterogeneity[seed] < min_heterogeneity_achieved:
min_heterogeneity_achieved = heterogeneity[seed]
best_seed = seed
final_centroids = centroids
final_cluster_assignment = cluster_assignment
self.centroids=final_centroids
self.cluster_assignment=final_cluster_assignment
self.heterogeneities=heterogeneity
return final_centroids, final_cluster_assignment
def clusterEvaluation(self):
clustMaxDist={}
clustMinDist={}
clustMeanDist={}
for i in range(self.k):
binMaxDist=[]
binMinDist=[]
binMeanDist=[]
for j in np.concatenate(np.argwhere(self.cluster_assignment==i)):
dist=pairwise_distances(self.data[np.concatenate(np.argwhere(self.cluster_assignment==i))], self.data[j], metric='euclidean').flatten()
dist=dist**2
binMaxDist.append(np.max(dist))
binMinDist.append(np.min(dist))
binMeanDist.append(np.mean(dist))
clustMaxDist[i]=np.max(binMaxDist)
clustMinDist[i]=np.min(binMinDist)
clustMeanDist[i]=np.mean(binMeanDist)
plt.figure(figsize=(7,4.5))
plt.plot(clustMaxDist.keys(),clustMaxDist.values(), linewidth=2, label='Maximum distance among clusters')
plt.plot(clustMaxDist.keys(),clustMinDist.values(), linewidth=2, label='Minimum distance among clusters')
plt.plot(clustMaxDist.keys(),clustMeanDist.values(), linewidth=2, label='avarage distance among clusters')
plt.xlabel('Cluster number')
plt.ylabel('Eculidean distance')
plt.legend(loc='best', prop={'size':15})
plt.rcParams.update({'font.size':16})
plt.tight_layout()
plt.show()
return np.sum(clustMeanDist)
def compute_heterogeneity(self):
heterogeneity = 0.0
for i in range(self.k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = self.data[self.cluster_assignment==i, :]
if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty
# Compute distances from centroid to data points (RHS only)
distances = pairwise_distances(member_data_points, [self.centroids[i]], metric='euclidean')
squared_distances = distances**2
heterogeneity += np.sum(squared_distances)
self.heterogeneity=heterogeneity
return heterogeneity
def plot_k_vs_heterogeneity(self, k_values, heterogeneity_values):
plt.figure(figsize=(7,4))
plt.plot(k_values, heterogeneity_values, linewidth=4)
plt.xlabel('K')
plt.ylabel('Heterogeneity')
plt.title('K vs. Heterogeneity')
plt.rcParams.update({'font.size': 16})
plt.tight_layout()
plt.show()
return None
def get_cluster_data(self, cluster_number):
return self.data[np.in1d(np.array(self.cluster_assignment), cluster_number),:], self.cellNames[np.in1d(np.array(self.cluster_assignment), cluster_number)]
def select_K(self):
cluster_centroids={}
cluster_assignments={}
hetroginity_score=float('inf')
delta_k={}
max_K_value=self.k
hetro_Per_K={}
deltaHetro=None
for i in range(max_K_value):
self.k=i+1
print("going for k=", i+1)
cluster_centroid, cluster_assignment=self.kmeans_multiple_runs(5,100)
hetro=self.compute_heterogeneity()
hetro_Per_K[i+1]=hetro
if hetro<hetroginity_score:
if hetroginity_score==float('inf'):
hetroginity_score=hetro
deltaHetro=0
else:
deltaHetro=hetroginity_score-hetro
hetroginity_score=hetro
cluster_centroids[i+1]=cluster_centroid
cluster_assignments[i+1]=cluster_assignment
delta_k[i+1]=deltaHetro
best_k=sum(delta_k.values()[1:]>sum(delta_k.values())/(2*len(delta_k.values())))
print("best k value:", best_k, delta_k)
self.centroids=cluster_centroids[best_k]
self.cluster_assignment=cluster_assignments[best_k]
self.k=best_k
self.getVisualization(method="tsne")
self.plot_k_vs_heterogeneity(hetro_Per_K.keys(), hetro_Per_K.values())
return self.k
| [
"numpy.mean",
"sklearn.metrics.pairwise_distances",
"numpy.max",
"numpy.array",
"numpy.random.randint",
"numpy.apply_along_axis",
"numpy.zeros",
"numpy.sum",
"numpy.random.seed",
"numpy.min",
"numpy.argwhere",
"time.time"
] | [((1207, 1238), 'numpy.random.randint', 'np.random.randint', (['(0)', 'n', 'self.k'], {}), '(0, n, self.k)\n', (1224, 1238), True, 'import numpy as np\n'), ((1839, 1877), 'numpy.zeros', 'np.zeros', (['(self.k, self.data.shape[1])'], {}), '((self.k, self.data.shape[1]))\n', (1847, 1877), True, 'import numpy as np\n'), ((2009, 2046), 'numpy.random.randint', 'np.random.randint', (['self.data.shape[0]'], {}), '(self.data.shape[0])\n', (2026, 2046), True, 'import numpy as np\n'), ((3228, 3293), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['self.data', 'self.centroids'], {'metric': '"""euclidean"""'}), "(self.data, self.centroids, metric='euclidean')\n", (3246, 3293), False, 'from sklearn.metrics import pairwise_distances\n'), ((3424, 3483), 'numpy.apply_along_axis', 'np.apply_along_axis', (['np.argmin', '(1)', 'distances_from_centroids'], {}), '(np.argmin, 1, distances_from_centroids)\n', (3443, 3483), True, 'import numpy as np\n'), ((4145, 4168), 'numpy.array', 'np.array', (['new_centroids'], {}), '(new_centroids)\n', (4153, 4168), True, 'import numpy as np\n'), ((9452, 9473), 'numpy.sum', 'np.sum', (['clustMeanDist'], {}), '(clustMeanDist)\n', (9458, 9473), True, 'import numpy as np\n'), ((1050, 1075), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (1064, 1075), True, 'import numpy as np\n'), ((1793, 1818), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (1807, 1818), True, 'import numpy as np\n'), ((8723, 8741), 'numpy.max', 'np.max', (['binMaxDist'], {}), '(binMaxDist)\n', (8729, 8741), True, 'import numpy as np\n'), ((8770, 8788), 'numpy.min', 'np.min', (['binMinDist'], {}), '(binMinDist)\n', (8776, 8788), True, 'import numpy as np\n'), ((8818, 8838), 'numpy.mean', 'np.mean', (['binMeanDist'], {}), '(binMeanDist)\n', (8825, 8838), True, 'import numpy as np\n'), ((5623, 5681), 'numpy.sum', 'np.sum', (['(prev_cluster_assignment != self.cluster_assignment)'], {}), '(prev_cluster_assignment != self.cluster_assignment)\n', (5629, 5681), True, 'import numpy as np\n'), ((6751, 6771), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (6765, 6771), True, 'import numpy as np\n'), ((6847, 6867), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (6861, 6867), True, 'import numpy as np\n'), ((8326, 8367), 'numpy.argwhere', 'np.argwhere', (['(self.cluster_assignment == i)'], {}), '(self.cluster_assignment == i)\n', (8337, 8367), True, 'import numpy as np\n'), ((9937, 10016), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['member_data_points', '[self.centroids[i]]'], {'metric': '"""euclidean"""'}), "(member_data_points, [self.centroids[i]], metric='euclidean')\n", (9955, 10016), False, 'from sklearn.metrics import pairwise_distances\n'), ((10099, 10124), 'numpy.sum', 'np.sum', (['squared_distances'], {}), '(squared_distances)\n', (10105, 10124), True, 'import numpy as np\n'), ((2213, 2278), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['self.data', 'centroids[0:1]'], {'metric': '"""euclidean"""'}), "(self.data, centroids[0:1], metric='euclidean')\n", (2231, 2278), False, 'from sklearn.metrics import pairwise_distances\n'), ((2894, 2963), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['self.data', 'centroids[0:i + 1]'], {'metric': '"""euclidean"""'}), "(self.data, centroids[0:i + 1], metric='euclidean')\n", (2912, 2963), False, 'from sklearn.metrics import pairwise_distances\n'), ((6818, 6829), 'time.time', 'time.time', ([], {}), '()\n', (6827, 6829), False, 'import time\n'), ((8583, 8595), 'numpy.max', 'np.max', (['dist'], {}), '(dist)\n', (8589, 8595), True, 'import numpy as np\n'), ((8631, 8643), 'numpy.min', 'np.min', (['dist'], {}), '(dist)\n', (8637, 8643), True, 'import numpy as np\n'), ((8680, 8693), 'numpy.mean', 'np.mean', (['dist'], {}), '(dist)\n', (8687, 8693), True, 'import numpy as np\n'), ((10744, 10777), 'numpy.array', 'np.array', (['self.cluster_assignment'], {}), '(self.cluster_assignment)\n', (10752, 10777), True, 'import numpy as np\n'), ((10666, 10699), 'numpy.array', 'np.array', (['self.cluster_assignment'], {}), '(self.cluster_assignment)\n', (10674, 10699), True, 'import numpy as np\n'), ((8433, 8474), 'numpy.argwhere', 'np.argwhere', (['(self.cluster_assignment == i)'], {}), '(self.cluster_assignment == i)\n', (8444, 8474), True, 'import numpy as np\n')] |
from django.db import models
from sessions_coding.models import Classroom_session,Subject,Axis,Skill,Learning_goal,Copus_code
DIALOGIC_CHOICES = (
('Autoritativo', 'Autoritativo'),
('Dialogico', 'Dialógico'),
('NA', 'NA'),
)
class Discourse_form(models.Model):
session = models.ForeignKey(Classroom_session, on_delete=models.CASCADE,default=1)
init_line = models.IntegerField(default=0)
end_line = models.IntegerField(default=0)
artificial_name = models.CharField(max_length=100)
text = models.TextField()
def __str__(self):
return str(self.pk)+'-'+self.artificial_name
class Form_answer(models.Model):
form = models.ForeignKey(Discourse_form, on_delete=models.CASCADE)
ans_date = models.DateTimeField('date answered',auto_now_add=True, blank=True)
user = models.EmailField()
dialogic = models.CharField(blank=True,default='NA',max_length=40)
done = models.BooleanField(blank=True,default=False)
def __str__(self):
label_id = str(self.form.pk)+'-'+self.form.artificial_name
return label_id+'-'+str(self.ans_date)
class Answered_subject(models.Model):
subject = models.ForeignKey(Subject,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
def __str__(self):
return str(self.subject)
class Answered_axis(models.Model):
axis = models.ForeignKey(Axis,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
def __str__(self):
return str(self.axis)
class Answered_skill(models.Model):
skill = models.ForeignKey(Skill,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
def __str__(self):
return str(self.skill)
class Answered_learning_goal(models.Model):
goal = models.ForeignKey(Learning_goal,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
def __str__(self):
return str(self.goal)
class Answered_copus_code(models.Model):
copus_code = models.ForeignKey(Copus_code,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
def __str__(self):
return str(self.copus_code)
class Answered_axis_phrases(models.Model):
axis = models.ForeignKey(Answered_axis,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
phrases = models.TextField()
def __str__(self):
return str(self.axis)
class Answered_skill_phrases(models.Model):
skill = models.ForeignKey(Answered_skill,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
code = models.IntegerField(default=0,blank=True)
phrases = models.TextField()
def __str__(self):
return str(self.skill)
class Answered_dialogic_phrases(models.Model):
dialogic = models.CharField(max_length=20,choices=DIALOGIC_CHOICES)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
code = models.IntegerField(default=0,blank=True)
phrases = models.TextField()
def __str__(self):
return str(self.dialogic)
class Answered_copus_phrases(models.Model):
copus = models.ForeignKey(Answered_copus_code,on_delete=models.CASCADE)
ans_form = models.ForeignKey(Form_answer, on_delete=models.CASCADE)
code = models.IntegerField(default=0,blank=True)
phrases = models.TextField()
def __str__(self):
return str(self.copus)
| [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((289, 362), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Classroom_session'], {'on_delete': 'models.CASCADE', 'default': '(1)'}), '(Classroom_session, on_delete=models.CASCADE, default=1)\n', (306, 362), False, 'from django.db import models\n'), ((378, 408), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (397, 408), False, 'from django.db import models\n'), ((424, 454), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (443, 454), False, 'from django.db import models\n'), ((477, 509), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (493, 509), False, 'from django.db import models\n'), ((521, 539), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (537, 539), False, 'from django.db import models\n'), ((661, 720), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Discourse_form'], {'on_delete': 'models.CASCADE'}), '(Discourse_form, on_delete=models.CASCADE)\n', (678, 720), False, 'from django.db import models\n'), ((736, 804), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""date answered"""'], {'auto_now_add': '(True)', 'blank': '(True)'}), "('date answered', auto_now_add=True, blank=True)\n", (756, 804), False, 'from django.db import models\n'), ((815, 834), 'django.db.models.EmailField', 'models.EmailField', ([], {}), '()\n', (832, 834), False, 'from django.db import models\n'), ((850, 907), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'default': '"""NA"""', 'max_length': '(40)'}), "(blank=True, default='NA', max_length=40)\n", (866, 907), False, 'from django.db import models\n'), ((917, 963), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'blank': '(True)', 'default': '(False)'}), '(blank=True, default=False)\n', (936, 963), False, 'from django.db import models\n'), ((1153, 1205), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Subject'], {'on_delete': 'models.CASCADE'}), '(Subject, on_delete=models.CASCADE)\n', (1170, 1205), False, 'from django.db import models\n'), ((1220, 1276), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (1237, 1276), False, 'from django.db import models\n'), ((1380, 1429), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Axis'], {'on_delete': 'models.CASCADE'}), '(Axis, on_delete=models.CASCADE)\n', (1397, 1429), False, 'from django.db import models\n'), ((1444, 1500), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (1461, 1500), False, 'from django.db import models\n'), ((1603, 1653), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Skill'], {'on_delete': 'models.CASCADE'}), '(Skill, on_delete=models.CASCADE)\n', (1620, 1653), False, 'from django.db import models\n'), ((1668, 1724), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (1685, 1724), False, 'from django.db import models\n'), ((1835, 1893), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Learning_goal'], {'on_delete': 'models.CASCADE'}), '(Learning_goal, on_delete=models.CASCADE)\n', (1852, 1893), False, 'from django.db import models\n'), ((1908, 1964), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (1925, 1964), False, 'from django.db import models\n'), ((2077, 2132), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Copus_code'], {'on_delete': 'models.CASCADE'}), '(Copus_code, on_delete=models.CASCADE)\n', (2094, 2132), False, 'from django.db import models\n'), ((2147, 2203), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (2164, 2203), False, 'from django.db import models\n'), ((2318, 2376), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Answered_axis'], {'on_delete': 'models.CASCADE'}), '(Answered_axis, on_delete=models.CASCADE)\n', (2335, 2376), False, 'from django.db import models\n'), ((2391, 2447), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (2408, 2447), False, 'from django.db import models\n'), ((2462, 2480), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (2478, 2480), False, 'from django.db import models\n'), ((2591, 2650), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Answered_skill'], {'on_delete': 'models.CASCADE'}), '(Answered_skill, on_delete=models.CASCADE)\n', (2608, 2650), False, 'from django.db import models\n'), ((2665, 2721), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (2682, 2721), False, 'from django.db import models\n'), ((2733, 2775), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'blank': '(True)'}), '(default=0, blank=True)\n', (2752, 2775), False, 'from django.db import models\n'), ((2789, 2807), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (2805, 2807), False, 'from django.db import models\n'), ((2925, 2982), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)', 'choices': 'DIALOGIC_CHOICES'}), '(max_length=20, choices=DIALOGIC_CHOICES)\n', (2941, 2982), False, 'from django.db import models\n'), ((2997, 3053), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (3014, 3053), False, 'from django.db import models\n'), ((3065, 3107), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'blank': '(True)'}), '(default=0, blank=True)\n', (3084, 3107), False, 'from django.db import models\n'), ((3121, 3139), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (3137, 3139), False, 'from django.db import models\n'), ((3254, 3318), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Answered_copus_code'], {'on_delete': 'models.CASCADE'}), '(Answered_copus_code, on_delete=models.CASCADE)\n', (3271, 3318), False, 'from django.db import models\n'), ((3333, 3389), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Form_answer'], {'on_delete': 'models.CASCADE'}), '(Form_answer, on_delete=models.CASCADE)\n', (3350, 3389), False, 'from django.db import models\n'), ((3401, 3443), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'blank': '(True)'}), '(default=0, blank=True)\n', (3420, 3443), False, 'from django.db import models\n'), ((3457, 3475), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (3473, 3475), False, 'from django.db import models\n')] |
import FWCore.ParameterSet.Config as cms
allSuperClusterCandidates = cms.EDProducer("ConcreteEcalCandidateProducer",
src = cms.InputTag("hybridSuperClusters"),
particleType = cms.string('gamma')
)
| [
"FWCore.ParameterSet.Config.string",
"FWCore.ParameterSet.Config.InputTag"
] | [((128, 163), 'FWCore.ParameterSet.Config.InputTag', 'cms.InputTag', (['"""hybridSuperClusters"""'], {}), "('hybridSuperClusters')\n", (140, 163), True, 'import FWCore.ParameterSet.Config as cms\n'), ((184, 203), 'FWCore.ParameterSet.Config.string', 'cms.string', (['"""gamma"""'], {}), "('gamma')\n", (194, 203), True, 'import FWCore.ParameterSet.Config as cms\n')] |
#!/usr/bin/python
# coding:utf-8
import sys
sys.path.append('./libs')
import RPi.GPIO as GPIO
from time import sleep
#from libs import snapshot as snap
import snapshot as snap
#from libs import aws_iot_pub as iot
import aws_iot_pub as iot
import commands
#import system
#from subprocess import check_call
import ConfigParser
#設定ファイルの読み込み
inifile = ConfigParser.SafeConfigParser()
inifile.read('conf/config.ini')
bucket = inifile.get('main', 's3bucket')
domain = inifile.get('main', 's3domain')
def cencer_callback(ch):
print('hi')
print(ch)
path = snap.capture_camera()
print(path)
#s3にアップロードするコマンド
#os.system('aws s3 cp ' + path + ' s3://' + bucket + ' --acl public-read')
cmd = 'aws s3 cp ' + path + ' s3://' + bucket + ' --acl public-read'
print(cmd)
#check_call([cmd])
commands.getoutput(cmd)
arr = path.split('/')
size = len(arr)
url = 'https://' + domain + '/' + bucket + '/' + arr[size -1]
print(url)
iot.publish(url)
pin = 10
#GPIO.setmode(GPIO.BCM)
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)
GPIO.add_event_detect(pin, GPIO.RISING, callback=cencer_callback, bouncetime=1000)
try:
while True:
# if GPIO.input(pin) == GPIO.HIGH:
# print("1:not obstacled")
# else:
# print("0:obstacled")
sleep(0.5)
except:
pass
GPIO.cleanup(pin)
| [
"RPi.GPIO.cleanup",
"commands.getoutput",
"RPi.GPIO.add_event_detect",
"ConfigParser.SafeConfigParser",
"aws_iot_pub.publish",
"RPi.GPIO.setup",
"time.sleep",
"snapshot.capture_camera",
"sys.path.append",
"RPi.GPIO.setmode"
] | [((45, 70), 'sys.path.append', 'sys.path.append', (['"""./libs"""'], {}), "('./libs')\n", (60, 70), False, 'import sys\n'), ((352, 383), 'ConfigParser.SafeConfigParser', 'ConfigParser.SafeConfigParser', ([], {}), '()\n', (381, 383), False, 'import ConfigParser\n'), ((1032, 1054), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (1044, 1054), True, 'import RPi.GPIO as GPIO\n'), ((1055, 1079), 'RPi.GPIO.setup', 'GPIO.setup', (['pin', 'GPIO.IN'], {}), '(pin, GPIO.IN)\n', (1065, 1079), True, 'import RPi.GPIO as GPIO\n'), ((1081, 1167), 'RPi.GPIO.add_event_detect', 'GPIO.add_event_detect', (['pin', 'GPIO.RISING'], {'callback': 'cencer_callback', 'bouncetime': '(1000)'}), '(pin, GPIO.RISING, callback=cencer_callback,\n bouncetime=1000)\n', (1102, 1167), True, 'import RPi.GPIO as GPIO\n'), ((1352, 1369), 'RPi.GPIO.cleanup', 'GPIO.cleanup', (['pin'], {}), '(pin)\n', (1364, 1369), True, 'import RPi.GPIO as GPIO\n'), ((566, 587), 'snapshot.capture_camera', 'snap.capture_camera', ([], {}), '()\n', (585, 587), True, 'import snapshot as snap\n'), ((824, 847), 'commands.getoutput', 'commands.getoutput', (['cmd'], {}), '(cmd)\n', (842, 847), False, 'import commands\n'), ((980, 996), 'aws_iot_pub.publish', 'iot.publish', (['url'], {}), '(url)\n', (991, 996), True, 'import aws_iot_pub as iot\n'), ((1323, 1333), 'time.sleep', 'sleep', (['(0.5)'], {}), '(0.5)\n', (1328, 1333), False, 'from time import sleep\n')] |
#!/usr/bin/env python
import glob
import logging
import os
import sys
from msspec.calculator import MSSPEC
from msspec.utils import get_atom_index
from msspec.utils import hemispherical_cluster
from msspec.utils import SPRKKRPotential
from ase2sprkkr.sprkkr.calculator import SPRKKR
from ase.build import bulk
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Create a copper cell
Cu = bulk('Cu')
# ########## SPRKKR part
if 'sprkkr' in sys.argv:
# create a SPRKKR calculator
calc = SPRKKR(atoms=Cu,mpi=['mpirun','-np','16'])
# Here is how to modify input file
# launch kkrscf
calc.input_parameters.set(NL=3)
calc.input_parameters.SCF.MIX=0.20
calc.input_parameters.ENERGY.ImE=0.0
calc.input_parameters.ENERGY.GRID=[5,3]
calc.input_parameters.set(NE=32)
out_scf=calc.calculate()
#
# EXPORT POTENTIAL FOR PHAGEN
#
#change task and command
calc.input_parameters='PHAGEN'
# calc.input_parameters.set(NL=3)
calc.input_parameters.SCF.MIX=0.20
calc.input_parameters.ENERGY.ImE=0.0
calc.input_parameters.ENERGY.GRID=[5,3]
calc.input_parameters.set(NE=32)
calc.calculate(potential=out_scf.potential_filename)
# ######### MsSpec part
if 'msspec' in sys.argv:
pot = SPRKKRPotential(Cu, "Cu_scf.pot_new", *glob.glob("*PHAGEN.pot"))
nplanes = 3
cluster = hemispherical_cluster(Cu, planes=nplanes,
emitter_plane=nplanes-1)
cluster.absorber = get_atom_index(cluster, 0, 0, 0)
calc = MSSPEC(folder="calc")
calc.set_atoms(cluster)
calc.tmatrix_parameters.potential = pot
data = calc.get_theta_scan(level='2p3/2')
data.view()
if len(sys.argv) <= 1:
print("Please specify either 'sprkkr', 'msspec' keywords or both "
"of them on the command line")
| [
"logging.basicConfig",
"logging.getLogger",
"msspec.calculator.MSSPEC",
"ase2sprkkr.sprkkr.calculator.SPRKKR",
"msspec.utils.get_atom_index",
"msspec.utils.hemispherical_cluster",
"ase.build.bulk",
"glob.glob"
] | [((314, 354), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (333, 354), False, 'import logging\n'), ((364, 391), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (381, 391), False, 'import logging\n'), ((421, 431), 'ase.build.bulk', 'bulk', (['"""Cu"""'], {}), "('Cu')\n", (425, 431), False, 'from ase.build import bulk\n'), ((527, 572), 'ase2sprkkr.sprkkr.calculator.SPRKKR', 'SPRKKR', ([], {'atoms': 'Cu', 'mpi': "['mpirun', '-np', '16']"}), "(atoms=Cu, mpi=['mpirun', '-np', '16'])\n", (533, 572), False, 'from ase2sprkkr.sprkkr.calculator import SPRKKR\n'), ((1384, 1452), 'msspec.utils.hemispherical_cluster', 'hemispherical_cluster', (['Cu'], {'planes': 'nplanes', 'emitter_plane': '(nplanes - 1)'}), '(Cu, planes=nplanes, emitter_plane=nplanes - 1)\n', (1405, 1452), False, 'from msspec.utils import hemispherical_cluster\n'), ((1510, 1542), 'msspec.utils.get_atom_index', 'get_atom_index', (['cluster', '(0)', '(0)', '(0)'], {}), '(cluster, 0, 0, 0)\n', (1524, 1542), False, 'from msspec.utils import get_atom_index\n'), ((1555, 1576), 'msspec.calculator.MSSPEC', 'MSSPEC', ([], {'folder': '"""calc"""'}), "(folder='calc')\n", (1561, 1576), False, 'from msspec.calculator import MSSPEC\n'), ((1327, 1351), 'glob.glob', 'glob.glob', (['"""*PHAGEN.pot"""'], {}), "('*PHAGEN.pot')\n", (1336, 1351), False, 'import glob\n')] |
# -*- coding: utf-8 -*-
from dd_invitation import models
from django.contrib import admin
class TokenAdmin(admin.ModelAdmin):
list_display = ('value', 'consumed', 'created')
ordering = ('-created',)
class Media:
js = ('dd_invitation.js',)
admin.site.register(models.Token, TokenAdmin)
| [
"django.contrib.admin.site.register"
] | [((255, 300), 'django.contrib.admin.site.register', 'admin.site.register', (['models.Token', 'TokenAdmin'], {}), '(models.Token, TokenAdmin)\n', (274, 300), False, 'from django.contrib import admin\n')] |
from __future__ import absolute_import
from pyti import catch_errors
from pyti.exponential_moving_average import (
exponential_moving_average as ema
)
def double_exponential_moving_average(data, period):
"""
Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA)
"""
catch_errors.check_for_period_error(data, period)
dema = (2 * ema(data, period)) - ema(ema(data, period), period)
return dema
| [
"pyti.catch_errors.check_for_period_error",
"pyti.exponential_moving_average.exponential_moving_average"
] | [((315, 364), 'pyti.catch_errors.check_for_period_error', 'catch_errors.check_for_period_error', (['data', 'period'], {}), '(data, period)\n', (350, 364), False, 'from pyti import catch_errors\n'), ((382, 399), 'pyti.exponential_moving_average.exponential_moving_average', 'ema', (['data', 'period'], {}), '(data, period)\n', (385, 399), True, 'from pyti.exponential_moving_average import exponential_moving_average as ema\n'), ((407, 424), 'pyti.exponential_moving_average.exponential_moving_average', 'ema', (['data', 'period'], {}), '(data, period)\n', (410, 424), True, 'from pyti.exponential_moving_average import exponential_moving_average as ema\n')] |
import importlib
import os
from PyQt5.QtCore import QSettings
class Continue(BaseException):
pass
class PluginLoader:
loadedPlugins = []
loaded = False
settings = QSettings("plugins.ini", QSettings.IniFormat)
@staticmethod
def getLoadedPlugins():
"""
This returns instances for all PluginImpl's from
core.plugins.load
:return: [] of plugins
"""
if not PluginLoader.loaded:
for plugin in os.listdir("plugins/."):
if not plugin.endswith("_plugin"):
continue
mod = importlib.import_module("plugins." + plugin + ".PluginImpl")
if hasattr(mod, "PluginImpl"):
instance = getattr(mod, "PluginImpl")()
instance.nativeName = plugin
instance.settings = PluginLoader.settings
PluginLoader.loadedPlugins.append(instance)
PluginLoader.loaded = True
return PluginLoader.loadedPlugins
@classmethod
def reloadPlugins(cls):
print("Reloading plugins...")
PluginLoader.loadedPlugins = []
PluginLoader.loaded = False
PluginLoader.getLoadedPlugins() | [
"os.listdir",
"PyQt5.QtCore.QSettings",
"importlib.import_module"
] | [((185, 230), 'PyQt5.QtCore.QSettings', 'QSettings', (['"""plugins.ini"""', 'QSettings.IniFormat'], {}), "('plugins.ini', QSettings.IniFormat)\n", (194, 230), False, 'from PyQt5.QtCore import QSettings\n'), ((481, 504), 'os.listdir', 'os.listdir', (['"""plugins/."""'], {}), "('plugins/.')\n", (491, 504), False, 'import os\n'), ((610, 670), 'importlib.import_module', 'importlib.import_module', (["('plugins.' + plugin + '.PluginImpl')"], {}), "('plugins.' + plugin + '.PluginImpl')\n", (633, 670), False, 'import importlib\n')] |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""A More Flexible Video models."""
import math
import torch
import torch.nn as nn
from .build import MODEL_REGISTRY
from .monet import Monet
@MODEL_REGISTRY.register()
class Linear(nn.Module):
"""
Simple linear Neural Network for testing
"""
def __init__(self, cfg):
"""
The `__init__` method of any subclass should also contain these
arguments.
Args:
cfg (CfgNode): model building configs, details are in the
comments of the config file.
"""
super(Linear, self).__init__()
num_classes=cfg.MODEL.NUM_CLASSES
self.lin = nn.Linear(224*224*3, num_classes) #Requires TRAIN_CROP_SIZE: 224 TEST_CROP_SIZE: 224
def forward(self, x):
x = torch.flatten(x[0], start_dim=1)
return self.lin(x)
# License: MIT
# Author: <NAME>
from collections import namedtuple
config_options = [
# Training config
#'vis_every', # Visualize progress every X iterations
#'batch_size',
#'num_epochs',
#'load_parameters', # Load parameters from checkpoint
#'checkpoint_file', # File for loading/storing checkpoints
#'data_dir', # Directory for the training data
#'parallel', # Train using nn.DataParallel
# Model config
'num_slots', # Number of slots k,
'num_blocks', # Number of blochs in attention U-Net
'channel_base', # Number of channels used for the first U-Net conv layer
'bg_sigma', # Sigma of the decoder distributions for the first slot
'fg_sigma', # Sigma of the decoder distributions for all other slots
]
MonetConfig = namedtuple('MonetConfig', config_options)
@MODEL_REGISTRY.register()
class MonetModel(Monet):
"""
Class used as an interface from PySlowFast with a MONet implementation in monet.py
"""
def __init__(self, cfg):
"""
The `__init__` method of any subclass should also contain these
arguments.
Args:
cfg (CfgNode): model building configs, details are in the
comments of the config file.
"""
clevr_conf = MonetConfig(num_slots=cfg.MONET.NUM_SLOTS,
num_blocks=6,
channel_base=64,
bg_sigma=0.09,
fg_sigma=0.11,
)
height = cfg.DATA.RESIZE_H
width = cfg.DATA.RESIZE_W
super(MonetModel, self).__init__(clevr_conf, height, width) | [
"collections.namedtuple",
"torch.nn.Linear",
"torch.flatten"
] | [((1708, 1749), 'collections.namedtuple', 'namedtuple', (['"""MonetConfig"""', 'config_options'], {}), "('MonetConfig', config_options)\n", (1718, 1749), False, 'from collections import namedtuple\n'), ((736, 773), 'torch.nn.Linear', 'nn.Linear', (['(224 * 224 * 3)', 'num_classes'], {}), '(224 * 224 * 3, num_classes)\n', (745, 773), True, 'import torch.nn as nn\n'), ((860, 892), 'torch.flatten', 'torch.flatten', (['x[0]'], {'start_dim': '(1)'}), '(x[0], start_dim=1)\n', (873, 892), False, 'import torch\n')] |
import collections
import requests
from sentinels import NOTHING
from ._compat import xrange, iteritems
class LazyQuery(object):
def __init__(self, client, path=None, url=None, query_params=None, page_size=100):
super(LazyQuery, self).__init__()
self._client = client
if url is None:
url = client.api.url
if path is not None:
url = url.add_path(path)
if query_params is not None:
for (param, value) in query_params.items():
url = url.add_query_param(param, str(value))
self._url = url
self._fetched = collections.defaultdict(lambda: NOTHING)
self._total_num_objects = None
self._page_size = page_size
def filter(self, *filter_objects, **fields):
returned_url = self._url
for filter_object in filter_objects:
returned_url = filter_object.add_to_url(returned_url)
for field_name, field_value in iteritems(fields):
returned_url = returned_url.add_query_param(field_name, str(field_value))
return LazyQuery(self._client, url=returned_url, page_size=self._page_size)
def __repr__(self):
return '<Query {0!r}>'.format(str(self._url))
def __iter__(self):
for i in xrange(len(self)):
yield self._fetch_index(i)
def __len__(self):
if self._total_num_objects is None:
self._fetch_page(1)
return self._total_num_objects
def __getitem__(self, idx):
if isinstance(idx, slice):
raise NotImplementedError() # pragma: no cover
if idx < 0:
if idx < -len(self):
raise IndexError()
idx = len(self) + idx
return self._fetch_index(idx)
def _fetch_index(self, index):
returned = self._fetched[index]
if returned is NOTHING:
page_index = (index // self._page_size) + 1
self._fetch_page(page_index)
returned = self._fetched[index]
assert returned is not NOTHING
return returned
def _fetch_page(self, page_index):
assert page_index != 0
response = requests.get(self._url.add_query_param(
'page', str(page_index)).add_query_param('page_size', str(self._page_size)))
response.raise_for_status()
response_data = response.json()
if self._total_num_objects is None:
self._total_num_objects = response_data[
'metadata']['total_num_objects']
for index, json_obj in enumerate(response_data['result']):
real_index = ((page_index - 1) * self._page_size) + index
self._fetched[real_index] = self._client.api.build_api_object(json_obj)
return response_data
| [
"collections.defaultdict"
] | [((618, 659), 'collections.defaultdict', 'collections.defaultdict', (['(lambda : NOTHING)'], {}), '(lambda : NOTHING)\n', (641, 659), False, 'import collections\n')] |
import importlib.util
import logging
import logging.config
import os
import typing as t
from pathlib import Path
import yaml
import xleapp.globals as g
from ..helpers.utils import generate_program_header
StrPath = t.Union[str, os.PathLike[str]]
class ProcessFileFilter(logging.Filter):
def filter(self, record):
return record.name == "xleapp.process" and record.levelno >= 20
class InfoLogFileFilter(logging.Filter):
def filter(self, record):
return record.name == "xleapp.logfile" and record.levelno >= 20
class DebugFileFilter(logging.Filter):
def filter(self, record):
return g.app.debug
class StreamHandler(logging.StreamHandler):
def emit(self, record: logging.LogRecord):
if record.msg.startswith("->"):
record.msg = f" {record.msg}"
logging.StreamHandler.emit(self, record)
class FileHandler(logging.FileHandler):
def __init__(
self,
filename: StrPath,
mode: str = "a",
encoding: t.Union[str, None] = None,
delay: bool = False,
errors: t.Union[str, None] = None,
) -> None:
super().__init__(
filename,
mode=mode,
encoding=encoding,
delay=delay,
errors=errors,
)
def emit(self, record: logging.LogRecord):
if record.msg.startswith("->"):
record.msg = f" {record.msg}"
logging.FileHandler.emit(self, record)
class FileHandlerWithHeader(logging.FileHandler):
def __init__(self, filename, header, mode="a", encoding=None, delay=0):
self.header = header
self.file_pre_exists = Path(filename)
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
if not delay and self.stream is not None:
self.stream.write("%s\n" % header)
def emit(self, record: logging.LogRecord):
if self.stream is None:
self.stream = self._open()
if not self.file_pre_exists:
self.stream.write("%s\n" % self.header)
message = record.msg
if message.startswith("->"):
message = f" {message}"
record.msg = message
logging.FileHandler.emit(self, record)
def init() -> None:
mod = importlib.util.find_spec(__name__)
if not mod:
raise FileNotFoundError("Missing package 'log_config.yaml' to configure logging!")
if mod.origin:
logConfig = Path(mod.origin).parent / "log_config.yaml"
with open(logConfig, "r") as file:
config = yaml.safe_load(file.read())
if not g.app.log_folder.exists():
g.app.log_folder.mkdir(parents=True, exist_ok=True)
info_log_file = config["handlers"]["info_file_handler"]["filename"]
config["handlers"]["info_file_handler"]["filename"] = (
g.app.log_folder / info_log_file
)
config["handlers"]["info_file_handler"]["header"] = generate_program_header(
project_version=f"{g.app.project} v{g.app.version}",
input_path=g.app.input_path,
output_path=g.app.output_path,
num_to_process=g.app.num_to_process,
num_of_categories=g.app.num_of_categories,
)
process_log_file = config["handlers"]["process_file_handler"]["filename"]
config["handlers"]["process_file_handler"]["filename"] = (
g.app.log_folder / process_log_file
)
debug_log_file = config["handlers"]["debug_file_handler"]["filename"]
config["handlers"]["debug_file_handler"]["filename"] = (
g.app.log_folder / debug_log_file
)
logging.config.dictConfig(config)
else:
raise FileNotFoundError(
"Package found! Missing 'log_config.yaml' to "
"configure logging! Reinstall package.",
)
| [
"logging.StreamHandler.emit",
"pathlib.Path",
"logging.config.dictConfig",
"logging.FileHandler.__init__",
"xleapp.globals.app.log_folder.exists",
"logging.FileHandler.emit",
"xleapp.globals.app.log_folder.mkdir"
] | [((825, 865), 'logging.StreamHandler.emit', 'logging.StreamHandler.emit', (['self', 'record'], {}), '(self, record)\n', (851, 865), False, 'import logging\n'), ((1429, 1467), 'logging.FileHandler.emit', 'logging.FileHandler.emit', (['self', 'record'], {}), '(self, record)\n', (1453, 1467), False, 'import logging\n'), ((1656, 1670), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (1660, 1670), False, 'from pathlib import Path\n'), ((1679, 1746), 'logging.FileHandler.__init__', 'logging.FileHandler.__init__', (['self', 'filename', 'mode', 'encoding', 'delay'], {}), '(self, filename, mode, encoding, delay)\n', (1707, 1746), False, 'import logging\n'), ((2203, 2241), 'logging.FileHandler.emit', 'logging.FileHandler.emit', (['self', 'record'], {}), '(self, record)\n', (2227, 2241), False, 'import logging\n'), ((3661, 3694), 'logging.config.dictConfig', 'logging.config.dictConfig', (['config'], {}), '(config)\n', (3686, 3694), False, 'import logging\n'), ((2609, 2634), 'xleapp.globals.app.log_folder.exists', 'g.app.log_folder.exists', ([], {}), '()\n', (2632, 2634), True, 'import xleapp.globals as g\n'), ((2648, 2699), 'xleapp.globals.app.log_folder.mkdir', 'g.app.log_folder.mkdir', ([], {'parents': '(True)', 'exist_ok': '(True)'}), '(parents=True, exist_ok=True)\n', (2670, 2699), True, 'import xleapp.globals as g\n'), ((2457, 2473), 'pathlib.Path', 'Path', (['mod.origin'], {}), '(mod.origin)\n', (2461, 2473), False, 'from pathlib import Path\n')] |
from pydantic import Field
from pystratis.api import Model
from pystratis.core.types import uint256
# noinspection PyUnresolvedReferences
class ScheduleVoteWhitelistHashRequest(Model):
"""A request model for the voting/schedulevote-whitelist endpoint.
Args:
hash_id (uint256): The hash to whitelist.
"""
hash_id: uint256 = Field(alias='hash')
| [
"pydantic.Field"
] | [((350, 369), 'pydantic.Field', 'Field', ([], {'alias': '"""hash"""'}), "(alias='hash')\n", (355, 369), False, 'from pydantic import Field\n')] |
address_coordinate_cache = {}
def calculate_distance_address_store(address, store):
address_latitude, address_longitude = get_coordinates_for_address(address)
return calculate_distance_between_coordinates(address_latitude, address_longitude, store.latitude, store.longitude)
def calculate_distance_between_coordinates(latitude1, longitude1, latitude2, longitude2):
from math import sin, cos, sqrt, atan2, radians
# approximate radius of earth in km
R = 6373.0
lat1 = radians(float(latitude1))
lon1 = radians(float(longitude1))
lat2 = radians(float(latitude2))
lon2 = radians(float(longitude2))
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
return distance
def get_coordinates_for_address(address):
import json
import urllib3
http = urllib3.PoolManager()
# Cache the coordinates
if address not in address_coordinate_cache:
r = http.request('GET',
f"https://nominatim.openstreetmap.org/search/{address}?format=json")
location_data = json.loads(r.data)
address_coordinate_cache[address] = (location_data[0]["lat"], location_data[0]["lon"])
return address_coordinate_cache[address]
| [
"json.loads",
"math.sqrt",
"math.cos",
"urllib3.PoolManager",
"math.sin"
] | [((924, 945), 'urllib3.PoolManager', 'urllib3.PoolManager', ([], {}), '()\n', (943, 945), False, 'import urllib3\n'), ((1173, 1191), 'json.loads', 'json.loads', (['r.data'], {}), '(r.data)\n', (1183, 1191), False, 'import json\n'), ((689, 702), 'math.sin', 'sin', (['(dlat / 2)'], {}), '(dlat / 2)\n', (692, 702), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((771, 778), 'math.sqrt', 'sqrt', (['a'], {}), '(a)\n', (775, 778), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((780, 791), 'math.sqrt', 'sqrt', (['(1 - a)'], {}), '(1 - a)\n', (784, 791), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((710, 719), 'math.cos', 'cos', (['lat1'], {}), '(lat1)\n', (713, 719), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((722, 731), 'math.cos', 'cos', (['lat2'], {}), '(lat2)\n', (725, 731), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((734, 747), 'math.sin', 'sin', (['(dlon / 2)'], {}), '(dlon / 2)\n', (737, 747), False, 'from math import sin, cos, sqrt, atan2, radians\n')] |
import os
import logging
from pathlib import Path
import pandas as pd
from simsi_transfer.merging_functions import merge_with_msmsscanstxt, merge_with_summarytxt, merge_with_msmstxt
logger = logging.getLogger(__name__)
def export_annotated_clusters(annotated_clusters, mainpath, pval):
export_csv(annotated_clusters, 'annotated_clusters', mainpath, pval)
def export_msmsscans(msmsscans_simsi, mainpath, pval):
export_csv(msmsscans_simsi, 'msmsScans', mainpath, pval, sort_columns=['Raw file', 'scanID'])
def export_msms(msms_simsi, mainpath, pval):
export_csv(msms_simsi, 'msms', mainpath, pval, sort_columns=['Sequence', 'Modified sequence'])
def export_csv(df: pd.DataFrame, filename: str, mainpath, pval, sort_columns=None):
sumpath = mainpath / Path('summaries')
if not os.path.exists(sumpath):
os.makedirs(sumpath)
pval_path = sumpath / Path(pval)
if not os.path.exists(pval_path):
os.makedirs(pval_path)
if sort_columns:
df.sort_values(by=sort_columns)
path = pval_path / Path(f'{pval}_{filename}.txt')
df.to_csv(path, sep='\t', index=False, na_rep='NaN')
def export_simsi_evidence_file(evidence_file, mainpath, pval):
sumpath = mainpath / Path('summaries')
pval_path = sumpath / Path(pval)
evidence_file.to_csv(pval_path / Path(f'{pval}_evidence.txt'), sep='\t', index=False, na_rep='NaN')
def count_clustering_parameters(summary, rawtrans=False):
"""
Counts MICs, tIDs, dIDs, optionally IDs with lost phospho location, and clusters. Requires flagged MICs and tIDs.
MICs = multiply identified clusters, i.e. ambiguous clusters with multiple peptide sequence
tIDs = transferred identifications (by SIMSI-Transfer)
dIDs = direct identifications (by MaxQuant)
:param summary: summary_extended input dataframe
:param rawtrans: Flag for added lost phospho localization counting
:return: Dictionary of counted values
"""
ids = len(summary)
dids = len(summary[summary['identification'] == 'd'])
tids = len(summary[summary['identification'] == 't'])
lostphos = None
if rawtrans:
lostphos = len(
summary[
(summary['identification'] == 't') & (summary['Modified sequence'] != summary['Modified sequence'])])
totclus = max(summary['clusterID'])
mulclus = max(summary[summary['clusterID'].duplicated(keep=False)]['clusterID'])
pho_mics = summary[summary['mod_ambiguous'] == 1]['clusterID'].nunique(dropna=True)
raw_mics = summary[summary['raw_ambiguous'] == 1]['clusterID'].nunique(dropna=True)
logger.info(f'Identified spectra: {str(ids)}')
logger.info(f'- MaxQuant IDs: {str(dids)}')
logger.info(f'- SIMSI IDs: {str(tids)}')
if rawtrans:
logger.info(f' - PTM-Isomeric: {str(lostphos)}')
logger.info(f'Clusters: {str(totclus)}')
logger.info(f'- size > 1: {str(mulclus)}')
logger.info(f'- PTM-isomeric: {str(pho_mics)}')
logger.info(f'- Ambiguous: {str(raw_mics)}')
if rawtrans:
return {'scans': ids, 'dids': dids, 'tids': tids, 'lostphos': lostphos, 'totclus': totclus,
'mulclus': mulclus, 'pho_mics': pho_mics, 'raw_mics': raw_mics}
else:
return {'scans': ids, 'dids': dids, 'tids': tids, 'totclus': totclus, 'mulclus': mulclus,
'pho_mics': pho_mics, 'raw_mics': raw_mics}
def remove_unidentified_scans(summary):
summary = summary.loc[~summary['identification'].isna()]
summary.insert(0, 'summary_ID', range(len(summary)))
return summary
def annotate_clusters(msmsscansdf, msmsdf, rawfile_metadata, clusterfile):
"""
Merges msmsscans.txt, msms.txt, and MaRaCluster clusters to generate summary file
:param msmsscansdf:
:param msmsdf:
:param rawfile_metadata:
:param clusterfile:
:return:
"""
summary = merge_with_msmsscanstxt(clusterfile, msmsscansdf)
summary = merge_with_summarytxt(summary, rawfile_metadata)
summary = merge_with_msmstxt(summary, msmsdf)
return summary
if __name__ == '__main__':
raise NotImplementedError('Do not run this script.')
| [
"logging.getLogger",
"os.path.exists",
"os.makedirs",
"pathlib.Path",
"simsi_transfer.merging_functions.merge_with_msmstxt",
"simsi_transfer.merging_functions.merge_with_msmsscanstxt",
"simsi_transfer.merging_functions.merge_with_summarytxt"
] | [((194, 221), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (211, 221), False, 'import logging\n'), ((3872, 3921), 'simsi_transfer.merging_functions.merge_with_msmsscanstxt', 'merge_with_msmsscanstxt', (['clusterfile', 'msmsscansdf'], {}), '(clusterfile, msmsscansdf)\n', (3895, 3921), False, 'from simsi_transfer.merging_functions import merge_with_msmsscanstxt, merge_with_summarytxt, merge_with_msmstxt\n'), ((3936, 3984), 'simsi_transfer.merging_functions.merge_with_summarytxt', 'merge_with_summarytxt', (['summary', 'rawfile_metadata'], {}), '(summary, rawfile_metadata)\n', (3957, 3984), False, 'from simsi_transfer.merging_functions import merge_with_msmsscanstxt, merge_with_summarytxt, merge_with_msmstxt\n'), ((3999, 4034), 'simsi_transfer.merging_functions.merge_with_msmstxt', 'merge_with_msmstxt', (['summary', 'msmsdf'], {}), '(summary, msmsdf)\n', (4017, 4034), False, 'from simsi_transfer.merging_functions import merge_with_msmsscanstxt, merge_with_summarytxt, merge_with_msmstxt\n'), ((776, 793), 'pathlib.Path', 'Path', (['"""summaries"""'], {}), "('summaries')\n", (780, 793), False, 'from pathlib import Path\n'), ((805, 828), 'os.path.exists', 'os.path.exists', (['sumpath'], {}), '(sumpath)\n', (819, 828), False, 'import os\n'), ((838, 858), 'os.makedirs', 'os.makedirs', (['sumpath'], {}), '(sumpath)\n', (849, 858), False, 'import os\n'), ((885, 895), 'pathlib.Path', 'Path', (['pval'], {}), '(pval)\n', (889, 895), False, 'from pathlib import Path\n'), ((907, 932), 'os.path.exists', 'os.path.exists', (['pval_path'], {}), '(pval_path)\n', (921, 932), False, 'import os\n'), ((942, 964), 'os.makedirs', 'os.makedirs', (['pval_path'], {}), '(pval_path)\n', (953, 964), False, 'import os\n'), ((1049, 1079), 'pathlib.Path', 'Path', (['f"""{pval}_{filename}.txt"""'], {}), "(f'{pval}_{filename}.txt')\n", (1053, 1079), False, 'from pathlib import Path\n'), ((1227, 1244), 'pathlib.Path', 'Path', (['"""summaries"""'], {}), "('summaries')\n", (1231, 1244), False, 'from pathlib import Path\n'), ((1271, 1281), 'pathlib.Path', 'Path', (['pval'], {}), '(pval)\n', (1275, 1281), False, 'from pathlib import Path\n'), ((1319, 1347), 'pathlib.Path', 'Path', (['f"""{pval}_evidence.txt"""'], {}), "(f'{pval}_evidence.txt')\n", (1323, 1347), False, 'from pathlib import Path\n')] |
from django.conf import settings
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny
from inquest.users.models import User
from inquest.users.permissions import IsUserOrReadOnly
from inquest.users.serializers import CreateUserSerializer, UserSerializer
class UserViewSet(
mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet
):
""" Updates and retrieves user accounts. """
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsUserOrReadOnly,)
@method_decorator(cache_page(settings.CACHE_TTL))
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
class UserCreateViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
""" Creates user accounts. """
queryset = User.objects.all()
serializer_class = CreateUserSerializer
permission_classes = (AllowAny,)
| [
"django.views.decorators.cache.cache_page",
"inquest.users.models.User.objects.all"
] | [((569, 587), 'inquest.users.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (585, 587), False, 'from inquest.users.models import User\n'), ((944, 962), 'inquest.users.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (960, 962), False, 'from inquest.users.models import User\n'), ((694, 724), 'django.views.decorators.cache.cache_page', 'cache_page', (['settings.CACHE_TTL'], {}), '(settings.CACHE_TTL)\n', (704, 724), False, 'from django.views.decorators.cache import cache_page\n')] |
from collections import namedtuple
from re import compile
from sys import exit as sysexit
from typing import List
from util import read_input
DAY = 10
UPPER_LIMIT = 25000
Point = namedtuple("Point", ["x", "y"])
Star = namedtuple("Star", ["position", "velocity"])
line_re = compile(r"position=<(?P<x>[-\s\d]+),(?P<y>[-\s\d]+)> velocity=<(?P<vx>[-\s\d]+),(?P<vy>[-\s\d]+)>")
def to_star(line: str) -> Star:
def to_int(s: str) -> int:
return int(s.replace(" ", ""))
match = line_re.match(line.rstrip())
if not match:
raise ValueError(f"Unable to Parse Line: {line.rstrip()}")
sysexit(1)
groups = match.groupdict()
velocity = Point(to_int(groups["vx"]), to_int(groups["vy"]))
x, y = to_int(groups["x"]), to_int(groups["y"])
return Star(Point(x, y), velocity)
def position(star: Star, time: int = 0) -> Point:
x = star.position.x + (star.velocity.x * (time + 1))
y = star.position.y + (star.velocity.y * (time + 1))
return Point(x, y)
def calculate_area(points: List[Point]) -> int:
max_x = max([point.x for point in points])
min_x = min([point.x for point in points])
max_y = max([point.x for point in points])
min_y = min([point.x for point in points])
return (max_x - min_x) * (max_y - min_y)
def print_points(points: List[Point]):
max_x = max([point.x for point in points])
min_x = min([point.x for point in points])
max_y = max([point.y for point in points])
min_y = min([point.y for point in points])
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
if len([p for p in points if p.x == x and p.y == y]) > 0:
print("X", end="")
else:
print(" ", end="")
print("")
def main():
stars = [to_star(line) for line in read_input(DAY)]
min_t: int = None
min_area: int = None
for t in range(0, UPPER_LIMIT):
points = [position(star, t) for star in stars]
area = calculate_area(points)
if not min_area or area < min_area:
min_area = area
min_t = t
print_points([position(star, min_t) for star in stars])
if __name__ == "__main__":
main()
| [
"util.read_input",
"collections.namedtuple",
"sys.exit",
"re.compile"
] | [((181, 212), 'collections.namedtuple', 'namedtuple', (['"""Point"""', "['x', 'y']"], {}), "('Point', ['x', 'y'])\n", (191, 212), False, 'from collections import namedtuple\n'), ((220, 264), 'collections.namedtuple', 'namedtuple', (['"""Star"""', "['position', 'velocity']"], {}), "('Star', ['position', 'velocity'])\n", (230, 264), False, 'from collections import namedtuple\n'), ((275, 391), 're.compile', 'compile', (['"""position=<(?P<x>[-\\\\s\\\\d]+),(?P<y>[-\\\\s\\\\d]+)> velocity=<(?P<vx>[-\\\\s\\\\d]+),(?P<vy>[-\\\\s\\\\d]+)>"""'], {}), "(\n 'position=<(?P<x>[-\\\\s\\\\d]+),(?P<y>[-\\\\s\\\\d]+)> velocity=<(?P<vx>[-\\\\s\\\\d]+),(?P<vy>[-\\\\s\\\\d]+)>'\n )\n", (282, 391), False, 'from re import compile\n'), ((614, 624), 'sys.exit', 'sysexit', (['(1)'], {}), '(1)\n', (621, 624), True, 'from sys import exit as sysexit\n'), ((1824, 1839), 'util.read_input', 'read_input', (['DAY'], {}), '(DAY)\n', (1834, 1839), False, 'from util import read_input\n')] |
import csv
from django.contrib.auth.models import User
from jcourse_api.models import Course, Review, FormerCode, Semester
f = open('./data/2021_wenjuan.csv', mode='r', encoding='utf-8-sig')
csv_reader = csv.DictReader(f)
q = []
users = User.objects.filter(username__istartswith='工具人')
for row in csv_reader:
try:
code, course_name, teacher = row['课程'].split(' ')
# print(code, course_name, teahcer)
try:
codes = [code]
try:
former_code = FormerCode.objects.get(old_code=code).new_code
codes.append(former_code)
except FormerCode.DoesNotExist:
pass
course = Course.objects.get(code__in=codes, main_teacher__name=teacher)
has_reviewed = Review.objects.filter(course=course, user__in=users).exists()
if not has_reviewed:
q.append((course, row))
print(course)
except Course.DoesNotExist:
print("未查到:", code, course_name, teacher)
except ValueError:
# print(row['课程'])
pass
i = 1
while len(q) > 0:
new_q = []
user, _ = User.objects.get_or_create(username=f"工具人{i}号")
for course, row in q:
if Review.objects.filter(course=course, user=user).exists():
new_q.append((course, row))
continue
year = int(row['学期'][0:4])
term = row['学期'][-1]
if term == '春':
semester = Semester.objects.get(name=f'{year - 1}-{year}-2')
elif term == '夏':
semester = Semester.objects.get(name=f'{year - 1}-{year}-3')
else:
semester = Semester.objects.get(name=f'{year}-{year + 1}-1')
comment = f"课程内容:{row['课程内容']}\n上课自由度:{row['课程自由度']}\n考核标准:{row['考核标准']}\n教师:{row['教师']}"
rating = int(row['安利程度']) // 2
review = Review(course=course, user=user, comment=comment, rating=rating, semester=semester, score=row['成绩'])
review.save()
# print(review)
q = new_q
i = i + 1
| [
"django.contrib.auth.models.User.objects.get_or_create",
"csv.DictReader",
"jcourse_api.models.Semester.objects.get",
"jcourse_api.models.Course.objects.get",
"jcourse_api.models.Review.objects.filter",
"jcourse_api.models.FormerCode.objects.get",
"django.contrib.auth.models.User.objects.filter",
"jco... | [((207, 224), 'csv.DictReader', 'csv.DictReader', (['f'], {}), '(f)\n', (221, 224), False, 'import csv\n'), ((240, 288), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', ([], {'username__istartswith': '"""工具人"""'}), "(username__istartswith='工具人')\n", (259, 288), False, 'from django.contrib.auth.models import User\n'), ((1146, 1193), 'django.contrib.auth.models.User.objects.get_or_create', 'User.objects.get_or_create', ([], {'username': 'f"""工具人{i}号"""'}), "(username=f'工具人{i}号')\n", (1172, 1193), False, 'from django.contrib.auth.models import User\n'), ((1851, 1956), 'jcourse_api.models.Review', 'Review', ([], {'course': 'course', 'user': 'user', 'comment': 'comment', 'rating': 'rating', 'semester': 'semester', 'score': "row['成绩']"}), "(course=course, user=user, comment=comment, rating=rating, semester=\n semester, score=row['成绩'])\n", (1857, 1956), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n'), ((685, 747), 'jcourse_api.models.Course.objects.get', 'Course.objects.get', ([], {'code__in': 'codes', 'main_teacher__name': 'teacher'}), '(code__in=codes, main_teacher__name=teacher)\n', (703, 747), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n'), ((1461, 1510), 'jcourse_api.models.Semester.objects.get', 'Semester.objects.get', ([], {'name': 'f"""{year - 1}-{year}-2"""'}), "(name=f'{year - 1}-{year}-2')\n", (1481, 1510), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n'), ((1231, 1278), 'jcourse_api.models.Review.objects.filter', 'Review.objects.filter', ([], {'course': 'course', 'user': 'user'}), '(course=course, user=user)\n', (1252, 1278), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n'), ((1560, 1609), 'jcourse_api.models.Semester.objects.get', 'Semester.objects.get', ([], {'name': 'f"""{year - 1}-{year}-3"""'}), "(name=f'{year - 1}-{year}-3')\n", (1580, 1609), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n'), ((1647, 1696), 'jcourse_api.models.Semester.objects.get', 'Semester.objects.get', ([], {'name': 'f"""{year}-{year + 1}-1"""'}), "(name=f'{year}-{year + 1}-1')\n", (1667, 1696), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n'), ((510, 547), 'jcourse_api.models.FormerCode.objects.get', 'FormerCode.objects.get', ([], {'old_code': 'code'}), '(old_code=code)\n', (532, 547), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n'), ((775, 827), 'jcourse_api.models.Review.objects.filter', 'Review.objects.filter', ([], {'course': 'course', 'user__in': 'users'}), '(course=course, user__in=users)\n', (796, 827), False, 'from jcourse_api.models import Course, Review, FormerCode, Semester\n')] |
from flask import Flask, render_template, request
from keras.preprocessing.image import img_to_array, load_img
from keras.models import load_model
import cv2
import os
import numpy as np
from flask_cors import CORS, cross_origin
import tensorflow.keras
from PIL import Image, ImageOps
import base64
import json
import dlib
import imutils
from imutils import face_utils
handLabels = ["Stretched", "NotStretched"]
faceLabels = ["MildPain", "NoPain"]
facialLabels = ["No Face Droop", "Face Droop"]
model_face = tensorflow.keras.models.load_model('keras_face_model.h5')
model_hand = tensorflow.keras.models.load_model('keras_hand_model.h5')
model_facial_path = tensorflow.keras.models.load_model('Model.h5')
# Process image and predict label
def processImgFacial(IMG_PATH):
global shape
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
image = cv2.imread(IMG_PATH)
image = imutils.resize(image, width=500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
coord = []
print(rects)
if len(rects) > 0:
for (i, rect) in enumerate(rects):
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
i = 0
for (x, y) in shape:
if i > 36:
coord.append(x)
coord.append(y)
i += 1
t2 = np.array([coord])
normalized_image_array = (t2.astype(np.float32) / 127.0) - 1
model_facial_path.load_weights('weight.h5')
prediction = model_facial_path.predict(normalized_image_array)
print("pred", prediction)
lastfacialLabel = facialLabels[np.argmax(np.squeeze(prediction[0]))]
print(lastfacialLabel)
confidence = np.max(np.squeeze(prediction))
writeList = [str(confidence), lastfacialLabel]
with open('facialdroop.txt', 'w') as filehandle:
json.dump(writeList, filehandle)
return lastfacialLabel
# Process image and predict label
def processImgFace(IMG_PATH):
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
# determined by the first position in the shape tuple, in this case 1.
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
image = Image.open(IMG_PATH)
# resize the image to a 224x224 with the same strategy as in TM2:
# resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.ANTIALIAS)
# turn the image into a numpy array
image_array = np.asarray(image)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
data[0] = normalized_image_array
# run the inference
prediction = model_face.predict(data)
print(prediction)
lastpainLabel = faceLabels[np.argmax(np.squeeze(prediction))]
confidence = np.max(np.squeeze(prediction))
writeList = [str(confidence), lastpainLabel]
with open('face.txt', 'w') as filehandle:
json.dump(writeList, filehandle)
return lastpainLabel
# Process image and predict label
def processImgHand(IMG_PATH):
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
# Load the model
# determined by the first position in the shape tuple, in this case 1.
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
image = Image.open(IMG_PATH)
# resize the image to a 224x224 with the same strategy as in TM2:
# resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.ANTIALIAS)
# turn the image into a numpy array
image_array = np.asarray(image)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
data[0] = normalized_image_array
# run the inference
prediction = model_hand.predict(data)
lasthandLabel = handLabels[np.argmax(np.squeeze(prediction))]
confidence = np.max(np.squeeze(prediction))
writeList = [str(confidence), lasthandLabel]
with open('hand.txt', 'w') as filehandle:
json.dump(writeList, filehandle)
return lasthandLabel
# Initializing flask application
app = Flask(__name__)
cors = CORS(app)
@app.route("/")
def main():
return """
Application is working
"""
# About page with render template
@app.route("/about")
def postsPage():
return render_template("about.html")
@app.route("/analysisreport", methods=["POST"])
def resultPage():
# open output file for reading
with open('face.txt', 'r') as filehandle:
faceResult = json.load(filehandle)
# open output file for reading
with open('hand.txt', 'r') as filehandle:
handResult = json.load(filehandle)
with open('facialdroop.txt', 'r') as filehandle:
FacialDroop = json.load(filehandle)
dictRecult = {}
dictRecult["hand_lbl"] = handResult[1]
dictRecult["face_lbl"] = faceResult[1]
dictRecult["facial_lbl"] = FacialDroop[1]
dictRecult["hand_acc"] = str(round(float(handResult[0]) * 100, 2))
dictRecult["face_acc"] = str(round(float(faceResult[0]) * 100, 2))
dictRecult["facial_acc"] = str(round(float(FacialDroop[0]) * 100, 2))
app_json = json.dumps(dictRecult)
return app_json
@app.route("/processfacial", methods=["POST"])
def processReqFacial():
if request.user_agent.browser is None:
data = request.files["img"]
data.save("temp.jpg")
else:
data = request.form["photo"]
data = data.split(",")[1]
buff = np.fromstring(base64.b64decode(data), np.uint8)
data = cv2.imdecode(buff, cv2.IMREAD_COLOR)
im = Image.fromarray(data)
im.save("temp.jpg")
resp = processImgFacial("temp.jpg")
return resp
@app.route("/processface", methods=["POST"])
def processReqFace():
if request.user_agent.browser is None:
data = request.files["img"]
data.save("temp.jpg")
else:
data = request.form["photo"]
data = data.split(",")[1]
buff = np.fromstring(base64.b64decode(data), np.uint8)
data = cv2.imdecode(buff, cv2.IMREAD_COLOR)
im = Image.fromarray(data)
im.save("temp.jpg")
resp = processImgFace("temp.jpg")
return resp
@app.route("/processhand", methods=["POST"])
def processReqHand():
if request.user_agent.browser is None:
data = request.files["img"]
data.save("temp.jpg")
else:
data = request.form["photo"]
data = data.split(",")[1]
buff = np.fromstring(base64.b64decode(data), np.uint8)
data = cv2.imdecode(buff, cv2.IMREAD_COLOR)
im = Image.fromarray(data)
im.save("temp.jpg")
resp = processImgHand("temp.jpg")
return resp
if __name__ == "__main__":
app.run(debug=True)
| [
"flask.render_template",
"flask_cors.CORS",
"flask.Flask",
"PIL.ImageOps.fit",
"numpy.array",
"cv2.imdecode",
"json.dumps",
"numpy.asarray",
"dlib.shape_predictor",
"dlib.get_frontal_face_detector",
"numpy.squeeze",
"cv2.cvtColor",
"imutils.face_utils.shape_to_np",
"cv2.imread",
"numpy.s... | [((4465, 4480), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (4470, 4480), False, 'from flask import Flask, render_template, request\n'), ((4488, 4497), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (4492, 4497), False, 'from flask_cors import CORS, cross_origin\n'), ((807, 839), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (837, 839), False, 'import dlib\n'), ((856, 917), 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""shape_predictor_68_face_landmarks.dat"""'], {}), "('shape_predictor_68_face_landmarks.dat')\n", (876, 917), False, 'import dlib\n'), ((931, 951), 'cv2.imread', 'cv2.imread', (['IMG_PATH'], {}), '(IMG_PATH)\n', (941, 951), False, 'import cv2\n'), ((964, 996), 'imutils.resize', 'imutils.resize', (['image'], {'width': '(500)'}), '(image, width=500)\n', (978, 996), False, 'import imutils\n'), ((1008, 1047), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (1020, 1047), False, 'import cv2\n'), ((1451, 1468), 'numpy.array', 'np.array', (['[coord]'], {}), '([coord])\n', (1459, 1468), True, 'import numpy as np\n'), ((2119, 2153), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (2138, 2153), True, 'import numpy as np\n'), ((2240, 2292), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(1, 224, 224, 3)', 'dtype': 'np.float32'}), '(shape=(1, 224, 224, 3), dtype=np.float32)\n', (2250, 2292), True, 'import numpy as np\n'), ((2352, 2372), 'PIL.Image.open', 'Image.open', (['IMG_PATH'], {}), '(IMG_PATH)\n', (2362, 2372), False, 'from PIL import Image, ImageOps\n'), ((2559, 2601), 'PIL.ImageOps.fit', 'ImageOps.fit', (['image', 'size', 'Image.ANTIALIAS'], {}), '(image, size, Image.ANTIALIAS)\n', (2571, 2601), False, 'from PIL import Image, ImageOps\n'), ((2660, 2677), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (2670, 2677), True, 'import numpy as np\n'), ((3330, 3364), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (3349, 3364), True, 'import numpy as np\n'), ((3472, 3524), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(1, 224, 224, 3)', 'dtype': 'np.float32'}), '(shape=(1, 224, 224, 3), dtype=np.float32)\n', (3482, 3524), True, 'import numpy as np\n'), ((3584, 3604), 'PIL.Image.open', 'Image.open', (['IMG_PATH'], {}), '(IMG_PATH)\n', (3594, 3604), False, 'from PIL import Image, ImageOps\n'), ((3791, 3833), 'PIL.ImageOps.fit', 'ImageOps.fit', (['image', 'size', 'Image.ANTIALIAS'], {}), '(image, size, Image.ANTIALIAS)\n', (3803, 3833), False, 'from PIL import Image, ImageOps\n'), ((3892, 3909), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (3902, 3909), True, 'import numpy as np\n'), ((4667, 4696), 'flask.render_template', 'render_template', (['"""about.html"""'], {}), "('about.html')\n", (4682, 4696), False, 'from flask import Flask, render_template, request\n'), ((5495, 5517), 'json.dumps', 'json.dumps', (['dictRecult'], {}), '(dictRecult)\n', (5505, 5517), False, 'import json\n'), ((1806, 1828), 'numpy.squeeze', 'np.squeeze', (['prediction'], {}), '(prediction)\n', (1816, 1828), True, 'import numpy as np\n'), ((1943, 1975), 'json.dump', 'json.dump', (['writeList', 'filehandle'], {}), '(writeList, filehandle)\n', (1952, 1975), False, 'import json\n'), ((3029, 3051), 'numpy.squeeze', 'np.squeeze', (['prediction'], {}), '(prediction)\n', (3039, 3051), True, 'import numpy as np\n'), ((3156, 3188), 'json.dump', 'json.dump', (['writeList', 'filehandle'], {}), '(writeList, filehandle)\n', (3165, 3188), False, 'import json\n'), ((4239, 4261), 'numpy.squeeze', 'np.squeeze', (['prediction'], {}), '(prediction)\n', (4249, 4261), True, 'import numpy as np\n'), ((4366, 4398), 'json.dump', 'json.dump', (['writeList', 'filehandle'], {}), '(writeList, filehandle)\n', (4375, 4398), False, 'import json\n'), ((4867, 4888), 'json.load', 'json.load', (['filehandle'], {}), '(filehandle)\n', (4876, 4888), False, 'import json\n'), ((4991, 5012), 'json.load', 'json.load', (['filehandle'], {}), '(filehandle)\n', (5000, 5012), False, 'import json\n'), ((5088, 5109), 'json.load', 'json.load', (['filehandle'], {}), '(filehandle)\n', (5097, 5109), False, 'import json\n'), ((5879, 5915), 'cv2.imdecode', 'cv2.imdecode', (['buff', 'cv2.IMREAD_COLOR'], {}), '(buff, cv2.IMREAD_COLOR)\n', (5891, 5915), False, 'import cv2\n'), ((5929, 5950), 'PIL.Image.fromarray', 'Image.fromarray', (['data'], {}), '(data)\n', (5944, 5950), False, 'from PIL import Image, ImageOps\n'), ((6372, 6408), 'cv2.imdecode', 'cv2.imdecode', (['buff', 'cv2.IMREAD_COLOR'], {}), '(buff, cv2.IMREAD_COLOR)\n', (6384, 6408), False, 'import cv2\n'), ((6422, 6443), 'PIL.Image.fromarray', 'Image.fromarray', (['data'], {}), '(data)\n', (6437, 6443), False, 'from PIL import Image, ImageOps\n'), ((6863, 6899), 'cv2.imdecode', 'cv2.imdecode', (['buff', 'cv2.IMREAD_COLOR'], {}), '(buff, cv2.IMREAD_COLOR)\n', (6875, 6899), False, 'import cv2\n'), ((6913, 6934), 'PIL.Image.fromarray', 'Image.fromarray', (['data'], {}), '(data)\n', (6928, 6934), False, 'from PIL import Image, ImageOps\n'), ((1238, 1267), 'imutils.face_utils.shape_to_np', 'face_utils.shape_to_np', (['shape'], {}), '(shape)\n', (1260, 1267), False, 'from imutils import face_utils\n'), ((1726, 1751), 'numpy.squeeze', 'np.squeeze', (['prediction[0]'], {}), '(prediction[0])\n', (1736, 1751), True, 'import numpy as np\n'), ((2980, 3002), 'numpy.squeeze', 'np.squeeze', (['prediction'], {}), '(prediction)\n', (2990, 3002), True, 'import numpy as np\n'), ((4190, 4212), 'numpy.squeeze', 'np.squeeze', (['prediction'], {}), '(prediction)\n', (4200, 4212), True, 'import numpy as np\n'), ((5830, 5852), 'base64.b64decode', 'base64.b64decode', (['data'], {}), '(data)\n', (5846, 5852), False, 'import base64\n'), ((6323, 6345), 'base64.b64decode', 'base64.b64decode', (['data'], {}), '(data)\n', (6339, 6345), False, 'import base64\n'), ((6814, 6836), 'base64.b64decode', 'base64.b64decode', (['data'], {}), '(data)\n', (6830, 6836), False, 'import base64\n')] |
import multiprocessing
import tlib.conf as conf
bind='0.0.0.0:%s' % conf.get("port")
# workers=multiprocessing.cpu_count() * 2 + 1
# workers=multiprocessing.cpu_count()
workers=10
backlog=2048
worker_class="gevent"
debug=False
daemon=False
timeout=30
| [
"tlib.conf.get"
] | [((70, 86), 'tlib.conf.get', 'conf.get', (['"""port"""'], {}), "('port')\n", (78, 86), True, 'import tlib.conf as conf\n')] |
import os
import pytest
if __name__ == '__main__':
os.environ['PYWEBVIEW_GUI'] = 'win32'
pytest.main() | [
"pytest.main"
] | [((99, 112), 'pytest.main', 'pytest.main', ([], {}), '()\n', (110, 112), False, 'import pytest\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 13:17:19 2021
@author: matthew-bailey
"""
from layer_utils import verify_layer_sequence
import pytest
class TestSequenceVerifier:
def test_all_same_type(self):
"""
Test two simple valid sequences.
"""
seq = [1, 1, 1, 1, 1, 1]
assert verify_layer_sequence(seq)
seq = [3, 3, 3, 3, 3, 3]
assert verify_layer_sequence(seq)
def test_one_negative(self):
with pytest.raises(ValueError):
seq = [1, 1, 1, 1, 5, 1]
assert not verify_layer_sequence(seq)
def test_one_nonnumeric(self):
seq = [1, 1, 1, "a", 1, 1]
assert not verify_layer_sequence(seq)
def test_valid_pattern(self):
seq = [1, 2, 3, 4]
assert verify_layer_sequence(seq)
def test_invalid_pattern(self):
seq = [1, 3, 2, 4]
assert not verify_layer_sequence(seq)
def test_real_sequence(self):
"""
This sequence came with the code of unknown provenance
"""
seq = [1, 1, 1, 2, 3, 3, 3, 3, 3, 4, 1]
assert verify_layer_sequence(seq)
| [
"layer_utils.verify_layer_sequence",
"pytest.raises"
] | [((354, 380), 'layer_utils.verify_layer_sequence', 'verify_layer_sequence', (['seq'], {}), '(seq)\n', (375, 380), False, 'from layer_utils import verify_layer_sequence\n'), ((430, 456), 'layer_utils.verify_layer_sequence', 'verify_layer_sequence', (['seq'], {}), '(seq)\n', (451, 456), False, 'from layer_utils import verify_layer_sequence\n'), ((812, 838), 'layer_utils.verify_layer_sequence', 'verify_layer_sequence', (['seq'], {}), '(seq)\n', (833, 838), False, 'from layer_utils import verify_layer_sequence\n'), ((1134, 1160), 'layer_utils.verify_layer_sequence', 'verify_layer_sequence', (['seq'], {}), '(seq)\n', (1155, 1160), False, 'from layer_utils import verify_layer_sequence\n'), ((504, 529), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (517, 529), False, 'import pytest\n'), ((708, 734), 'layer_utils.verify_layer_sequence', 'verify_layer_sequence', (['seq'], {}), '(seq)\n', (729, 734), False, 'from layer_utils import verify_layer_sequence\n'), ((922, 948), 'layer_utils.verify_layer_sequence', 'verify_layer_sequence', (['seq'], {}), '(seq)\n', (943, 948), False, 'from layer_utils import verify_layer_sequence\n'), ((591, 617), 'layer_utils.verify_layer_sequence', 'verify_layer_sequence', (['seq'], {}), '(seq)\n', (612, 617), False, 'from layer_utils import verify_layer_sequence\n')] |
# -*- coding: utf-8 -*-
u"""zgoubi datafile parser
:copyright: Copyright (c) 2018 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkresource
from pykern.pkdebug import pkdc, pkdlog, pkdp
from sirepo import simulation_db
from sirepo.template import elegant_common, zgoubi_parser
from sirepo.template import template_common
import math
import re
_SIM_TYPE = 'zgoubi'
_SCHEMA = simulation_db.get_schema(_SIM_TYPE)
_IGNORE_FIELDS = ['bunch.coordinates', 'BEND.IL', 'BEND.NCE', 'BEND.NCS', 'MULTIPOL.IL', 'MULTIPOL.NCE', 'MULTIPOL.NCS', 'QUADRUPO.IL', 'QUADRUPO.NCE', 'QUADRUPO.NCS', 'SEXTUPOL.IL', 'SEXTUPOL.NCE', 'SEXTUPOL.NCS']
_DEGREE_TO_RADIAN_FIELDS = ['CHANGREF.ALE']
_MRAD_FIELDS = ['AUTOREF.ALE']
#TODO(pjm): consolidate this with template.zgoubi _MODEL_UNITS, use one definition
_CM_FIELDS = ['l', 'X_E', 'LAM_E', 'X_S', 'LAM_S', 'XCE', 'YCE', 'R_0', 'dY', 'dZ', 'dS', 'YR', 'ZR', 'SR']
def import_file(text):
data = simulation_db.default_data(_SIM_TYPE)
#TODO(pjm): need a common way to clean-up/uniquify a simulation name from imported text
title, elements, unhandled_elements = zgoubi_parser.parse_file(text, 1)
title = re.sub(r'\s+', ' ', title)
title = re.sub(r'^\s+|\s+$', '', title)
data['models']['simulation']['name'] = title if title else 'zgoubi'
if len(unhandled_elements):
data['models']['simulation']['warnings'] = 'Unsupported Zgoubi elements: {}'.format(', '.join(unhandled_elements))
info = _validate_and_dedup_elements(data, elements)
_validate_element_names(data, info)
elegant_common.sort_elements_and_beamlines(data)
return data
def _validate_and_dedup_elements(data, elements):
beamline = []
current_id = 1
data['models']['beamlines'] = [
{
'name': 'BL1',
'id': current_id,
'items': beamline,
},
]
data['models']['simulation']['activeBeamlineId'] = current_id
data['models']['simulation']['visualizationBeamlineId'] = current_id
info = {
'ids': [],
'names': [],
'elements': [],
}
for el in elements:
_validate_model(el)
if 'name' in el:
name = el['name']
#TODO(pjm): don't de-duplicate certain types
if el['type'] != 'MARKER':
del el['name']
if el not in info['elements']:
current_id += 1
info['ids'].append(current_id)
info['names'].append(name)
info['elements'].append(el)
beamline.append(info['ids'][info['elements'].index(el)])
else:
if el['type'] in data['models']:
pkdlog('replacing existing {} model', el['type'])
template_common.update_model_defaults(el, el['type'], _SCHEMA)
data['models'][el['type']] = el
return info
def _validate_element_names(data, info):
names = {}
for idx in range(len(info['ids'])):
el = info['elements'][idx]
template_common.update_model_defaults(el, el['type'], _SCHEMA)
el['_id'] = info['ids'][idx]
name = info['names'][idx]
name = re.sub(r'\\', '_', name)
name = re.sub(r'\d+$', '', name)
name = re.sub(r'(\_|\#)$', '', name)
if not name:
name = el['type'][:2]
if name in names:
count = 2
while True:
name2 = '{}{}'.format(name, count)
if name2 not in names:
name = name2
break
count += 1
el['name'] = name
names[name] = True
data['models']['elements'].append(el)
def _validate_field(model, field, model_info):
if field in ('_id', 'type'):
return
assert field in model_info, \
'unknown model field: {}.{}, value: {}'.format(model['type'], field, model[field])
field_info = model_info[field]
field_type = field_info[1]
if field_type == 'Float':
model[field] = float(model[field])
mf = '{}.{}'.format(model['type'], field)
if mf in _DEGREE_TO_RADIAN_FIELDS:
model[field] *= math.pi / 180.0
elif mf in _MRAD_FIELDS:
model[field] /= 1000.0
elif field in _CM_FIELDS and model['type'] != 'CAVITE':
model[field] *= 0.01
elif field == 'XPAS':
#TODO(pjm): need special handling, may be in #00|00|00 format
if not re.search(r'\#', model[field]):
v = float(model[field])
if v > 1e10:
# old step size format
m = re.search(r'^0*(\d+)\.0*(\d+)', model[field])
assert m, 'XPAS failed to parse step size: {}'.format(model[field])
model[field] = '#{}|{}|{}'.format(m.group(2), m.group(1), m.group(2))
else:
model[field] = str(v * 0.01)
elif field_type in _SCHEMA['enum']:
for v in _SCHEMA['enum'][field_type]:
if v[0] == model[field]:
return
pkdlog('invalid enum value, {}.{} {}: {}', model['type'], field, field_type, model[field])
model[field] = field_info[3]
def _validate_model(model):
assert model['type'] in _SCHEMA['model'], \
'element type missing from schema: {}'.format(model['type'])
model_info = _SCHEMA['model'][model['type']]
if 'name' in model_info and 'name' not in model:
model['name'] = ''
for f in model:
if f == 'label2':
continue
if '{}.{}'.format(model['type'], f) in _IGNORE_FIELDS:
continue
_validate_field(model, f, model_info)
| [
"sirepo.simulation_db.default_data",
"sirepo.template.template_common.update_model_defaults",
"pykern.pkdebug.pkdlog",
"sirepo.simulation_db.get_schema",
"re.sub",
"sirepo.template.elegant_common.sort_elements_and_beamlines",
"sirepo.template.zgoubi_parser.parse_file",
"re.search"
] | [((512, 547), 'sirepo.simulation_db.get_schema', 'simulation_db.get_schema', (['_SIM_TYPE'], {}), '(_SIM_TYPE)\n', (536, 547), False, 'from sirepo import simulation_db\n'), ((1065, 1102), 'sirepo.simulation_db.default_data', 'simulation_db.default_data', (['_SIM_TYPE'], {}), '(_SIM_TYPE)\n', (1091, 1102), False, 'from sirepo import simulation_db\n'), ((1237, 1270), 'sirepo.template.zgoubi_parser.parse_file', 'zgoubi_parser.parse_file', (['text', '(1)'], {}), '(text, 1)\n', (1261, 1270), False, 'from sirepo.template import elegant_common, zgoubi_parser\n'), ((1283, 1309), 're.sub', 're.sub', (['"""\\\\s+"""', '""" """', 'title'], {}), "('\\\\s+', ' ', title)\n", (1289, 1309), False, 'import re\n'), ((1322, 1354), 're.sub', 're.sub', (['"""^\\\\s+|\\\\s+$"""', '""""""', 'title'], {}), "('^\\\\s+|\\\\s+$', '', title)\n", (1328, 1354), False, 'import re\n'), ((1681, 1729), 'sirepo.template.elegant_common.sort_elements_and_beamlines', 'elegant_common.sort_elements_and_beamlines', (['data'], {}), '(data)\n', (1723, 1729), False, 'from sirepo.template import elegant_common, zgoubi_parser\n'), ((3121, 3183), 'sirepo.template.template_common.update_model_defaults', 'template_common.update_model_defaults', (['el', "el['type']", '_SCHEMA'], {}), "(el, el['type'], _SCHEMA)\n", (3158, 3183), False, 'from sirepo.template import template_common\n'), ((3270, 3295), 're.sub', 're.sub', (['"""\\\\\\\\"""', '"""_"""', 'name'], {}), "('\\\\\\\\', '_', name)\n", (3276, 3295), False, 'import re\n'), ((3310, 3335), 're.sub', 're.sub', (['"""\\\\d+$"""', '""""""', 'name'], {}), "('\\\\d+$', '', name)\n", (3316, 3335), False, 'import re\n'), ((3351, 3381), 're.sub', 're.sub', (['"""(\\\\_|\\\\#)$"""', '""""""', 'name'], {}), "('(\\\\_|\\\\#)$', '', name)\n", (3357, 3381), False, 'import re\n'), ((2857, 2919), 'sirepo.template.template_common.update_model_defaults', 'template_common.update_model_defaults', (['el', "el['type']", '_SCHEMA'], {}), "(el, el['type'], _SCHEMA)\n", (2894, 2919), False, 'from sirepo.template import template_common\n'), ((2795, 2844), 'pykern.pkdebug.pkdlog', 'pkdlog', (['"""replacing existing {} model"""', "el['type']"], {}), "('replacing existing {} model', el['type'])\n", (2801, 2844), False, 'from pykern.pkdebug import pkdc, pkdlog, pkdp\n'), ((4557, 4587), 're.search', 're.search', (['"""\\\\#"""', 'model[field]'], {}), "('\\\\#', model[field])\n", (4566, 4587), False, 'import re\n'), ((5142, 5236), 'pykern.pkdebug.pkdlog', 'pkdlog', (['"""invalid enum value, {}.{} {}: {}"""', "model['type']", 'field', 'field_type', 'model[field]'], {}), "('invalid enum value, {}.{} {}: {}', model['type'], field, field_type,\n model[field])\n", (5148, 5236), False, 'from pykern.pkdebug import pkdc, pkdlog, pkdp\n'), ((4709, 4756), 're.search', 're.search', (['"""^0*(\\\\d+)\\\\.0*(\\\\d+)"""', 'model[field]'], {}), "('^0*(\\\\d+)\\\\.0*(\\\\d+)', model[field])\n", (4718, 4756), False, 'import re\n')] |
from django.db import models
LINEAGE_CHOICES = (
('startswith', 'startswith'),
('endswith', 'endswith'),
('contains', 'contains'),
('equals', 'equals')
)
class Lineage(models.Model):
parent = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE)
key = models.CharField(choices=LINEAGE_CHOICES, blank=False, null=False, max_length=255)
value = models.CharField(max_length=500, blank=False, null=False)
os = models.CharField(max_length=255, blank=False, null=False)
def __str__(self):
if self.parent:
return f"{self.os}: {self.parent.key}:{self.parent.value} > {self.key}:{self.value}"
else:
return f"{self.os}: {self.key}:{self.value}"
| [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((216, 290), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""self"""'], {'blank': '(True)', 'null': '(True)', 'on_delete': 'models.CASCADE'}), "('self', blank=True, null=True, on_delete=models.CASCADE)\n", (233, 290), False, 'from django.db import models\n'), ((301, 387), 'django.db.models.CharField', 'models.CharField', ([], {'choices': 'LINEAGE_CHOICES', 'blank': '(False)', 'null': '(False)', 'max_length': '(255)'}), '(choices=LINEAGE_CHOICES, blank=False, null=False,\n max_length=255)\n', (317, 387), False, 'from django.db import models\n'), ((396, 453), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)', 'blank': '(False)', 'null': '(False)'}), '(max_length=500, blank=False, null=False)\n', (412, 453), False, 'from django.db import models\n'), ((463, 520), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'blank': '(False)', 'null': '(False)'}), '(max_length=255, blank=False, null=False)\n', (479, 520), False, 'from django.db import models\n')] |
"""
Tests of ModelAdmin validation logic.
"""
from django.db import models
class Album(models.Model):
title = models.CharField(max_length=150)
class Song(models.Model):
title = models.CharField(max_length=150)
album = models.ForeignKey(Album)
original_release = models.DateField(editable=False)
class Meta:
ordering = ('title',)
def __unicode__(self):
return self.title
def readonly_method_on_model(self):
# does nothing
pass
class TwoAlbumFKAndAnE(models.Model):
album1 = models.ForeignKey(Album, related_name="album1_set")
album2 = models.ForeignKey(Album, related_name="album2_set")
e = models.CharField(max_length=1)
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
name = models.CharField(max_length=100)
subtitle = models.CharField(max_length=100)
price = models.FloatField()
authors = models.ManyToManyField(Author, through='AuthorsBooks')
class AuthorsBooks(models.Model):
author = models.ForeignKey(Author)
book = models.ForeignKey(Book)
__test__ = {'API_TESTS':"""
>>> from django import forms
>>> from django.contrib import admin
>>> from django.contrib.admin.validation import validate, validate_inline
# Regression test for #8027: custom ModelForms with fields/fieldsets
>>> class SongForm(forms.ModelForm):
... pass
>>> class ValidFields(admin.ModelAdmin):
... form = SongForm
... fields = ['title']
>>> class InvalidFields(admin.ModelAdmin):
... form = SongForm
... fields = ['spam']
>>> validate(ValidFields, Song)
>>> validate(InvalidFields, Song)
Traceback (most recent call last):
...
ImproperlyConfigured: 'InvalidFields.fields' refers to field 'spam' that is missing from the form.
# Tests for basic validation of 'exclude' option values (#12689)
>>> class ExcludedFields1(admin.ModelAdmin):
... exclude = ('foo')
>>> validate(ExcludedFields1, Book)
Traceback (most recent call last):
...
ImproperlyConfigured: 'ExcludedFields1.exclude' must be a list or tuple.
>>> class ExcludedFields2(admin.ModelAdmin):
... exclude = ('name', 'name')
>>> validate(ExcludedFields2, Book)
Traceback (most recent call last):
...
ImproperlyConfigured: There are duplicate field(s) in ExcludedFields2.exclude
>>> class ExcludedFieldsInline(admin.TabularInline):
... model = Song
... exclude = ('foo')
>>> class ExcludedFieldsAlbumAdmin(admin.ModelAdmin):
... model = Album
... inlines = [ExcludedFieldsInline]
>>> validate(ExcludedFieldsAlbumAdmin, Album)
Traceback (most recent call last):
...
ImproperlyConfigured: 'ExcludedFieldsInline.exclude' must be a list or tuple.
# Regression test for #9932 - exclude in InlineModelAdmin
# should not contain the ForeignKey field used in ModelAdmin.model
>>> class SongInline(admin.StackedInline):
... model = Song
... exclude = ['album']
>>> class AlbumAdmin(admin.ModelAdmin):
... model = Album
... inlines = [SongInline]
>>> validate(AlbumAdmin, Album)
Traceback (most recent call last):
...
ImproperlyConfigured: SongInline cannot exclude the field 'album' - this is the foreign key to the parent model Album.
# Regression test for #11709 - when testing for fk excluding (when exclude is
# given) make sure fk_name is honored or things blow up when there is more
# than one fk to the parent model.
>>> class TwoAlbumFKAndAnEInline(admin.TabularInline):
... model = TwoAlbumFKAndAnE
... exclude = ("e",)
... fk_name = "album1"
>>> validate_inline(TwoAlbumFKAndAnEInline, None, Album)
# Ensure inlines validate that they can be used correctly.
>>> class TwoAlbumFKAndAnEInline(admin.TabularInline):
... model = TwoAlbumFKAndAnE
>>> validate_inline(TwoAlbumFKAndAnEInline, None, Album)
Traceback (most recent call last):
...
Exception: <class 'regressiontests.admin_validation.models.TwoAlbumFKAndAnE'> has more than 1 ForeignKey to <class 'regressiontests.admin_validation.models.Album'>
>>> class TwoAlbumFKAndAnEInline(admin.TabularInline):
... model = TwoAlbumFKAndAnE
... fk_name = "album1"
>>> validate_inline(TwoAlbumFKAndAnEInline, None, Album)
>>> class SongAdmin(admin.ModelAdmin):
... readonly_fields = ("title",)
>>> validate(SongAdmin, Song)
>>> def my_function(obj):
... # does nothing
... pass
>>> class SongAdmin(admin.ModelAdmin):
... readonly_fields = (my_function,)
>>> validate(SongAdmin, Song)
>>> class SongAdmin(admin.ModelAdmin):
... readonly_fields = ("readonly_method_on_modeladmin",)
...
... def readonly_method_on_modeladmin(self, obj):
... # does nothing
... pass
>>> validate(SongAdmin, Song)
>>> class SongAdmin(admin.ModelAdmin):
... readonly_fields = ("readonly_method_on_model",)
>>> validate(SongAdmin, Song)
>>> class SongAdmin(admin.ModelAdmin):
... readonly_fields = ("title", "nonexistant")
>>> validate(SongAdmin, Song)
Traceback (most recent call last):
...
ImproperlyConfigured: SongAdmin.readonly_fields[1], 'nonexistant' is not a callable or an attribute of 'SongAdmin' or found in the model 'Song'.
>>> class SongAdmin(admin.ModelAdmin):
... readonly_fields = ("title", "awesome_song")
... fields = ("album", "title", "awesome_song")
>>> validate(SongAdmin, Song)
Traceback (most recent call last):
...
ImproperlyConfigured: SongAdmin.readonly_fields[1], 'awesome_song' is not a callable or an attribute of 'SongAdmin' or found in the model 'Song'.
>>> class SongAdmin(SongAdmin):
... def awesome_song(self, instance):
... if instance.title == "Born to Run":
... return "Best Ever!"
... return "Status unknown."
>>> validate(SongAdmin, Song)
>>> class SongAdmin(admin.ModelAdmin):
... readonly_fields = (lambda obj: "test",)
>>> validate(SongAdmin, Song)
# Regression test for #12203/#12237 - Fail more gracefully when a M2M field that
# specifies the 'through' option is included in the 'fields' or the 'fieldsets'
# ModelAdmin options.
>>> class BookAdmin(admin.ModelAdmin):
... fields = ['authors']
>>> validate(BookAdmin, Book)
Traceback (most recent call last):
...
ImproperlyConfigured: 'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.
>>> class FieldsetBookAdmin(admin.ModelAdmin):
... fieldsets = (
... ('Header 1', {'fields': ('name',)}),
... ('Header 2', {'fields': ('authors',)}),
... )
>>> validate(FieldsetBookAdmin, Book)
Traceback (most recent call last):
...
ImproperlyConfigured: 'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.
>>> class NestedFieldsetAdmin(admin.ModelAdmin):
... fieldsets = (
... ('Main', {'fields': ('price', ('name', 'subtitle'))}),
... )
>>> validate(NestedFieldsetAdmin, Book)
# Regression test for #12209 -- If the explicitly provided through model
# is specified as a string, the admin should still be able use
# Model.m2m_field.through
>>> class AuthorsInline(admin.TabularInline):
... model = Book.authors.through
>>> class BookAdmin(admin.ModelAdmin):
... inlines = [AuthorsInline]
# If the through model is still a string (and hasn't been resolved to a model)
# the validation will fail.
>>> validate(BookAdmin, Book)
# Regression for ensuring ModelAdmin.fields can contain non-model fields
# that broke with r11737
>>> class SongForm(forms.ModelForm):
... extra_data = forms.CharField()
... class Meta:
... model = Song
>>> class FieldsOnFormOnlyAdmin(admin.ModelAdmin):
... form = SongForm
... fields = ['title', 'extra_data']
>>> validate(FieldsOnFormOnlyAdmin, Song)
"""}
| [
"django.db.models.FloatField",
"django.db.models.DateField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.CharField"
] | [((117, 149), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(150)'}), '(max_length=150)\n', (133, 149), False, 'from django.db import models\n'), ((190, 222), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(150)'}), '(max_length=150)\n', (206, 222), False, 'from django.db import models\n'), ((235, 259), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Album'], {}), '(Album)\n', (252, 259), False, 'from django.db import models\n'), ((283, 315), 'django.db.models.DateField', 'models.DateField', ([], {'editable': '(False)'}), '(editable=False)\n', (299, 315), False, 'from django.db import models\n'), ((547, 598), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Album'], {'related_name': '"""album1_set"""'}), "(Album, related_name='album1_set')\n", (564, 598), False, 'from django.db import models\n'), ((612, 663), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Album'], {'related_name': '"""album2_set"""'}), "(Album, related_name='album2_set')\n", (629, 663), False, 'from django.db import models\n'), ((672, 702), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(1)'}), '(max_length=1)\n', (688, 702), False, 'from django.db import models\n'), ((744, 776), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (760, 776), False, 'from django.db import models\n'), ((816, 848), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (832, 848), False, 'from django.db import models\n'), ((864, 896), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (880, 896), False, 'from django.db import models\n'), ((909, 928), 'django.db.models.FloatField', 'models.FloatField', ([], {}), '()\n', (926, 928), False, 'from django.db import models\n'), ((943, 997), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Author'], {'through': '"""AuthorsBooks"""'}), "(Author, through='AuthorsBooks')\n", (965, 997), False, 'from django.db import models\n'), ((1047, 1072), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Author'], {}), '(Author)\n', (1064, 1072), False, 'from django.db import models\n'), ((1084, 1107), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Book'], {}), '(Book)\n', (1101, 1107), False, 'from django.db import models\n')] |