code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
from enum import Enum from typing import Dict, Any from jwt.algorithms import get_default_algorithms from cryptography.hazmat._types import ( _PRIVATE_KEY_TYPES, _PUBLIC_KEY_TYPES, ) # custom types PrivateKey = _PRIVATE_KEY_TYPES PublicKey = _PUBLIC_KEY_TYPES JWTClaims = Dict[str, Any] class EncryptionKeyFormat(str, Enum): """ represent the supported formats for storing encryption keys. - PEM (https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) - SSH (RFC4716) or short format (RFC4253, section-6.6, explained here: https://coolaj86.com/articles/the-ssh-public-key-format/) - DER (https://en.wikipedia.org/wiki/X.690#DER_encoding) """ pem = 'pem' ssh = 'ssh' der = 'der' # dynamic enum because pyjwt does not define one # see: https://pyjwt.readthedocs.io/en/stable/algorithms.html for possible values JWTAlgorithm = Enum('JWTAlgorithm', [(k,k) for k in get_default_algorithms().keys()])
[ "jwt.algorithms.get_default_algorithms" ]
[((910, 934), 'jwt.algorithms.get_default_algorithms', 'get_default_algorithms', ([], {}), '()\n', (932, 934), False, 'from jwt.algorithms import get_default_algorithms\n')]
# coding=utf8 微信公众号代码 from werobot import WeRoBot from .models import * import time robot = WeRoBot(enable_session=False, token='<PASSWORD>', app_id='wx87d17a791d346b6b', app_secret='8d2d3270d9c8c564056dbe43110a7dce', ) # @robot.handler # def hello(message): # return "hello world! yhj888" @robot.key_click("music") def music(message): return '你点击了“今日歌曲”按钮' @robot.subscribe def subscribe(message): print('关注信息') print(message.FromUserName) openid=message.FromUserName createtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) upeate_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) if openid: try: user = wxuser.objects.get(openid=openid) print(user) user.stats = '1' user.upeate_time=upeate_time user.save() return "欢迎再次关注!" except: # 如果用户不存在,提交到数据库保存 re1 = wxuser.objects.create(openid=openid, create_time=createtime,stats=1,upeate_time=upeate_time) re1.save() return "终于等到你,欢迎关注!" else: # message = "用户名或密码为空!请重新输入!" return "警告,非法请求!" @robot.unsubscribe def unsubscribe(message): print('取消关注') # print(message.FromUserName) openid=message.FromUserName createtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) upeate_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) try: user = wxuser.objects.get(openid=openid) user.stats = '0' user.upeate_time=upeate_time user.save() return "欢迎你的再次光临!" except: return "请先关注公众号!" @robot.text def echo(message): #try: # 提取消息 msg1 = message.content print('文本'+msg1) return msg1 @robot.image def img(message): # print(type(message)) # print(type(message.img)) # return message.img return "别闹,还是发文字吧!" @robot.voice def voice(message): return "有什么心里话,可以微我。" @robot.video def video(message): return "抱歉我看不懂视频!可以给我主人发哦" @robot.link def link(message): return "抱歉我打不开链接,你可以告诉我里面的故事啊!" @robot.unknown def unknown(message): return "可以好好说话吗?"
[ "time.localtime", "werobot.WeRoBot" ]
[((92, 222), 'werobot.WeRoBot', 'WeRoBot', ([], {'enable_session': '(False)', 'token': '"""<PASSWORD>"""', 'app_id': '"""wx87d17a791d346b6b"""', 'app_secret': '"""8d2d3270d9c8c564056dbe43110a7dce"""'}), "(enable_session=False, token='<PASSWORD>', app_id=\n 'wx87d17a791d346b6b', app_secret='8d2d3270d9c8c564056dbe43110a7dce')\n", (99, 222), False, 'from werobot import WeRoBot\n'), ((591, 607), 'time.localtime', 'time.localtime', ([], {}), '()\n', (605, 607), False, 'import time\n'), ((660, 676), 'time.localtime', 'time.localtime', ([], {}), '()\n', (674, 676), False, 'import time\n'), ((1374, 1390), 'time.localtime', 'time.localtime', ([], {}), '()\n', (1388, 1390), False, 'import time\n'), ((1443, 1459), 'time.localtime', 'time.localtime', ([], {}), '()\n', (1457, 1459), False, 'import time\n')]
import board import busio import digitalio import time import adafruit_requests as requests from adafruit_wiznet5k.adafruit_wiznet5k import * import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket from adafruit_wiznet5k.adafruit_wiznet5k_ntp import NTP import adafruit_wiznet5k.adafruit_wiznet5k_dns as dns days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") ##SPI0 SPI0_SCK = board.GP18 SPI0_TX = board.GP19 SPI0_RX = board.GP16 SPI0_CSn = board.GP17 ##reset W5x00_RSTn = board.GP20 print("Wiznet5k NTP Client ( DHCP)") # Setup your network configuration below # random MAC, later should change this value on your vendor ID MY_MAC = (0x00, 0x01, 0x02, 0xFF, 0xFF, 0xFF) IP_ADDRESS = (192, 168, 1, 11) SUBNET_MASK = (255, 255, 255, 0) GATEWAY_ADDRESS = (192, 168, 1, 1) DNS_SERVER = (8, 8, 8, 8) port = 5000 ntp_server_port= 123 led = digitalio.DigitalInOut(board.GP25) led.direction = digitalio.Direction.OUTPUT ethernetRst = digitalio.DigitalInOut(W5x00_RSTn) ethernetRst.direction = digitalio.Direction.OUTPUT # For Adafruit Ethernet FeatherWing cs = digitalio.DigitalInOut(SPI0_CSn) # cs = digitalio.DigitalInOut(board.D5) spi_bus = busio.SPI(SPI0_SCK, MOSI=SPI0_TX, MISO=SPI0_RX) # Reset W5500 first ethernetRst.value = False time.sleep(1) ethernetRst.value = True # Initialize ethernet interface without DHCP #eth = WIZNET5K(spi_bus, cs, is_dhcp=False, mac=MY_MAC, debug=False) # Initialize ethernet interface with DHCP eth = WIZNET5K(spi_bus, cs, is_dhcp=True, mac=MY_MAC, debug=False) print("Chip Version:", eth.chip) print("MAC Address:", [hex(i) for i in eth.mac_address]) print("My IP address is:", eth.pretty_ip(eth.ip_address)) # Initialize a socket for our server #socket.set_interface(eth) # Set network configuration #eth.ifconfig = (IP_ADDRESS, SUBNET_MASK, GATEWAY_ADDRESS, DNS_SERVER) #NTP ntpserver_ip = eth.pretty_ip(eth.get_host_by_name("time.google.com")) print("NTP : %s" % ntpserver_ip) #DNS Domain ntp = NTP(iface = eth, ntp_address =ntpserver_ip ,utc=9) cal = ntp.get_time() print("The date is %s %d/%d/%d" %(days[cal.tm_wday], cal.tm_mday,cal.tm_mon,cal.tm_year)) print("The time is %d:%02d:%02d" %(cal.tm_hour,cal.tm_min,cal.tm_sec))
[ "digitalio.DigitalInOut", "busio.SPI", "adafruit_wiznet5k.adafruit_wiznet5k_ntp.NTP", "time.sleep" ]
[((924, 958), 'digitalio.DigitalInOut', 'digitalio.DigitalInOut', (['board.GP25'], {}), '(board.GP25)\n', (946, 958), False, 'import digitalio\n'), ((1020, 1054), 'digitalio.DigitalInOut', 'digitalio.DigitalInOut', (['W5x00_RSTn'], {}), '(W5x00_RSTn)\n', (1042, 1054), False, 'import digitalio\n'), ((1152, 1184), 'digitalio.DigitalInOut', 'digitalio.DigitalInOut', (['SPI0_CSn'], {}), '(SPI0_CSn)\n', (1174, 1184), False, 'import digitalio\n'), ((1239, 1286), 'busio.SPI', 'busio.SPI', (['SPI0_SCK'], {'MOSI': 'SPI0_TX', 'MISO': 'SPI0_RX'}), '(SPI0_SCK, MOSI=SPI0_TX, MISO=SPI0_RX)\n', (1248, 1286), False, 'import busio\n'), ((1338, 1351), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1348, 1351), False, 'import time\n'), ((2060, 2107), 'adafruit_wiznet5k.adafruit_wiznet5k_ntp.NTP', 'NTP', ([], {'iface': 'eth', 'ntp_address': 'ntpserver_ip', 'utc': '(9)'}), '(iface=eth, ntp_address=ntpserver_ip, utc=9)\n', (2063, 2107), False, 'from adafruit_wiznet5k.adafruit_wiznet5k_ntp import NTP\n')]
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db.models import Max def set_order(sender, instance, **kwargs): """If not set, determine and set the instance's order value.""" from .models import OrderMixin is_order_subclass = issubclass(instance.__class__, OrderMixin) raw = kwargs.get('raw', False) if is_order_subclass and not any([instance.pk, instance.order, raw]): order = instance.__class__.objects.aggregate( order=Max('order')).get('order') instance.order = order + 1 if order is not None else 1
[ "django.db.models.Max" ]
[((512, 524), 'django.db.models.Max', 'Max', (['"""order"""'], {}), "('order')\n", (515, 524), False, 'from django.db.models import Max\n')]
import datetime import logging import random import re import time from typing import Iterator, List, Union, Dict from urllib.parse import quote import pandas as pd import requests from bs4 import BeautifulSoup from .conn_postgresql import ConnPostgreSQL log = logging.getLogger(__name__) class HhParser: """Парсер hh.ru.""" def __init__(self, area: int, search_period: int, search_text: str, search_regex: str) -> None: """ :param area: Регион поиска (1 - Москва) :param search_period: Период поиска в днях :param search_text: Поисквовый запрос :param search_regex: Уточняющая регулярка для названия вакансии """ self.__area = area self.__search_period = search_period self.__search_text = search_text self.__search_regex = search_regex self.__base_url = 'https://hh.ru/search/vacancy' self.__url_params = { 'search_period': self.__search_period, 'clusters': 'true', 'area': self.__area, 'text': quote(self.__search_text), 'enable_snippets': 'true', 'page': 0 } self.__session = requests.Session() self.__headers = { 'accept': '*/*', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/76.0.3809.100 Safari/537.36' } area = property(lambda self: self.__area) search_period = property(lambda self: self.__search_period) search_text = property(lambda self: self.__search_text) search_regex = property(lambda self: self.__search_regex) class HhParserResults: """Результаты парсинга hh.""" def __init__(self, data: pd.DataFrame) -> None: """ :param data: Данные парсинга """ self.__data = data self.area = None self.search_period = None self.search_text = None self.search_regex = None self.parse_duration = None self.df_parsing_results = None self.df_current_jobs = None self.df_unique_jobs = None self.df_unique_closed_jobs = None data = property(lambda self: self.__data) @staticmethod def _get_url_with_params(url: str, params: dict) -> str: """ Сформируй URL с параметрами. :param url: URL :param params: Параметры URL """ return f'{url}?' + '&'.join([f'{k}={v}' for k, v in params.items()]) def _get_urls_pages_with_vacancies(self) -> Iterator[str]: """Получи URL страниц с вакансиями.""" start_url = self._get_url_with_params(self.__base_url, self.__url_params) urls = [start_url] response = self.__exponential_backoff(start_url) if response is not False: result = BeautifulSoup(response.content, 'lxml') pages = result.find_all('a', attrs={'data-qa': 'pager-page'}) page_count = int(pages[-1].text) url_params = self.__url_params for i in range(page_count - 1): url_params['page'] = i + 1 urls.append(self._get_url_with_params(self.__base_url, url_params)) log.info(f'Found {len(urls)} pages with "{self.__search_text}" vacancies') yield from urls else: log.error(f'Start request failed') raise RuntimeError('Request failed') def run(self) -> HhParserResults: """Запусти парсер.""" time_start = time.monotonic() log.info(f'Looking for "{self.__search_text}" vacancies on hh.ru...') vacancies_pages_urls = self._get_urls_pages_with_vacancies() raw_vacancies_data = [] url_counter = 1 for url in vacancies_pages_urls: log.info(f'Parsing page {url_counter}...') response = self.__exponential_backoff(url) if response is not False: result = BeautifulSoup(response.content, 'lxml') vacancies_divs = result.find_all('div', attrs={ 'data-qa': 'vacancy-serp__vacancy' }) premium_vacancies_divs = result.find_all('div', attrs={ 'data-qa': 'vacancy-serp__vacancy vacancy-serp__vacancy_premium' }) vacancies_data = self._get_data_from_divs(vacancies_divs) premium_vacancies_data = self._get_data_from_divs(premium_vacancies_divs) raw_vacancies_data += vacancies_data + premium_vacancies_data else: log.error(f'Request failed') raise RuntimeError('Request failed') url_counter += 1 df = pd.DataFrame(raw_vacancies_data) if len(df) == 0: log.error(f'No results found for settings: area={self.__area}, period={self.__search_period}, ' f'text={self.__search_text}, specifying_regex={self.__search_regex}') raise RuntimeError('No results found') df['date'] = pd.to_datetime(df['date'], dayfirst=True) df = df[['date', 'title', 'salary', 'company', 'href']].sort_values(by='date', ascending=False) parse_duration = round(time.monotonic() - time_start, 2) log.info(f'Found {len(df)} vacancies in {parse_duration} seconds') results = self.HhParserResults(df) results.parse_duration = parse_duration results.area = self.__area results.search_period = self.__search_period results.search_text = self.__search_text results.search_regex = self.__search_regex return results def _vacancy_name_check(self, title: str) -> bool: """ Проверь название вакансии уточняющим регулярным выражением. :param title: Название вакансии """ if re.search(self.__search_regex, title, flags=re.IGNORECASE): return True return False @staticmethod def _process_date(raw_date: str) -> str: """ Преобразуй дату публикации вакансии. :param raw_date: Дата из вакансии """ date_dict = { 'января': '01', 'февраля': '02', 'марта': '03', 'апреля': '04', 'мая': '05', 'июня': '06', 'июля': '07', 'августа': '08', 'сентября': '09', 'октября': '10', 'ноября': '11', 'декабря': '12' } date_arr = raw_date.split(' ') for i in range(len(date_arr)): try: date_arr[i] = date_dict[date_arr[i]] except KeyError: pass # Добавляем год к дате date_arr.append(str(datetime.datetime.now().year)) if datetime.datetime.strptime('.'.join(date_arr), '%d.%m.%Y') > datetime.datetime.now(): date_arr[-1] = str(datetime.datetime.now().year - 1) return '.'.join(date_arr) def _get_data_from_divs(self, divs: List) -> List[dict]: """ Получи данные из блоков с вакансиями. :param divs: Блоки с вакансиями """ results = [] for div in divs: title = div.find('a', attrs={'data-qa': 'vacancy-serp__vacancy-title'}).text if not self._vacancy_name_check(title): continue company_data = div.find('a', attrs={'data-qa': 'vacancy-serp__vacancy-employer'}) company = company_data.text if company_data else 'Не определено' href = div.find('a', attrs={'data-qa': 'vacancy-serp__vacancy-title'}).get('href') date = self._process_date( div.find('span', attrs={'class': 'vacancy-serp-item__publication-date'}).text.replace('\xa0', ' ') ) salary_data = div.find('span', attrs={'data-qa': 'vacancy-serp__vacancy-compensation'}) salary = salary_data.text.replace('\xa0', '') if salary_data else 'Не указано' results.append({'title': title, 'company': company, 'salary': salary, 'date': date, 'href': href}) return results def __exponential_backoff(self, url: str) -> Union[requests.Response, bool]: """ Экспоненциальная выдержка для 403, 500 и 503 ошибки. :param url: URL запроса :return: Ответ сервера или False при ошибке """ for n in range(0, 5): log.debug(f'GET request to URL {url}') response = self.__session.get(url, headers=self.__headers) if response.status_code in [403, 500, 503]: log.debug(f'HTTP error: {response.status_code}. Trying again. Attempt {n + 1}') time.sleep((2 ** n) + random.random()) elif response.status_code == 200: return response else: log.error(f'HTTP error {response.status_code} during requesting URL: {url}') return False log.error(f'Failed request URL {url} in 5 attempts') return False class HhParserResultsProcessor: """Обработка результатов парсинга.""" def __init__(self, hh_parsed_data: HhParser.HhParserResults, pg_conn=ConnPostgreSQL) -> None: """ :param hh_parsed_data: Результаты парсинга :param pg_conn: Активное подключение к PostgreSQL """ self.__hh_parsed_data = hh_parsed_data self.__df = hh_parsed_data.data self.__parsing_duration = hh_parsed_data.parse_duration self.__pg_conn = pg_conn hh_parsed_data = property(lambda self: self.__hh_parsed_data) report_folder = property(lambda self: self.__report_folder) def run(self) -> HhParser.HhParserResults: """Запусти обработку результатов парсинга.""" self._get_parsing_results_df() self._get_current_jobs_df() self._get_unique_jobs_df() self._get_unique_closed_jobs_df() return self.__hh_parsed_data def _find_jobs_without_salary(self) -> Dict[str, Union[int, float]]: """Найди % вакансий без указания зарплаты.""" unknown_salary_count = self.__df.loc[self.__df['salary'] == 'Не указано']['salary'].count() unknown_salary_percent = round((unknown_salary_count / len(self.__df)) * 100, 2) log.info(f'Jobs without salary: {unknown_salary_percent}%') return {'jobs_without_salary': unknown_salary_percent} def _find_salary_mean_and_median(self) -> Dict[str, Union[int, float]]: """Найди медианную, среднюю, среднюю максимальную и средней минимальную зарплаты.""" salaries_min = [] salaries_max = [] for i in range(len(self.__df)): # Указана зарплата "от" if self.__df.loc[i, 'salary'].split()[0] == 'от': salaries_min.append(int(self.__df.loc[i, 'salary'].split()[1])) # Указана зарплата "до" elif self.__df.loc[i, 'salary'].split()[0] == 'до': salaries_max.append(int(self.__df.loc[i, 'salary'].split()[1])) # Указана вилка зарплаты elif len(self.__df.loc[i, 'salary'].split()[0].split('-')) == 2: fork = self.__df.loc[i, 'salary'].split()[0].split('-') salaries_min.append(int(fork[0])) salaries_max.append(int(fork[1])) # Зарплата не указана elif self.__df.loc[i, 'salary'] == 'Не указано': pass # Указана фиксированная зарплата else: salaries_min.append(int(self.__df.loc[i, 'salary'].split()[0])) salaries_max.append(int(self.__df.loc[i, 'salary'].split()[0])) salaries_all = salaries_min + salaries_max salary_mean = round(pd.Series(salaries_all).mean()) salary_median = round(pd.Series(salaries_all).median()) min_salary_mean = round(pd.Series(salaries_min).mean()) max_salary_mean = round(pd.Series(salaries_max).mean()) log.info(f'Mean salary: {salary_mean}, median salary: {salary_median}, mean min salary: {min_salary_mean}, ' f'mean max salary: {max_salary_mean}') return {'salary_mean': salary_mean, 'salary_median': salary_median, 'min_salary_mean': min_salary_mean, 'max_salary_mean': max_salary_mean} def _get_parsing_results_df(self) -> None: """Сформируй датафрейм для таблицы "parsing_results".""" data_for_update = {} data_for_update.update(self._find_jobs_without_salary()) data_for_update.update(self._find_salary_mean_and_median()) data_for_update.update({'jobs_count': len(self.__df), 'date': datetime.datetime.now().strftime("%Y-%m-%d"), 'time_parse': self.__parsing_duration}) df = pd.DataFrame([data_for_update]) df['date'] = pd.to_datetime(df['date']) self.__hh_parsed_data.df_parsing_results = df log.info(f'DataFrame for "parsing_results" table generated') def _get_current_jobs_df(self) -> None: """Сформируй датафрейм для таблицы "current_jobs".""" min_salary = [] max_salary = [] df = self.__df.copy().reset_index(drop=True) for i in range(len(df)): # Указана зарплата "от" if df.loc[i, 'salary'].split()[0] == 'от': min_salary.append(int(df.loc[i, 'salary'].split()[1])) max_salary.append(int(df.loc[i, 'salary'].split()[1])) # Укащана зарплата "до" elif df.loc[i, 'salary'].split()[0] == 'до': min_salary.append(0) max_salary.append(int(df.loc[i, 'salary'].split()[1])) # Указана вилка зарплаты elif len(df.loc[i, 'salary'].split()[0].split('-')) == 2: fork = df.loc[i, 'salary'].split()[0].split('-') min_salary.append(int(fork[0])) max_salary.append(int(fork[1])) # Зарплата не указана elif df.loc[i, 'salary'] == 'Не указано': min_salary.append(0) max_salary.append(0) # Указана фиксированная зарплата else: min_salary.append(int(df.loc[i, 'salary'].split()[0])) max_salary.append(int(df.loc[i, 'salary'].split()[0])) df['min_salary'] = min_salary df['max_salary'] = max_salary df['mean_salary'] = (df['min_salary'] + df['max_salary']) / 2 df = df.sort_values(['mean_salary', 'max_salary', 'min_salary'], ascending=False).reset_index(drop=True) df['row'] = list(range(1, len(df) + 1)) self.__hh_parsed_data.df_current_jobs = df[['row', 'date', 'title', 'company', 'salary', 'href']] log.info(f'DataFrame for "current_jobs" table generated') def _get_unique_jobs_merged_df(self) -> pd.DataFrame: """Получи сджойненый датафрейм уникальных вакансий из Postgres и результатов парсинга.""" pg_unique_jobs_raw = self.__pg_conn.get_table(table_name='unique_jobs') pg_unique_jobs = self._get_df_from_pgtable(pg_unique_jobs_raw) if pg_unique_jobs is None or pg_unique_jobs.empty: pg_unique_jobs = pd.DataFrame.from_dict({'date': [], 'href': []}) pg_unique_jobs['date'] = pd.to_datetime(pg_unique_jobs['date']) pg_unique_jobs['href'] = pg_unique_jobs['href'].astype(str) r = pd.merge(pg_unique_jobs, self.__df[['date', 'href']], on='href', how='outer') return r @staticmethod def _get_df_from_pgtable(pg_table: ConnPostgreSQL.PgTable) -> Union[pd.DataFrame, None]: """ Получи датафрейм из PgTable. :param pg_table: Таблица Postgres :return: Датафрейм, если есть данные, в противном случае - None """ if not pg_table: return df_from_pg = pd.DataFrame() for df in pg_table.table_data: df_from_pg = df_from_pg.append(df) return df_from_pg def _get_unique_jobs_df(self) -> None: """Сформируй датафрейм для таблицы "unique_jobs".""" df_merged = self._get_unique_jobs_merged_df() df_merged = df_merged[pd.isnull(df_merged['date_x'])][['date_y', 'href']].reset_index(drop=True) df_merged.columns = ['date', 'href'] self.__hh_parsed_data.df_unique_jobs = df_merged log.info(f'DataFrame for "unique_jobs" table generated') def _get_unique_closed_jobs_df(self) -> None: """Сформируй датафрейм для таблицы "unique_closed_jobs".""" df_merged = self._get_unique_jobs_merged_df() df_merged = df_merged[pd.isnull(df_merged['date_y'])].reset_index(drop=True) df_merged.columns = ['publication_date', 'href', 'closing_date'] df_merged['closing_date'] = datetime.datetime.now().strftime("%Y-%m-%d") df_merged['href'] = df_merged['href'].astype(str) df_merged['closing_date'] = pd.to_datetime(df_merged['closing_date']) df_merged['publication_date'] = pd.to_datetime(df_merged['publication_date']) df_merged['date_diff'] = (df_merged['closing_date'] - df_merged['publication_date']).dt.days.astype(int) pg_unique_closed_jobs_raw = self.__pg_conn.get_table(table_name='unique_closed_jobs') pg_unique_closed_jobs = self._get_df_from_pgtable(pg_unique_closed_jobs_raw) if pg_unique_closed_jobs is None or pg_unique_closed_jobs.empty: pg_unique_closed_jobs = pd.DataFrame().from_dict({ 'href': [], 'publication_date': [], 'closing_date': [], 'date_diff': [] }) pg_unique_closed_jobs['closing_date'] = pd.to_datetime(pg_unique_closed_jobs['closing_date']) pg_unique_closed_jobs['publication_date'] = pd.to_datetime(pg_unique_closed_jobs['publication_date']) pg_unique_closed_jobs['date_diff'] = pg_unique_closed_jobs['date_diff'].astype(int) pg_unique_closed_jobs['href'] = pg_unique_closed_jobs['href'].astype(str) df_merged_closed_jobs = pd.merge(pg_unique_closed_jobs, df_merged, on='href', how='outer') df_merged_closed_jobs = df_merged_closed_jobs[pd.isnull(df_merged_closed_jobs['closing_date_x'])] df_merged_closed_jobs = df_merged_closed_jobs[['href', 'publication_date_y', 'closing_date_y', 'date_diff_y']]\ .reset_index(drop=True) df_merged_closed_jobs.columns = ['href', 'publication_date', 'closing_date', 'date_diff'] df_merged_closed_jobs['date_diff'] = df_merged_closed_jobs['date_diff'].astype(int) self.__hh_parsed_data.df_unique_closed_jobs = df_merged_closed_jobs log.info(f'DataFrame for "unique_closed_jobs" table generated')
[ "logging.getLogger", "pandas.isnull", "pandas.Series", "requests.Session", "time.monotonic", "pandas.merge", "urllib.parse.quote", "pandas.DataFrame.from_dict", "bs4.BeautifulSoup", "datetime.datetime.now", "pandas.DataFrame", "random.random", "pandas.to_datetime", "re.search" ]
[((264, 291), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (281, 291), False, 'import logging\n'), ((1178, 1196), 'requests.Session', 'requests.Session', ([], {}), '()\n', (1194, 1196), False, 'import requests\n'), ((3593, 3609), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (3607, 3609), False, 'import time\n'), ((4783, 4815), 'pandas.DataFrame', 'pd.DataFrame', (['raw_vacancies_data'], {}), '(raw_vacancies_data)\n', (4795, 4815), True, 'import pandas as pd\n'), ((5113, 5154), 'pandas.to_datetime', 'pd.to_datetime', (["df['date']"], {'dayfirst': '(True)'}), "(df['date'], dayfirst=True)\n", (5127, 5154), True, 'import pandas as pd\n'), ((5901, 5959), 're.search', 're.search', (['self.__search_regex', 'title'], {'flags': 're.IGNORECASE'}), '(self.__search_regex, title, flags=re.IGNORECASE)\n', (5910, 5959), False, 'import re\n'), ((12876, 12907), 'pandas.DataFrame', 'pd.DataFrame', (['[data_for_update]'], {}), '([data_for_update])\n', (12888, 12907), True, 'import pandas as pd\n'), ((12929, 12955), 'pandas.to_datetime', 'pd.to_datetime', (["df['date']"], {}), "(df['date'])\n", (12943, 12955), True, 'import pandas as pd\n'), ((15474, 15551), 'pandas.merge', 'pd.merge', (['pg_unique_jobs', "self.__df[['date', 'href']]"], {'on': '"""href"""', 'how': '"""outer"""'}), "(pg_unique_jobs, self.__df[['date', 'href']], on='href', how='outer')\n", (15482, 15551), True, 'import pandas as pd\n'), ((15921, 15935), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (15933, 15935), True, 'import pandas as pd\n'), ((16985, 17026), 'pandas.to_datetime', 'pd.to_datetime', (["df_merged['closing_date']"], {}), "(df_merged['closing_date'])\n", (16999, 17026), True, 'import pandas as pd\n'), ((17067, 17112), 'pandas.to_datetime', 'pd.to_datetime', (["df_merged['publication_date']"], {}), "(df_merged['publication_date'])\n", (17081, 17112), True, 'import pandas as pd\n'), ((18128, 18194), 'pandas.merge', 'pd.merge', (['pg_unique_closed_jobs', 'df_merged'], {'on': '"""href"""', 'how': '"""outer"""'}), "(pg_unique_closed_jobs, df_merged, on='href', how='outer')\n", (18136, 18194), True, 'import pandas as pd\n'), ((1055, 1080), 'urllib.parse.quote', 'quote', (['self.__search_text'], {}), '(self.__search_text)\n', (1060, 1080), False, 'from urllib.parse import quote\n'), ((2905, 2944), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""lxml"""'], {}), "(response.content, 'lxml')\n", (2918, 2944), False, 'from bs4 import BeautifulSoup\n'), ((6907, 6930), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (6928, 6930), False, 'import datetime\n'), ((15265, 15313), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (["{'date': [], 'href': []}"], {}), "({'date': [], 'href': []})\n", (15287, 15313), True, 'import pandas as pd\n'), ((15351, 15389), 'pandas.to_datetime', 'pd.to_datetime', (["pg_unique_jobs['date']"], {}), "(pg_unique_jobs['date'])\n", (15365, 15389), True, 'import pandas as pd\n'), ((17745, 17798), 'pandas.to_datetime', 'pd.to_datetime', (["pg_unique_closed_jobs['closing_date']"], {}), "(pg_unique_closed_jobs['closing_date'])\n", (17759, 17798), True, 'import pandas as pd\n'), ((17855, 17912), 'pandas.to_datetime', 'pd.to_datetime', (["pg_unique_closed_jobs['publication_date']"], {}), "(pg_unique_closed_jobs['publication_date'])\n", (17869, 17912), True, 'import pandas as pd\n'), ((18249, 18299), 'pandas.isnull', 'pd.isnull', (["df_merged_closed_jobs['closing_date_x']"], {}), "(df_merged_closed_jobs['closing_date_x'])\n", (18258, 18299), True, 'import pandas as pd\n'), ((4028, 4067), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""lxml"""'], {}), "(response.content, 'lxml')\n", (4041, 4067), False, 'from bs4 import BeautifulSoup\n'), ((5291, 5307), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (5305, 5307), False, 'import time\n'), ((16846, 16869), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (16867, 16869), False, 'import datetime\n'), ((6804, 6827), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (6825, 6827), False, 'import datetime\n'), ((11775, 11798), 'pandas.Series', 'pd.Series', (['salaries_all'], {}), '(salaries_all)\n', (11784, 11798), True, 'import pandas as pd\n'), ((11837, 11860), 'pandas.Series', 'pd.Series', (['salaries_all'], {}), '(salaries_all)\n', (11846, 11860), True, 'import pandas as pd\n'), ((11903, 11926), 'pandas.Series', 'pd.Series', (['salaries_min'], {}), '(salaries_min)\n', (11912, 11926), True, 'import pandas as pd\n'), ((11967, 11990), 'pandas.Series', 'pd.Series', (['salaries_max'], {}), '(salaries_max)\n', (11976, 11990), True, 'import pandas as pd\n'), ((16682, 16712), 'pandas.isnull', 'pd.isnull', (["df_merged['date_y']"], {}), "(df_merged['date_y'])\n", (16691, 16712), True, 'import pandas as pd\n'), ((17515, 17529), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (17527, 17529), True, 'import pandas as pd\n'), ((6963, 6986), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (6984, 6986), False, 'import datetime\n'), ((8771, 8786), 'random.random', 'random.random', ([], {}), '()\n', (8784, 8786), False, 'import random\n'), ((12745, 12768), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (12766, 12768), False, 'import datetime\n'), ((16237, 16267), 'pandas.isnull', 'pd.isnull', (["df_merged['date_x']"], {}), "(df_merged['date_x'])\n", (16246, 16267), True, 'import pandas as pd\n')]
from bluesky.plan_patterns import spiral_square_pattern import time as ttime import numpy as np import bluesky.plans as bp from bluesky.plans import rel_spiral_square from ophyd.sim import NullStatus # def sample_spiral_scan(): # detectors = [apb_ave] # # return general_spiral_scan(detectors, giantxy.x, giantxy.y, 15, 15, 15, 15, time_step=0.1) # channels = [apb_ave.ch1, apb_ave.ch2, apb_ave.ch3, apb_ave.ch4] # offsets = [apb.ch1_offset, apb.ch2_offset, apb.ch3_offset, apb.ch4_offset, ] # plan = rel_spiral_square(detectors, giantxy.x, giantxy.y, 15, 15, 15, 15) # time_step = 0.1 # samples = 250 * (np.ceil(time_step * 10443 / 250)) # hn I forget what that does... let's look into the new PB OPI # yield from bps.abs_set(apb_ave.sample_len, time_step*1e3, wait=True) # yield from bps.abs_set(apb_ave.wf_len, time_step*1e3, wait=True) # yield from bps.abs_set(apb_ave.divide, 374, wait=True) # if hasattr(detector, 'kickoff'): # plan_with_flyers = bpp.fly_during_wrapper(plan, [detectors]) # uid = (yield from plan) # table = db[uid].table() # row_num = table[detector.volt.name].idxmin() # x_pos = table['giantxy_x'][row_num] # y_pos = table['giantxy_y'][row_num] def general_spiral_scan(detectors_list, *, motor1=giantxy.x, motor2=giantxy.y, motor1_range=15, motor2_range=15, motor1_nsteps=15, motor2_nsteps=15, time_step=0.1, **kwargs): sys.stdout = kwargs.pop('stdout', sys.stdout) print(f'Dets {detectors_list}') print(f'Motors {motor1}, {motor2}') plan = rel_spiral_square(detectors_list, motor1, motor2, motor1_range, motor2_range, motor1_nsteps, motor2_nsteps, md={"plan_name": "spiral scan"}) if apb_ave in detectors_list: print('Preparing pizzabox') cur_divide_value = apb_ave.divide.value cur_sample_len = apb_ave.sample_len.value cur_wf_len = apb_ave.wf_len.value print('[General Spiral Scan] Starting scan...') yield from bps.abs_set(apb_ave.divide, 374, wait=True) yield from bps.abs_set(apb_ave.sample_len, int(time_step * 1e3), wait=True) yield from bps.abs_set(apb_ave.wf_len, int(time_step * 1e3), wait=True) uid = (yield from plan) if apb_ave in detectors_list: print('Returning the pizzabox to its original state') yield from bps.abs_set(apb_ave.divide, cur_divide_value, wait=True) yield from bps.abs_set(apb_ave.sample_len, cur_sample_len, wait=True) yield from bps.abs_set(apb_ave.wf_len, cur_wf_len, wait=True) return uid from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D def get_mus(): data = db[-1].table() x = data['giantxy_x'] y = data['giantxy_y'] mut = np.log(data['apb_ave_ch1_mean']/data['apb_ave_ch2_mean']) muf = data['apb_ave_ch4_mean']/data['apb_ave_ch1_mean'] return x,y, mut, muf def analyze_surface(): x, y, mut, muf = get_mus() plot_xyz(x, y, mut) plot_xyz(x, y, muf) def com(a_orig, w_orig, mask=None): a = a_orig.copy() w = w_orig.copy() if mask is not None: a = a[mask] w = w[mask] return np.sum(a * w)/np.sum(w) def plot_xyz(x, y, z, r1=5, r2=(13.4/2-1)): fig = plt.figure() # ax = fig.gca(projection='3d') # ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True, cmap=plt.cm.Spectral) ax = fig.gca() x_im_center = x.iloc[0] y_im_center = y.iloc[0] # R = r1 #13.4/2-1 xy_mask = (np.sqrt(np.abs(x - x_im_center)**2 + np.abs(y - y_im_center)**2) < r1) x_ho_com = com(x, z.max() - z, ~xy_mask) y_ho_com = com(y, z.max() - z, ~xy_mask) xy_mask_recen = (np.sqrt(np.abs(x - x_ho_com) ** 2 + np.abs(y - y_ho_com) ** 2) < r2) # x_max = x[xy_mask_recen][np.argmax(z[xy_mask_recen])] # y_max = y[xy_mask_recen][np.argmax(z[xy_mask_recen])] x_max = com(x, (z - z.min())**2, xy_mask_recen) y_max = com(y, (z - z.min())**2, xy_mask_recen) ax.tricontourf(x, y, z, 50) ax.plot(x_im_center, y_im_center, 'ro', ms=25) ax.plot(x_ho_com, y_ho_com, 'bx', ms=25, markeredgewidth=5) ax.plot(x_max, y_max, 'm+', ms=25, markeredgewidth=5) # plt.plot(x[xy_mask], y[xy_mask], 'g.', alpha=0.5) # plt.plot(x[~xy_mask], y[~xy_mask], 'r.', alpha=0.5) # plt.show() class SnakeFlyer(): def __init__(self, det, pbs, motor_stage): self.name = 'snake_flyer' self.parent = None self.det = det self.pbs = pbs # a list of passed pizza-boxes self.motor_stage = motor_stage self._motor_status = None self.traj = None def _motor_snaker(self, motor_x=None, range_x=None, motor_y=None, range_y=None): """Snake tragectory for flyer. :param motor_x: ophyd object for motor :param range_x: range in motor units :param motor_y: ophyd object for motor :param range_y: range in motor units :return: None """ # Read start positions. start_pos_x = motor_x.user_readback.get() start_pos_y = motor_y.user_readback.get() step = 1 # We need the grid scan here to get the tragectory. plan = bp.rel_grid_scan([], motor_y, -range_y / 2, range_y / 2, (range_y / step + 1), motor_x, -range_x / 2, range_x / 2, 2, True # snake=True ) # This is adapted from plot_raster_scan in bluesky. cur_x = cur_y = None self.traj = [] for msg in plan: cmd = msg.command if cmd == 'set': if msg.obj.name == motor_x.name: cur_x = msg.args[0] if msg.obj.name == motor_y.name: cur_y = msg.args[0] elif cmd == 'save': self.traj.append((cur_x, cur_y)) # Move motors along the trajectory. for (x, y) in self.traj: print(x, y) if abs(motor_x.user_readback.get() - x) > 5e-3: print(f"Moving {motor_x.name}") # .move blocks the operation, and waits until the motor arrives to the target position. motor_x.move(x) if abs(motor_y.user_readback.get() - y) > 5e-3: print(f"Moving {motor_y.name}") # .move blocks the operation, and waits until the motor arrives to the target position. motor_y.move(y) # Move back to the original position both motors simultaneously. self._motor_status = motor_x.set(start_pos_x) self._motor_status &= motor_y.set(start_pos_y) def kickoff(self, *args, **kwargs): for pb in self.pbs: pb.stage() pb.kickoff() self.det.stage() # Start apb after encoder pizza-boxes, which will trigger the motor. self.det.stream.set(1) self._motor_snaker(motor_x=self.motor_stage.x, range_x=10, motor_y=self.motor_stage.y, range_y=4) print(f"Motor status in kickoff: {self._motor_status}") return NullStatus() def complete(self): print(f"Motor status in complete: {self._motor_status}") def callback_det(value, old_value, **kwargs): if int(round(old_value)) == 1 and int(round(value)) == 0: print(f'callback_det {ttime.ctime()}') return True else: return False streaming_st = SubscriptionStatus(self.det.streaming, callback_det) def callback_motor(): print(f'callback_motor {ttime.ctime()}') for pb in self.pbs: pb.complete() # TODO: see if this set is still needed (also called in self.det.unstage()) self.det.stream.put(0) self.det.complete() self._motor_status.add_callback(callback_motor) # Jdun! return streaming_st & self._motor_status def describe_collect(self): return_dict = {self.det.name: {f'{self.det.name}': {'source': 'APB', 'dtype': 'array', 'shape': [-1, -1], 'filename_bin': self.det.filename_bin, 'filename_txt': self.det.filename_txt, 'external': 'FILESTORE:'}}} # Also do it for all pizza-boxes for pb in self.pbs: return_dict[pb.name] = pb.describe_collect()[pb.name] # Add a stream for the motor positions. return_dict[self.motor_stage.name] = {f'{self.motor_stage.x.name}': {'source': 'SNAKE', 'dtype': 'number', 'shape': []}, f'{self.motor_stage.y.name}': {'source': 'SNAKE', 'dtype': 'number', 'shape': []} } return return_dict def collect_asset_docs(self): yield from self.det.collect_asset_docs() for pb in self.pbs: yield from pb.collect_asset_docs() def collect(self): print(f"Motor status in collect: {self._motor_status}") self.det.unstage() for pb in self.pbs: pb.unstage() def collect_all(): for pb in self.pbs: yield from pb.collect() yield from self.det.collect() # Collect docs for motor positions. now = ttime.time() for (x, y) in self.traj: data = {f"{self.motor_stage.x.name}": x, f"{self.motor_stage.y.name}": y} yield {'data': data, 'timestamps': {key: now for key in data}, 'time': now, 'filled': {key: False for key in data}} return collect_all() snake_flyer = SnakeFlyer(det=apb_stream, pbs=[pb4.enc3, pb4.enc4], motor_stage=giantxy)
[ "numpy.abs", "time.ctime", "bluesky.plans.rel_spiral_square", "numpy.log", "ophyd.sim.NullStatus", "bluesky.plans.rel_grid_scan", "numpy.sum", "matplotlib.pyplot.figure", "time.time" ]
[((1561, 1710), 'bluesky.plans.rel_spiral_square', 'rel_spiral_square', (['detectors_list', 'motor1', 'motor2', 'motor1_range', 'motor2_range', 'motor1_nsteps', 'motor2_nsteps'], {'md': "{'plan_name': 'spiral scan'}"}), "(detectors_list, motor1, motor2, motor1_range,\n motor2_range, motor1_nsteps, motor2_nsteps, md={'plan_name': 'spiral scan'}\n )\n", (1578, 1710), False, 'from bluesky.plans import rel_spiral_square\n'), ((2814, 2873), 'numpy.log', 'np.log', (["(data['apb_ave_ch1_mean'] / data['apb_ave_ch2_mean'])"], {}), "(data['apb_ave_ch1_mean'] / data['apb_ave_ch2_mean'])\n", (2820, 2873), True, 'import numpy as np\n'), ((3301, 3313), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3311, 3313), True, 'from matplotlib import pyplot as plt\n'), ((3219, 3232), 'numpy.sum', 'np.sum', (['(a * w)'], {}), '(a * w)\n', (3225, 3232), True, 'import numpy as np\n'), ((3233, 3242), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (3239, 3242), True, 'import numpy as np\n'), ((5296, 5421), 'bluesky.plans.rel_grid_scan', 'bp.rel_grid_scan', (['[]', 'motor_y', '(-range_y / 2)', '(range_y / 2)', '(range_y / step + 1)', 'motor_x', '(-range_x / 2)', '(range_x / 2)', '(2)', '(True)'], {}), '([], motor_y, -range_y / 2, range_y / 2, range_y / step + 1,\n motor_x, -range_x / 2, range_x / 2, 2, True)\n', (5312, 5421), True, 'import bluesky.plans as bp\n'), ((7199, 7211), 'ophyd.sim.NullStatus', 'NullStatus', ([], {}), '()\n', (7209, 7211), False, 'from ophyd.sim import NullStatus\n'), ((9927, 9939), 'time.time', 'ttime.time', ([], {}), '()\n', (9937, 9939), True, 'import time as ttime\n'), ((3558, 3581), 'numpy.abs', 'np.abs', (['(x - x_im_center)'], {}), '(x - x_im_center)\n', (3564, 3581), True, 'import numpy as np\n'), ((3610, 3633), 'numpy.abs', 'np.abs', (['(y - y_im_center)'], {}), '(y - y_im_center)\n', (3616, 3633), True, 'import numpy as np\n'), ((3765, 3785), 'numpy.abs', 'np.abs', (['(x - x_ho_com)'], {}), '(x - x_ho_com)\n', (3771, 3785), True, 'import numpy as np\n'), ((3822, 3842), 'numpy.abs', 'np.abs', (['(y - y_ho_com)'], {}), '(y - y_ho_com)\n', (3828, 3842), True, 'import numpy as np\n'), ((7700, 7713), 'time.ctime', 'ttime.ctime', ([], {}), '()\n', (7711, 7713), True, 'import time as ttime\n'), ((7465, 7478), 'time.ctime', 'ttime.ctime', ([], {}), '()\n', (7476, 7478), True, 'import time as ttime\n')]
#-*- coding: UTF-8 -*- from passlib.hash import sha256_crypt from marshmallow_sqlalchemy import SQLAlchemyAutoSchema from sqlalchemy import * from sqlalchemy.types import * from sqlalchemy.orm import * from ..engine.db import Base from .group import Group class Company(Base): __table_args__ = { 'schema': 'company' } __tablename__ = 'company_info' company_id = Column(Integer, primary_key=True, autoincrement=True) company_name = Column(String(45), nullable=True) company_post = Column(String(8)) company_city = Column(Integer) company_address = Column(String(150)) company_address_kana = Column(String(200)) company_logo = Column(JSON) company_home_page = Column(String(150)) company_copy_right = Column(String(150)) company_global_ip = Column(String(120)) company_cti_flag = Column(Integer) company_memo = Column(String(500)) company_global_locale = Column(Integer) company_theme = Column(String(15)) company_use_system_auth = Column(Integer) company_use_api = Column(Integer) company_start_use_date = Column(DateTime) company_basic_login_id = Column(String(30)) company_basic_password = Column(String(70)) company_deleted = Column(Integer) updated_id = Column(Integer) updated_time = Column(DateTime) groups = relationship("Group") def __init__(self, *args): engine = args[0] self.db = engine Base.metadata.create_all(self.db.engine) def __repr__(self): return '<Company %r>' % self.company_id def gets(self): return self.db.session.query(Company).all() # if objs is not None: # for o in objs: # o.company_basic_password = '******' # return objs def get(self, id): return self.db.session.query(Company).filter(Company.company_id==id).first() # if o is not None: # o.company_basic_password = '******' # return o def get_basic(self, id, pw): if id is None or pw is None: return None # newH = sha256_crypt.using(rounds=10000).hash(pw) # print(newH) # print(sha256_crypt.verify(pw, '$5$rounds=10000$BdgUHFSOc1D4nONw$qhmq23aKTI9PBqZsXFJqqsqPDUsUf0zuwseCO1ArnO0')) result = self.db.session.query(Company).filter( and_(Company.company_deleted==0, Company.company_basic_login_id==id)).first() if result is not None: verify = sha256_crypt.verify(pw, '$5$rounds=10000' + result.company_basic_password) if verify == True: return result return None return None class CompanyBasic(SQLAlchemyAutoSchema): class Meta: model = Company load_instance = True fields = ('company_id',) class CompanyMode(SQLAlchemyAutoSchema): class Meta: model = Company load_instance = True fields = ( 'company_id', 'company_name', 'company_logo', 'company_theme', 'company_global_locale', 'company_cti_flag', 'company_use_api', 'company_copy_right', 'company_home_page',) class CompanySchema(SQLAlchemyAutoSchema): class Meta: model = Company
[ "passlib.hash.sha256_crypt.verify" ]
[((2452, 2526), 'passlib.hash.sha256_crypt.verify', 'sha256_crypt.verify', (['pw', "('$5$rounds=10000' + result.company_basic_password)"], {}), "(pw, '$5$rounds=10000' + result.company_basic_password)\n", (2471, 2526), False, 'from passlib.hash import sha256_crypt\n')]
import logging import os import tempfile import warnings from configparser import ConfigParser from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence, Type, Union from articat.utils.class_or_instance_method import class_or_instance_method logger = logging.getLogger(__name__) if TYPE_CHECKING: from articat.catalog import Catalog class ArticatMode(str, Enum): local = "local" gcp_datastore = "gcp_datastore" class ArticatConfig: """ Articat config handler. Allows to read configuration from config files, and config dictionaries. See python's `configparser` for context. This class supports "global"/default config and instances of configuration which you can supply to Artifact to have custom configured Artifact objects, to for example materialise certain Artifacts in custom locations. """ # NOTE: the order in this list matters, and defines the override order default_config_paths = [ Path.home().joinpath(".config", "articat", "articat.cfg").as_posix(), Path.cwd().joinpath("articat.cfg").as_posix(), ] _config: ConfigParser = ConfigParser() def __init__( self, config_paths: Sequence[str] = [], config_dict: Mapping[str, Mapping[str, Any]] = {}, ) -> None: self._config = self._read_config( config_paths=config_paths, config_dict=config_dict ) @staticmethod def _read_config( config_paths: Sequence[str], config_dict: Mapping[str, Mapping[str, Any]] ) -> ConfigParser: config = ConfigParser() read = config.read(config_paths) if len(read) == 0: logger.warning(f"No configuration files found, searched in {config_paths}") config.read_dict(config_dict) return config @classmethod def register_config( cls, config_paths: Optional[Sequence[str]] = None, config_dict: Mapping[str, Mapping[str, Any]] = {}, ) -> "Type[ArticatConfig]": """ Register configuration from config paths and config dictionary. Config paths are read in order, `config_dict` is applied after config paths. This methods registers "global"/default configuration, use constructor to get an instance of a config. You can also specify the configuration location via env variable: ARTICAT_CONFIG. `config_paths` resolution order: * function argument * `ARTICAT_CONFIG` env variable * default paths """ if config_paths is None: env_config_path = os.environ.get("ARTICAT_CONFIG") if env_config_path is not None: config_paths = [env_config_path] else: config_paths = cls.default_config_paths cls._config = cls._read_config( config_paths=config_paths, config_dict=config_dict ) return cls @class_or_instance_method def mode(self) -> ArticatMode: """ Articat mode. Currently supported: `local`, `gcp`. Defaults to: `local` """ return ArticatMode(self._config.get("main", "mode", fallback=ArticatMode.local)) @class_or_instance_method def catalog(self) -> "Type[Catalog]": """Returns the Catalog implementation for given mode""" if self.mode() == ArticatMode.local: from articat.catalog_local import CatalogLocal return CatalogLocal elif self.mode() == ArticatMode.gcp_datastore: from articat.catalog_datastore import CatalogDatastore return CatalogDatastore else: raise ValueError(f"Unknown catalog for mode: {self.mode}") @class_or_instance_method def local_db_dir(self) -> str: """ Location of the local DB, `local` mode only. Defaults to: ~/.config/articat/local """ return self._config.get( "main", "local_db_dir", fallback=Path.home().joinpath(".config", "articat", "local").as_posix(), ) @class_or_instance_method def gcp_project(self) -> str: """Google Cloud Platform (GCP) project, for `gcp` mode only""" return self._config["gcp"]["project"] @class_or_instance_method def bq_prod_dataset(self) -> str: """BigQuery (BQ) production dataset, for `gcp` mode only""" return self._config["bq"]["prod_dataset"] @class_or_instance_method def bq_tmp_dataset(self) -> str: """BigQuery (BQ) temp dataset, for `gcp` mode only""" return self._config["bq"]["tmp_dataset"] @class_or_instance_method def bq_dev_dataset(self) -> str: """BigQuery (BQ) development dataset, for `gcp` mode only""" return self._config["bq"]["dev_dataset"] @classmethod def _set_option( cls, c: ConfigParser, section: str, option: str, value: Any ) -> None: if not c.has_section(section): c.add_section(section) c.set(section, option, value) @class_or_instance_method def fs_tmp_prefix(self) -> str: """File system (FS) temporary/staging location""" try: return self._config["fs"]["tmp_prefix"] except KeyError: r = tempfile.mkdtemp(suffix="artifact_temp_dir_") self._set_option(self._config, "fs", "tmp_prefix", r) warnings.warn( f"FSArtifact temp directory not configured, assuming local mode, using temp directory: {r}" ) return r @class_or_instance_method def fs_dev_prefix(self) -> str: """File system (FS) development location""" try: return self._config["fs"]["dev_prefix"] except KeyError: r = Path.cwd().joinpath(".articat_catalog", "dev").as_posix() self._set_option(self._config, "fs", "dev_prefix", r) warnings.warn( f"FSArtifact development directory not configured, assuming local mode, using cwd: {r}" ) return r @class_or_instance_method def fs_prod_prefix(self) -> str: """File system (FS) production/final location""" try: return self._config["fs"]["prod_prefix"] except KeyError: r = Path.cwd().joinpath(".articat_catalog", "prod").as_posix() self._set_option(self._config, "fs", "prod_prefix", r) warnings.warn( f"FSArtifact production directory not configured, assuming local mode, using cwd: {r}" ) return r class ConfigMixin: """ArticatConfig mixin/trait""" _config: Union[Type[ArticatConfig], ArticatConfig] @class_or_instance_method def config(self) -> Union[Type[ArticatConfig], ArticatConfig]: """Get Articat config object""" return self._config
[ "logging.getLogger", "configparser.ConfigParser", "pathlib.Path.cwd", "pathlib.Path.home", "os.environ.get", "tempfile.mkdtemp", "warnings.warn" ]
[((309, 336), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (326, 336), False, 'import logging\n'), ((1171, 1185), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1183, 1185), False, 'from configparser import ConfigParser\n'), ((1613, 1627), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1625, 1627), False, 'from configparser import ConfigParser\n'), ((2635, 2667), 'os.environ.get', 'os.environ.get', (['"""ARTICAT_CONFIG"""'], {}), "('ARTICAT_CONFIG')\n", (2649, 2667), False, 'import os\n'), ((5315, 5360), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'suffix': '"""artifact_temp_dir_"""'}), "(suffix='artifact_temp_dir_')\n", (5331, 5360), False, 'import tempfile\n'), ((5439, 5555), 'warnings.warn', 'warnings.warn', (['f"""FSArtifact temp directory not configured, assuming local mode, using temp directory: {r}"""'], {}), "(\n f'FSArtifact temp directory not configured, assuming local mode, using temp directory: {r}'\n )\n", (5452, 5555), False, 'import warnings\n'), ((5958, 6070), 'warnings.warn', 'warnings.warn', (['f"""FSArtifact development directory not configured, assuming local mode, using cwd: {r}"""'], {}), "(\n f'FSArtifact development directory not configured, assuming local mode, using cwd: {r}'\n )\n", (5971, 6070), False, 'import warnings\n'), ((6482, 6593), 'warnings.warn', 'warnings.warn', (['f"""FSArtifact production directory not configured, assuming local mode, using cwd: {r}"""'], {}), "(\n f'FSArtifact production directory not configured, assuming local mode, using cwd: {r}'\n )\n", (6495, 6593), False, 'import warnings\n'), ((1012, 1023), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (1021, 1023), False, 'from pathlib import Path\n'), ((1090, 1100), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (1098, 1100), False, 'from pathlib import Path\n'), ((4042, 4053), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (4051, 4053), False, 'from pathlib import Path\n'), ((5822, 5832), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (5830, 5832), False, 'from pathlib import Path\n'), ((6344, 6354), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (6352, 6354), False, 'from pathlib import Path\n')]
import cv2 import time import os import matplotlib.pyplot as plt import torch from torch import nn import torchvision.models as models import torchvision.transforms as transforms import numpy as np savepath='./color_heatmap' if not os.path.exists(savepath): os.mkdir(savepath) def draw_features(width, height, x, savename): tic = time.time() fig = plt.figure(figsize=(16, 16)) fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.05, hspace=0.05) for i in range(width * height): plt.subplot(height, width, i + 1) plt.axis('off') img = x[0, i, :, :] pmin = np.min(img) pmax = np.max(img) img = ((img - pmin) / (pmax - pmin + 0.000001)) * 255 # float在[0,1]之间,转换成0-255 img = img.astype(np.uint8) # 转成unit8 img = cv2.applyColorMap(img, cv2.COLORMAP_JET) # 生成heat map img = img[:, :, ::-1] # 注意cv2(BGR)和matplotlib(RGB)通道是相反的 plt.imshow(img) print("{}/{}".format(i, width * height)) fig.savefig(savename, dpi=100) fig.clf() plt.close() print("time:{}".format(time.time() - tic)) class ft_net(nn.Module): def __init__(self): super(ft_net, self).__init__() model_ft = models.resnet101(pretrained=True) self.model = model_ft def forward(self, x): if True: # draw features or not x = self.model.conv1(x) draw_features(8, 8, x.cpu().numpy(), "{}/f1_conv1.png".format(savepath)) x = self.model.bn1(x) draw_features(8, 8, x.cpu().numpy(), "{}/f2_bn1.png".format(savepath)) x = self.model.relu(x) draw_features(8, 8, x.cpu().numpy(), "{}/f3_relu.png".format(savepath)) x = self.model.maxpool(x) draw_features(8, 8, x.cpu().numpy(), "{}/f4_maxpool.png".format(savepath)) x = self.model.layer1(x) draw_features(16, 16, x.cpu().numpy(), "{}/f5_layer1.png".format(savepath)) x = self.model.layer2(x) draw_features(16, 32, x.cpu().numpy(), "{}/f6_layer2.png".format(savepath)) x = self.model.layer3(x) draw_features(32, 32, x.cpu().numpy(), "{}/f7_layer3.png".format(savepath)) x = self.model.layer4(x) draw_features(32, 32, x.cpu().numpy()[:, 0:1024, :, :], "{}/f8_layer4_1.png".format(savepath)) draw_features(32, 32, x.cpu().numpy()[:, 1024:2048, :, :], "{}/f8_layer4_2.png".format(savepath)) x = self.model.avgpool(x) plt.plot(np.linspace(1, 2048, 2048), x.cpu().numpy()[0, :, 0, 0]) plt.savefig("{}/f9_avgpool.png".format(savepath)) plt.clf() plt.close() x = x.view(x.size(0), -1) x = self.model.fc(x) plt.plot(np.linspace(1, 1000, 1000), x.cpu().numpy()[0, :]) plt.savefig("{}/f10_fc.png".format(savepath)) plt.clf() plt.close() else: x = self.model.conv1(x) x = self.model.bn1(x) x = self.model.relu(x) x = self.model.maxpool(x) x = self.model.layer1(x) x = self.model.layer2(x) x = self.model.layer3(x) x = self.model.layer4(x) x = self.model.avgpool(x) x = x.view(x.size(0), -1) x = self.model.fc(x) return x model = ft_net().cuda() # pretrained_dict = resnet50.state_dict() # pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} # model_dict.update(pretrained_dict) # net.load_state_dict(model_dict) model.eval() img = cv2.imread('example.jpg') img = cv2.resize(img, (224, 224)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) img = transform(img).cuda() img = img.unsqueeze(0) with torch.no_grad(): start = time.time() out = model(img) print("total time:{}".format(time.time() - start)) result = out.cpu().numpy() # ind=np.argmax(out.cpu().numpy()) ind = np.argsort(result, axis=1) for i in range(5): print("predict:top {} = cls {} : score {}".format(i + 1, ind[0, 1000 - i - 1], result[0, 1000 - i - 1])) print("done")
[ "numpy.argsort", "matplotlib.pyplot.imshow", "os.path.exists", "numpy.max", "matplotlib.pyplot.close", "numpy.linspace", "os.mkdir", "numpy.min", "matplotlib.pyplot.axis", "torchvision.transforms.ToTensor", "torchvision.models.resnet101", "cv2.cvtColor", "torchvision.transforms.Normalize", ...
[((3632, 3657), 'cv2.imread', 'cv2.imread', (['"""example.jpg"""'], {}), "('example.jpg')\n", (3642, 3657), False, 'import cv2\n'), ((3664, 3691), 'cv2.resize', 'cv2.resize', (['img', '(224, 224)'], {}), '(img, (224, 224))\n', (3674, 3691), False, 'import cv2\n'), ((3698, 3734), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (3710, 3734), False, 'import cv2\n'), ((233, 257), 'os.path.exists', 'os.path.exists', (['savepath'], {}), '(savepath)\n', (247, 257), False, 'import os\n'), ((263, 281), 'os.mkdir', 'os.mkdir', (['savepath'], {}), '(savepath)\n', (271, 281), False, 'import os\n'), ((341, 352), 'time.time', 'time.time', ([], {}), '()\n', (350, 352), False, 'import time\n'), ((363, 391), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 16)'}), '(figsize=(16, 16))\n', (373, 391), True, 'import matplotlib.pyplot as plt\n'), ((1067, 1078), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1076, 1078), True, 'import matplotlib.pyplot as plt\n'), ((3914, 3929), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3927, 3929), False, 'import torch\n'), ((3943, 3954), 'time.time', 'time.time', ([], {}), '()\n', (3952, 3954), False, 'import time\n'), ((4111, 4137), 'numpy.argsort', 'np.argsort', (['result'], {'axis': '(1)'}), '(result, axis=1)\n', (4121, 4137), True, 'import numpy as np\n'), ((532, 565), 'matplotlib.pyplot.subplot', 'plt.subplot', (['height', 'width', '(i + 1)'], {}), '(height, width, i + 1)\n', (543, 565), True, 'import matplotlib.pyplot as plt\n'), ((574, 589), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (582, 589), True, 'import matplotlib.pyplot as plt\n'), ((633, 644), 'numpy.min', 'np.min', (['img'], {}), '(img)\n', (639, 644), True, 'import numpy as np\n'), ((660, 671), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (666, 671), True, 'import numpy as np\n'), ((820, 860), 'cv2.applyColorMap', 'cv2.applyColorMap', (['img', 'cv2.COLORMAP_JET'], {}), '(img, cv2.COLORMAP_JET)\n', (837, 860), False, 'import cv2\n'), ((949, 964), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (959, 964), True, 'import matplotlib.pyplot as plt\n'), ((1236, 1269), 'torchvision.models.resnet101', 'models.resnet101', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1252, 1269), True, 'import torchvision.models as models\n'), ((3772, 3793), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3791, 3793), True, 'import torchvision.transforms as transforms\n'), ((3800, 3854), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (3820, 3854), True, 'import torchvision.transforms as transforms\n'), ((2677, 2686), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2684, 2686), True, 'import matplotlib.pyplot as plt\n'), ((2699, 2710), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2708, 2710), True, 'import matplotlib.pyplot as plt\n'), ((2925, 2934), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2932, 2934), True, 'import matplotlib.pyplot as plt\n'), ((2947, 2958), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2956, 2958), True, 'import matplotlib.pyplot as plt\n'), ((1106, 1117), 'time.time', 'time.time', ([], {}), '()\n', (1115, 1117), False, 'import time\n'), ((2546, 2572), 'numpy.linspace', 'np.linspace', (['(1)', '(2048)', '(2048)'], {}), '(1, 2048, 2048)\n', (2557, 2572), True, 'import numpy as np\n'), ((2804, 2830), 'numpy.linspace', 'np.linspace', (['(1)', '(1000)', '(1000)'], {}), '(1, 1000, 1000)\n', (2815, 2830), True, 'import numpy as np\n'), ((4009, 4020), 'time.time', 'time.time', ([], {}), '()\n', (4018, 4020), False, 'import time\n')]
import torch from torch import nn, distributed as dist from torch.nn import functional as F class LabelSmoothingLoss(nn.Module): def __init__(self, ignore_index, eps=0.1, reduction="mean"): super().__init__() self.ignore_index = ignore_index self.eps = eps self.reduction = reduction def forward(self, output, target): n_class = output.shape[-1] output = F.log_softmax(output, -1) if self.ignore_index > -1: n_class -= 1 true_dist = torch.full_like(output, self.eps / n_class) true_dist.scatter_( 1, target.data.unsqueeze(1), 1 - self.eps + self.eps / n_class ) if self.ignore_index > -1: true_dist[:, self.ignore_index] = 0 padding_mat = target.data == self.ignore_index mask = torch.nonzero(padding_mat, as_tuple=False) if mask.dim() > 0: true_dist.index_fill_(0, mask.squeeze(), 0.0) loss = F.kl_div( output, true_dist.detach(), reduction="sum" if self.reduction != "none" else "none", ) if self.reduction == "none": loss = loss.sum(1) elif self.reduction == "mean": if self.ignore_index > -1: loss = loss / (target.shape[0] - padding_mat.sum().item()) else: loss = loss / target.shape[0] return loss class MixLoss(nn.Module): def __init__(self, eps=0, reduction="mean"): super().__init__() self.eps = eps self.reduction = reduction def forward(self, output, target1, target2, interpolation): n_class = output.shape[-1] output = F.log_softmax(output, -1) true_dist = torch.full_like(output, self.eps / n_class) true1 = true_dist.scatter( 1, target1.data.unsqueeze(1), 1 - self.eps + self.eps / n_class ) true2 = true_dist.scatter( 1, target2.data.unsqueeze(1), 1 - self.eps + self.eps / n_class ) inter = torch.as_tensor(interpolation).unsqueeze(-1) true_dist = inter * true1 + (1 - inter) * true2 loss = F.kl_div( output, true_dist.detach(), reduction="sum" if self.reduction != "none" else "none", ) if self.reduction == "none": loss = loss.sum(1) elif self.reduction == "mean": loss = loss / target1.shape[0] return loss class DINOLoss(nn.Module): def __init__( self, out_dim, n_crop, warmup_teacher_temperature, teacher_temperature, warmup_teacher_epoch, n_epoch, student_temperature=0.1, center_momentum=0.9, ): super().__init__() self.student_temperature = student_temperature self.center_momentum = center_momentum self.n_crop = n_crop self.register_buffer("center", torch.zeros(1, out_dim)) self.teacher_temperature_schedule = torch.cat( ( torch.linspace( warmup_teacher_temperature, teacher_temperature, warmup_teacher_epoch, ), torch.ones(n_epoch - warmup_teacher_epoch) * teacher_temperature, ) ).tolist() def forward(self, student_output, teacher_output, epoch): student_out = student_output / self.student_temperature student_out = student_out.chunk(self.n_crop) temperature = self.teacher_temperature_schedule[epoch] teacher_out = torch.softmax((teacher_output - self.center) / temperature, -1) teacher_out = teacher_out.detach().chunk(2) total_loss = 0 n_loss_term = 0 for i_q, q in enumerate(teacher_out): for v in range(len(student_out)): if v == i_q: continue loss = torch.sum(-q * torch.log_softmax(student_out[v], -1), -1) total_loss += loss.mean() n_loss_term += 1 total_loss /= n_loss_term self.update_center(teacher_output) return total_loss @torch.no_grad() def update_center(self, teacher_out): batch_center = torch.sum(teacher_out, dim=0, keepdim=True) dist.all_reduce(batch_center) batch_center = batch_center / (len(teacher_out) * dist.get_world_size()) self.center.mul_(self.center_momentum).add_( batch_center, alpha=1 - self.center_momentum )
[ "torch.as_tensor", "torch.ones", "torch.log_softmax", "torch.distributed.all_reduce", "torch.full_like", "torch.softmax", "torch.nonzero", "torch.sum", "torch.nn.functional.log_softmax", "torch.no_grad", "torch.zeros", "torch.linspace", "torch.distributed.get_world_size" ]
[((4219, 4234), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4232, 4234), False, 'import torch\n'), ((415, 440), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['output', '(-1)'], {}), '(output, -1)\n', (428, 440), True, 'from torch.nn import functional as F\n'), ((523, 566), 'torch.full_like', 'torch.full_like', (['output', '(self.eps / n_class)'], {}), '(output, self.eps / n_class)\n', (538, 566), False, 'import torch\n'), ((1725, 1750), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['output', '(-1)'], {}), '(output, -1)\n', (1738, 1750), True, 'from torch.nn import functional as F\n'), ((1772, 1815), 'torch.full_like', 'torch.full_like', (['output', '(self.eps / n_class)'], {}), '(output, self.eps / n_class)\n', (1787, 1815), False, 'import torch\n'), ((3636, 3699), 'torch.softmax', 'torch.softmax', (['((teacher_output - self.center) / temperature)', '(-1)'], {}), '((teacher_output - self.center) / temperature, -1)\n', (3649, 3699), False, 'import torch\n'), ((4300, 4343), 'torch.sum', 'torch.sum', (['teacher_out'], {'dim': '(0)', 'keepdim': '(True)'}), '(teacher_out, dim=0, keepdim=True)\n', (4309, 4343), False, 'import torch\n'), ((4352, 4381), 'torch.distributed.all_reduce', 'dist.all_reduce', (['batch_center'], {}), '(batch_center)\n', (4367, 4381), True, 'from torch import nn, distributed as dist\n'), ((842, 884), 'torch.nonzero', 'torch.nonzero', (['padding_mat'], {'as_tuple': '(False)'}), '(padding_mat, as_tuple=False)\n', (855, 884), False, 'import torch\n'), ((2978, 3001), 'torch.zeros', 'torch.zeros', (['(1)', 'out_dim'], {}), '(1, out_dim)\n', (2989, 3001), False, 'import torch\n'), ((2074, 2104), 'torch.as_tensor', 'torch.as_tensor', (['interpolation'], {}), '(interpolation)\n', (2089, 2104), False, 'import torch\n'), ((4440, 4461), 'torch.distributed.get_world_size', 'dist.get_world_size', ([], {}), '()\n', (4459, 4461), True, 'from torch import nn, distributed as dist\n'), ((3089, 3178), 'torch.linspace', 'torch.linspace', (['warmup_teacher_temperature', 'teacher_temperature', 'warmup_teacher_epoch'], {}), '(warmup_teacher_temperature, teacher_temperature,\n warmup_teacher_epoch)\n', (3103, 3178), False, 'import torch\n'), ((3990, 4027), 'torch.log_softmax', 'torch.log_softmax', (['student_out[v]', '(-1)'], {}), '(student_out[v], -1)\n', (4007, 4027), False, 'import torch\n'), ((3271, 3313), 'torch.ones', 'torch.ones', (['(n_epoch - warmup_teacher_epoch)'], {}), '(n_epoch - warmup_teacher_epoch)\n', (3281, 3313), False, 'import torch\n')]
import random import torch import time import os import numpy as np from torch.utils.data import Dataset from functools import partial from .utils import dataset_to_dataloader, max_io_workers from pytorch_transformers.tokenization_bert import BertTokenizer # the following will be shared on other datasets too if not, they should become part of the ListeningDataset # maybe make SegmentedScanDataset with only static functions and then inherit. from .utils import check_segmented_object_order, sample_scan_object, pad_samples, objects_bboxes from .utils import instance_labels_of_context, mean_rgb_unit_norm_transform from ...data_generation.nr3d import decode_stimulus_string class ListeningDataset(Dataset): def __init__(self, references, scans, vocab, max_seq_len, points_per_object, max_distractors, class_to_idx=None, object_transformation=None, visualization=False, feat2dtype=None, num_class_dim=525, evalmode=False): self.references = references self.scans = scans self.vocab = vocab self.max_seq_len = max_seq_len self.points_per_object = points_per_object self.max_distractors = max_distractors self.max_context_size = self.max_distractors + 1 # to account for the target. self.class_to_idx = class_to_idx self.visualization = visualization self.object_transformation = object_transformation self.feat2dtype = feat2dtype self.max_2d_view = 5 self.num_class_dim = num_class_dim self.evalmode = evalmode self.bert_tokenizer = BertTokenizer.from_pretrained( 'bert-base-uncased') assert self.bert_tokenizer.encode(self.bert_tokenizer.pad_token) == [0] if not check_segmented_object_order(scans): raise ValueError def __len__(self): return len(self.references) def get_reference_data(self, index): ref = self.references.loc[index] scan = self.scans[ref['scan_id']] target = scan.three_d_objects[ref['target_id']] tokens = np.array(self.vocab.encode(ref['tokens'], self.max_seq_len), dtype=np.long) is_nr3d = ref['dataset'] == 'nr3d' return scan, target, tokens, ref['tokens'], is_nr3d def prepare_distractors(self, scan, target): target_label = target.instance_label # First add all objects with the same instance-label as the target distractors = [o for o in scan.three_d_objects if (o.instance_label == target_label and (o != target))] # Then all more objects up to max-number of distractors already_included = {target_label} clutter = [o for o in scan.three_d_objects if o.instance_label not in already_included] np.random.shuffle(clutter) distractors.extend(clutter) distractors = distractors[:self.max_distractors] np.random.shuffle(distractors) return distractors def __getitem__(self, index): res = dict() scan, target, tokens, text_tokens, is_nr3d = self.get_reference_data(index) ## BERT tokenize token_inds = torch.zeros(self.max_seq_len, dtype=torch.long) indices = self.bert_tokenizer.encode( ' '.join(text_tokens), add_special_tokens=True) indices = indices[:self.max_seq_len] token_inds[:len(indices)] = torch.tensor(indices) token_num = torch.tensor(len(indices), dtype=torch.long) # Make a context of distractors context = self.prepare_distractors(scan, target) # Add target object in 'context' list target_pos = np.random.randint(len(context) + 1) context.insert(target_pos, target) # sample point/color for them samples = np.array([sample_scan_object(o, self.points_per_object) for o in context]) # mark their classes res['class_labels'] = instance_labels_of_context(context, self.max_context_size, self.class_to_idx) if self.object_transformation is not None: samples, offset = self.object_transformation(samples) res['obj_offset'] = np.zeros((self.max_context_size, offset.shape[1])).astype(np.float32) res['obj_offset'][:len(offset),:] = offset.astype(np.float32) res['context_size'] = len(samples) # take care of padding, so that a batch has same number of N-objects across scans. res['objects'] = pad_samples(samples, self.max_context_size) # Get a mask indicating which objects have the same instance-class as the target. target_class_mask = np.zeros(self.max_context_size, dtype=np.bool) target_class_mask[:len(context)] = [target.instance_label == o.instance_label for o in context] res['target_class'] = self.class_to_idx[target.instance_label] res['target_pos'] = target_pos res['target_class_mask'] = target_class_mask res['tokens'] = tokens res['token_inds'] = token_inds.numpy().astype(np.int64) res['token_num'] = token_num.numpy().astype(np.int64) res['is_nr3d'] = is_nr3d if self.visualization: distrators_pos = np.zeros((6)) # 6 is the maximum context size we used in dataset collection object_ids = np.zeros((self.max_context_size)) j = 0 for k, o in enumerate(context): if o.instance_label == target.instance_label and o.object_id != target.object_id: distrators_pos[j] = k j += 1 for k, o in enumerate(context): object_ids[k] = o.object_id res['utterance'] = self.references.loc[index]['utterance'] res['stimulus_id'] = self.references.loc[index]['stimulus_id'] res['distrators_pos'] = distrators_pos res['object_ids'] = object_ids res['target_object_id'] = target.object_id if self.evalmode: return res # load cached 2D context information if os.path.isfile('../data/scannet_frames_25k_gtobjfeat_aggregate/%s.npy'%scan.scan_id): context_2d = np.load('../data/scannet_frames_25k_gtobjfeat_aggregate/%s.npy'%scan.scan_id,allow_pickle=True,encoding='latin1') objfeat_2d = context_2d.item()['obj_feat'] bbox_2d = context_2d.item()['obj_coord'] bboxsize_2d = context_2d.item()['obj_size'] obj_depth = context_2d.item()['obj_depth'] campose_2d = context_2d.item()['camera_pose'] ins_id_2d = context_2d.item()['instance_id'] if (self.feat2dtype.replace('3D',''))=='ROI': featdim = 2048 elif (self.feat2dtype.replace('3D',''))=='clsvec': featdim = self.num_class_dim elif (self.feat2dtype.replace('3D',''))=='clsvecROI': featdim = 2048+self.num_class_dim feat_2d = np.zeros((self.max_context_size, featdim)).astype(np.float32) coords_2d = np.zeros((self.max_context_size, 4+12)).astype(np.float32) selected_2d_idx = 0 selected_context_id = [o.object_id+1 for o in context] ## backbround included in cache, so +1 ## only for creating tensor of the correct size selected_objfeat_2d = objfeat_2d[selected_context_id,selected_2d_idx,:] selected_bbox_2d = bbox_2d[selected_context_id,selected_2d_idx,:] selected_bboxsize_2d = bboxsize_2d[selected_context_id,selected_2d_idx] selected_obj_depth = obj_depth[selected_context_id,selected_2d_idx] selected_campose_2d = campose_2d[selected_context_id,selected_2d_idx,:] selected_ins_id_2d = ins_id_2d[selected_context_id,selected_2d_idx] ## Fill in randomly selected view of 2D features for ii in range(len(selected_context_id)): cxt_id = selected_context_id[ii] view_id = random.randint(0, max(0,int((ins_id_2d[cxt_id,:]!=0).astype(np.float32).sum())-1)) selected_objfeat_2d[ii,:] = objfeat_2d[cxt_id,view_id,:] selected_bbox_2d[ii,:] = bbox_2d[cxt_id,view_id,:] selected_bboxsize_2d[ii] = bboxsize_2d[cxt_id,view_id] selected_obj_depth[ii] = obj_depth[cxt_id,view_id] selected_campose_2d[ii,:] = campose_2d[cxt_id,view_id,:] if self.feat2dtype!='clsvec': feat_2d[:len(selected_context_id),:2048] = selected_objfeat_2d for ii in range(len(res['class_labels'])): if self.feat2dtype=='clsvec': feat_2d[ii,res['class_labels'][ii]] = 1. if self.feat2dtype=='clsvecROI': feat_2d[ii,2048+res['class_labels'][ii]] = 1. coords_2d[:len(selected_context_id),:] = np.concatenate([selected_bbox_2d, selected_campose_2d[:,:12]],axis=-1) coords_2d[:,0], coords_2d[:,2] = coords_2d[:,0]/1296., coords_2d[:,2]/1296. ## norm by image size coords_2d[:,1], coords_2d[:,3] = coords_2d[:,1]/968., coords_2d[:,3]/968. else: print('please prepare the cached 2d feature') exit(0) res['feat_2d'] = feat_2d res['coords_2d'] = coords_2d return res def make_data_loaders(args, referit_data, vocab, class_to_idx, scans, mean_rgb, seed=None): n_workers = args.n_workers if n_workers == -1: n_workers = max_io_workers() data_loaders = dict() is_train = referit_data['is_train'] splits = ['train', 'test'] object_transformation = partial(mean_rgb_unit_norm_transform, mean_rgb=mean_rgb, unit_norm=args.unit_sphere_norm) for split in splits: mask = is_train if split == 'train' else ~is_train d_set = referit_data[mask] d_set.reset_index(drop=True, inplace=True) max_distractors = args.max_distractors if split == 'train' else args.max_test_objects - 1 ## this is a silly small bug -> not the minus-1. # if split == test remove the utterances of unique targets if split == 'test': def multiple_targets_utterance(x): _, _, _, _, distractors_ids = decode_stimulus_string(x.stimulus_id) return len(distractors_ids) > 0 multiple_targets_mask = d_set.apply(multiple_targets_utterance, axis=1) d_set = d_set[multiple_targets_mask] d_set.reset_index(drop=True, inplace=True) print("length of dataset before removing non multiple test utterances {}".format(len(d_set))) print("removed {} utterances from the test set that don't have multiple distractors".format( np.sum(~multiple_targets_mask))) print("length of dataset after removing non multiple test utterances {}".format(len(d_set))) assert np.sum(~d_set.apply(multiple_targets_utterance, axis=1)) == 0 dataset = ListeningDataset(references=d_set, scans=scans, vocab=vocab, max_seq_len=args.max_seq_len, points_per_object=args.points_per_object, max_distractors=max_distractors, class_to_idx=class_to_idx, object_transformation=object_transformation, visualization=args.mode == 'evaluate', feat2dtype=args.feat2d, num_class_dim = 525 if '00' in args.scannet_file else 608, evalmode=(args.mode=='evaluate')) seed = seed if split == 'test': seed = args.random_seed data_loaders[split] = dataset_to_dataloader(dataset, split, args.batch_size, n_workers, pin_memory=True, seed=seed) return data_loaders
[ "pytorch_transformers.tokenization_bert.BertTokenizer.from_pretrained", "os.path.isfile", "torch.tensor", "numpy.zeros", "numpy.sum", "functools.partial", "numpy.concatenate", "numpy.load", "torch.zeros", "numpy.random.shuffle" ]
[((9564, 9658), 'functools.partial', 'partial', (['mean_rgb_unit_norm_transform'], {'mean_rgb': 'mean_rgb', 'unit_norm': 'args.unit_sphere_norm'}), '(mean_rgb_unit_norm_transform, mean_rgb=mean_rgb, unit_norm=args.\n unit_sphere_norm)\n', (9571, 9658), False, 'from functools import partial\n'), ((1616, 1666), 'pytorch_transformers.tokenization_bert.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (1645, 1666), False, 'from pytorch_transformers.tokenization_bert import BertTokenizer\n'), ((2797, 2823), 'numpy.random.shuffle', 'np.random.shuffle', (['clutter'], {}), '(clutter)\n', (2814, 2823), True, 'import numpy as np\n'), ((2926, 2956), 'numpy.random.shuffle', 'np.random.shuffle', (['distractors'], {}), '(distractors)\n', (2943, 2956), True, 'import numpy as np\n'), ((3171, 3218), 'torch.zeros', 'torch.zeros', (['self.max_seq_len'], {'dtype': 'torch.long'}), '(self.max_seq_len, dtype=torch.long)\n', (3182, 3218), False, 'import torch\n'), ((3406, 3427), 'torch.tensor', 'torch.tensor', (['indices'], {}), '(indices)\n', (3418, 3427), False, 'import torch\n'), ((4626, 4672), 'numpy.zeros', 'np.zeros', (['self.max_context_size'], {'dtype': 'np.bool'}), '(self.max_context_size, dtype=np.bool)\n', (4634, 4672), True, 'import numpy as np\n'), ((6046, 6136), 'os.path.isfile', 'os.path.isfile', (["('../data/scannet_frames_25k_gtobjfeat_aggregate/%s.npy' % scan.scan_id)"], {}), "('../data/scannet_frames_25k_gtobjfeat_aggregate/%s.npy' %\n scan.scan_id)\n", (6060, 6136), False, 'import os\n'), ((5192, 5203), 'numpy.zeros', 'np.zeros', (['(6)'], {}), '(6)\n', (5200, 5203), True, 'import numpy as np\n'), ((5294, 5325), 'numpy.zeros', 'np.zeros', (['self.max_context_size'], {}), '(self.max_context_size)\n', (5302, 5325), True, 'import numpy as np\n'), ((6157, 6279), 'numpy.load', 'np.load', (["('../data/scannet_frames_25k_gtobjfeat_aggregate/%s.npy' % scan.scan_id)"], {'allow_pickle': '(True)', 'encoding': '"""latin1"""'}), "('../data/scannet_frames_25k_gtobjfeat_aggregate/%s.npy' % scan.\n scan_id, allow_pickle=True, encoding='latin1')\n", (6164, 6279), True, 'import numpy as np\n'), ((8803, 8875), 'numpy.concatenate', 'np.concatenate', (['[selected_bbox_2d, selected_campose_2d[:, :12]]'], {'axis': '(-1)'}), '([selected_bbox_2d, selected_campose_2d[:, :12]], axis=-1)\n', (8817, 8875), True, 'import numpy as np\n'), ((4158, 4208), 'numpy.zeros', 'np.zeros', (['(self.max_context_size, offset.shape[1])'], {}), '((self.max_context_size, offset.shape[1]))\n', (4166, 4208), True, 'import numpy as np\n'), ((6892, 6934), 'numpy.zeros', 'np.zeros', (['(self.max_context_size, featdim)'], {}), '((self.max_context_size, featdim))\n', (6900, 6934), True, 'import numpy as np\n'), ((6978, 7019), 'numpy.zeros', 'np.zeros', (['(self.max_context_size, 4 + 12)'], {}), '((self.max_context_size, 4 + 12))\n', (6986, 7019), True, 'import numpy as np\n'), ((10707, 10737), 'numpy.sum', 'np.sum', (['(~multiple_targets_mask)'], {}), '(~multiple_targets_mask)\n', (10713, 10737), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: parser_funs Description : Author : <NAME> date: ------------------------------------------------- Change Activity: 2019/7/28: ------------------------------------------------- """ import torch import numpy as np def sdp_decoder(semgraph_probs, sentlens): ''' semhead_probs type:ndarray, shape:(n,m,m) ''' semhead_probs = semgraph_probs.sum(axis=-1) semhead_preds = np.where(semhead_probs >= 0.5, 1, 0) masked_semhead_preds = np.zeros(semhead_preds.shape, dtype=np.int32) for i, (sem_preds, length) in enumerate(zip(semhead_preds, sentlens)): masked_semhead_preds[i, :length, :length] = sem_preds[:length, :length] n_counts = {'no_root': 0, 'multi_root': 0, 'no_head': 0, 'self_circle': 0} for i, length in enumerate(sentlens): for j in range(length): if masked_semhead_preds[i, j, j] == 1: n_counts['self_circle'] += 1 masked_semhead_preds[i, j, j] = 0 n_root = np.sum(masked_semhead_preds[i, :, 0]) if n_root == 0: n_counts['no_root'] += 1 new_root = np.argmax(semhead_probs[i, 1:, 0]) + 1 masked_semhead_preds[i, new_root, 0] = 1 elif n_root > 1: n_counts['multi_root'] += 1 kept_root = np.argmax(semhead_probs[i, 1:, 0]) + 1 masked_semhead_preds[i, :, 0] = 0 masked_semhead_preds[i, kept_root, 0] = 1 n_heads = masked_semhead_preds[i, :length, :length].sum(axis=-1) n_heads[0] = 1 for j, n_head in enumerate(n_heads): if n_head == 0: n_counts['no_head'] += 1 semhead_probs[i, j, j] = 0 new_head = np.argmax(semhead_probs[i, j, 1:length]) + 1 masked_semhead_preds[i, j, new_head] = 1 # (n x m x m x c) -> (n x m x m) semrel_preds = np.argmax(semgraph_probs, axis=-1) # (n x m x m) (*) (n x m x m) -> (n x m x m) semgraph_preds = masked_semhead_preds * semrel_preds result = masked_semhead_preds + semgraph_preds return result def parse_semgraph(semgraph, sentlens): semgraph = semgraph.tolist() sents = [] for s, l in zip(semgraph, sentlens): words = [] for w in s[1:l]: arc = [] for head_idx, deprel in enumerate(w[:l]): if deprel == 0: continue arc.append([head_idx, deprel - 1]) words.append(arc) sents.append(words) return sents
[ "numpy.where", "numpy.sum", "numpy.zeros", "numpy.argmax" ]
[((520, 556), 'numpy.where', 'np.where', (['(semhead_probs >= 0.5)', '(1)', '(0)'], {}), '(semhead_probs >= 0.5, 1, 0)\n', (528, 556), True, 'import numpy as np\n'), ((584, 629), 'numpy.zeros', 'np.zeros', (['semhead_preds.shape'], {'dtype': 'np.int32'}), '(semhead_preds.shape, dtype=np.int32)\n', (592, 629), True, 'import numpy as np\n'), ((1981, 2015), 'numpy.argmax', 'np.argmax', (['semgraph_probs'], {'axis': '(-1)'}), '(semgraph_probs, axis=-1)\n', (1990, 2015), True, 'import numpy as np\n'), ((1101, 1138), 'numpy.sum', 'np.sum', (['masked_semhead_preds[i, :, 0]'], {}), '(masked_semhead_preds[i, :, 0])\n', (1107, 1138), True, 'import numpy as np\n'), ((1223, 1257), 'numpy.argmax', 'np.argmax', (['semhead_probs[i, 1:, 0]'], {}), '(semhead_probs[i, 1:, 0])\n', (1232, 1257), True, 'import numpy as np\n'), ((1404, 1438), 'numpy.argmax', 'np.argmax', (['semhead_probs[i, 1:, 0]'], {}), '(semhead_probs[i, 1:, 0])\n', (1413, 1438), True, 'import numpy as np\n'), ((1823, 1863), 'numpy.argmax', 'np.argmax', (['semhead_probs[i, j, 1:length]'], {}), '(semhead_probs[i, j, 1:length])\n', (1832, 1863), True, 'import numpy as np\n')]
import functools import json import re from collections import Counter import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd import seaborn as sns from statics import STRUCTURE_TYPES sns.set_style("whitegrid") plt.rcParams["figure.figsize"] = (18, 12) plt.rcParams["font.size"] = 12 np.random.seed(1234) def get_jaccard(structure1, structure2, structure_type): if structure_type == "clique": nodes1 = set(structure1["nodes"]) nodes2 = set(structure2["nodes"]) overlap = nodes1.intersection(nodes2) union = nodes1.union(nodes2) return len(overlap) / len(union) if structure_type in ["biclique", "starclique"]: left1, left2 = set(structure1["left_nodes"]), set(structure2["left_nodes"]) right1, right2 = set(structure1["right_nodes"]), set(structure2["right_nodes"]) left_overlap = left1.intersection(left2) left_union = left1.union(left2) right_overlap = right1.intersection(right2) right_union = right1.union(right2) return ( len(left_overlap) / len(left_union) + len(right_overlap) / len(right_union) ) / 2 if structure_type == "star": hub1, hub2 = {structure1["hub"]}, {structure2["hub"]} spokes1, spokes2 = set(structure1["spokes"]), set(structure2["spokes"]) hub_overlap = hub1.intersection(hub2) hub_union = hub1.union(hub2) spoke_overlap = spokes1.intersection(spokes2) spoke_union = spokes1.union(spokes2) return ( len(hub_overlap) / len(hub_union) + len(spoke_overlap) / len(spoke_union) ) / 2 raise Exception(f"Unknown structure type: {structure_type}!") def get_dataset_color(dataset): if dataset.startswith("ors") or dataset.startswith("asb"): return "dodgerblue" elif dataset.startswith("orp") or dataset.startswith("asp"): return "lightskyblue" elif dataset.startswith("usl") or dataset.startswith("lus"): return "r" elif dataset.startswith("del") or dataset.startswith("lde"): return "darkorange" elif dataset.startswith("clg"): return "purple" elif dataset.startswith("csi"): return "magenta" elif "bio$_{\mathcal{A}}" in dataset: return "green" elif dataset.startswith("bio\n") or dataset.startswith("bio"): return "g" elif dataset.startswith("bag") or dataset.startswith("rba"): return "gray" elif dataset.startswith("erg") or dataset.startswith("rer"): return "darkgray" else: raise Exception(dataset) def load_json(file): """ load a json file as a dictionary """ with open(file) as f: model_json = json.load(f) return model_json def load_log(file): """ load a log file as a list of log file lines """ with open(file) as f: model_log = f.read().split("\n") return model_log def create_df(model_json): """ convert the model json computed by julia into a pd.DataFrame """ tuples = list( zip( model_json["macro_structures"], model_json["macro_structure_description_lengths"], model_json["description_lengths_over_time"], ) ) df = pd.DataFrame( tuples, columns=["structure", "structure_cost", "description_length"] ) df["n_edges_total"] = [ x.get("n_edges_total", model_json["m"]) for x in df.structure ] df["n_nodes_total"] = [ x.get("n_nodes_total", model_json["n"]) for x in df.structure ] df["structure_type"] = [x.get("structure_type") for x in df.structure] df["structure_shape"] = [ get_node_marker(x) if x in STRUCTURE_TYPES else "X" for x in df.structure_type ] df["structure_color"] = [ get_node_color(x) if x in STRUCTURE_TYPES else "k" for x in df.structure_type ] return df def create_progression_plot(df, save_path=None): """ position of structure in the sequence on x, description length after adding structure on y, color signaling structure type, size signalling number of edges """ scattertuples = list( zip( df.index - 1, df.description_length / df.description_length.max(), df.n_edges_total, df.structure_color, df.structure_shape, ) ) for t in reversed(scattertuples[1:]): plt.scatter(t[0], t[1], s=t[2] if t[3] != "k" else 10, c=t[3], marker="o") plt.xticks(range(0, len(scattertuples[1:]) + 1, 2)) plt.xlim(-1, len(scattertuples[1:]) + 1) plt.xlabel("Selected structure") plt.ylabel("Total description length after structure selected") plt.title(save_path) plt.tight_layout() if save_path is not None: plt.savefig(save_path) plt.close() def create_size_plot(model_json, x_granularity, y_granularity, save_path=None): """ number of nodes on x, number of edges on y, color signaling structure type """ structure_types, n_nodes, n_edges = list( zip( *( [ (s["structure_type"], s.get("n_nodes_total", 0), s["n_edges_total"]) for s in model_json["macro_structures"] ] ) ) ) plt.scatter( n_nodes[2:], n_edges[2:], c=list(map(get_node_color, structure_types[2:])), ) plt.xlabel("Number of Nodes") plt.xticks(range(0, max(n_nodes[2:]) + x_granularity, x_granularity)) plt.yticks(range(0, max(n_edges[2:]) + y_granularity, y_granularity)) plt.ylim(0, max(n_edges[2:]) + y_granularity) plt.ylabel("Number of Edges") plt.title(save_path) plt.tight_layout() if save_path is not None: plt.savefig(save_path) plt.close() def get_structures_added(model_json): """ return list of dicts, with each dict a structure added in the model building process (i.e., generic structures are excluded) """ return model_json["macro_structures"][2:] def get_node_sets(structures_added): """ return a list of lists, with each inner list holding the nodes of a structure """ return [_get_nodes(structure) for structure in structures_added] def _get_nodes(structure): """ helper for get_node_sets """ if structure["structure_type"] in ["biclique", "starclique"]: return structure["left_nodes"] + structure["right_nodes"] elif structure["structure_type"] == "clique": return structure["nodes"] elif structure["structure_type"] == "star": return [structure["hub"]] + structure["spokes"] else: raise Exception(f"Unknown structure type {structure['structure_type']}!") def get_structure_dfs(structures_added, node_sets): """ return two pd.DataFrame objects encoding the node overlap between structures: abs_df (# nodes in the overlap), rel_df (jaccard similarity) """ abs_df = pd.DataFrame( index=range(len(structures_added)), columns=range(len(structures_added)), data=np.nan, ) rel_df = pd.DataFrame( index=range(len(structures_added)), columns=range(len(structures_added)), data=np.nan, ) for idx in range(0, len(node_sets) - 1): for idx2 in range(idx + 1, len(node_sets)): abs_df.at[idx, idx2] = len( set(node_sets[idx]).intersection(set(node_sets[idx2])) ) abs_df.at[idx2, idx] = abs_df.at[idx, idx2] rel_df.at[idx, idx2] = len( set(node_sets[idx]).intersection(set(node_sets[idx2])) ) / len(set(node_sets[idx]).union(set(node_sets[idx2]))) rel_df.at[idx2, idx] = rel_df.at[idx, idx2] return abs_df, rel_df def _get_n_nodes_covered(node_sets): """ helper for get_fraction_nodes_covered """ return len(set(functools.reduce(lambda x, y: x + y, node_sets, []))) def get_fraction_nodes_covered(node_sets, model_json): return _get_n_nodes_covered(node_sets) / model_json["n"] def plot_overlap_heatmap(df, save_path=None): """ structures added to model on x and y, similarity as per df as color, default colormap, robust=False """ sns.heatmap(df, square=True) if save_path is not None: plt.savefig(save_path) plt.close() def create_rooted_bfs_tree(df, layout=False): G = nx.Graph(df.fillna(0)) maxst = nx.tree.maximum_spanning_tree(G) artificial_root = G.number_of_nodes() ccs = list(nx.connected_components(G)) for c in ccs: component_subgraph = maxst.subgraph(c) component_root = max(nx.degree(component_subgraph), key=lambda tup: tup[-1])[ 0 ] # node with max unweighted degree maxst.add_edge(artificial_root, component_root, weight=np.finfo(float).eps) tree = nx.traversal.bfs_tree(maxst, artificial_root) for e in tree.edges(): tree.edges[e]["weight"] = maxst.edges[e]["weight"] if layout: pos = nx.layout.kamada_kawai_layout(maxst, weight=None) return tree, pos else: return tree def add_tree_layout(G, root, node_sep, level_sep): for node in G.nodes(): G.nodes[node]["y"] = -level_sep * nx.dijkstra_path_length( G, root, node, weight=None ) base = 0 for node in nx.dfs_postorder_nodes(G, root): succ = sorted(list(G.successors(node)), reverse=True) if len(succ) < 1: G.nodes[node]["x"] = base + node_sep base += node_sep else: xmin = min([G.nodes[node]["x"] for node in succ]) xmax = max([G.nodes[node]["x"] for node in succ]) G.nodes[node]["x"] = xmin + (xmax - xmin) / 2 for node in G.nodes: G.nodes[node]["x"] = -G.nodes[node]["x"] return G def add_color(G, df): for node in G.nodes(): G.nodes[node]["color"] = ( df.at[node + 2, "structure_color"] if node != len(df) - 2 else "k" ) return G def plot_tree(G, df, save_path=None): G = add_color(G, df) _, ax = plt.subplots(1, 1, figsize=(12, 12)) for node in G.nodes(): x = G.nodes[node]["x"] y = G.nodes[node]["y"] color = G.nodes[node]["color"] for succ in G.successors(node): ax.plot( [x, G.nodes[succ]["x"]], [y, G.nodes[succ]["y"]], "-k", linewidth=max(G.edges[node, succ]["weight"] * 10, 1), zorder=1, alpha=1, ) ax.scatter( x, y, color=color, s=df.at[node + 2, "n_nodes_total"] * 6 if node != len(df) - 2 else 300, marker=df.at[node + 2, "structure_shape"] if node != len(df) - 2 else "X", zorder=2, alpha=1, ) # if node != len(df) - 2: # ax.annotate(node + 1, (x, y), fontsize=10, ha="center", va="center") plt.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False) plt.axis("off") plt.tight_layout() if save_path is not None: plt.savefig(save_path, transparent=True, bbox_inches="tight") plt.close() def plot_structure_tree(tree, layout, df, save_path=None): """ plot structure tree in basic kamada kawai layout; structure identifiers in order of structure addition and color corresponding to structure type (artificial root node black) """ nx.draw_networkx_edges(tree, pos=layout) for node, (x, y) in layout.items(): plt.scatter( x, y, color=df.at[node + 2, "structure_color"] if node != len(df) - 2 else "k", s=df.at[node + 2, "n_nodes_total"] * 6 if node != len(df) - 2 else 100, marker=df.at[node + 2, "structure_shape"] if node != len(df) - 2 else "X", zorder=2, alpha=0.8, ) labels = {idx: idx + 1 for idx in tree.nodes()} nx.draw_networkx_labels(tree, pos=layout, labels=labels) plt.axis("off") if save_path is not None: plt.savefig(save_path) plt.close() def write_plots_for_model_json( json_path, save_base, x_granularity_size, y_granularity_size, ): """ end-to-end plot generation for json file at given json_path """ print(f"Starting {json_path}...") model_json = load_json(json_path) save_base = save_base.split("_size")[0] df = create_df(model_json) df.to_csv(re.sub("figure", "structures", save_base) + ".csv", index=False) structures_added = get_structures_added(model_json) node_sets = get_node_sets(structures_added) try: abs_df, rel_df = get_structure_dfs(structures_added, node_sets) rel_df.to_csv(re.sub("figure", "structure_overlap_matrix", save_base) + ".csv") tree, layout = create_rooted_bfs_tree(rel_df, layout=True) plot_tree( add_tree_layout(tree, tree.number_of_nodes() - 1, 10, 10), df, re.sub("figure", "tree-hierarchical", save_base) + ".pdf", ) plot_structure_tree( tree, layout, df, re.sub("figure", "tree-kamada", save_base) + ".pdf" ) G = create_overlap_quotient_graph(structures_added, abs_df, model_json["n"]) plot_overlap_quotient_graph( G, df, model_json["n"], re.sub("figure", "overlap-quotient", save_base) + ".pdf", ) G = create_structure_quotient_graph(node_sets, save_base) plot_structure_quotient_graph( G, node_sets, structures_added, save_path=re.sub("figure", "structure-quotient", save_base) + ".pdf", ) except: print( f"Error for overlap dataframes or graph plots: {json_path} - moving on..." ) try: create_progression_plot( df, re.sub("figure", "progress", save_base) + ".pdf", ) except: print(f"Error for progression plot: {json_path} - moving on...") try: create_size_plot( model_json, x_granularity_size, y_granularity_size, re.sub("figure", "sizes", save_base) + ".pdf", ) except: print(f"Error for size plot: {json_path} - moving on...") def get_edgelist_separator(edgelist_path): with open(edgelist_path) as f: for line in f: if not line.startswith("#"): if "\t" in line: return "\t" elif "," in line: return "," elif " " in line: return " " else: raise def create_structure_quotient_graph(nodes, save_base): nodemap_path = ( re.sub("figure-", "", re.sub("graphics/", "results/", save_base)) + "-nodemap.csv" ) nodemap = pd.read_csv(nodemap_path) edgelist_path = ( re.sub("figure-", "", re.sub("graphics/", "data/", save_base)) + ".txt" ) edges = pd.read_csv( edgelist_path, sep=get_edgelist_separator(edgelist_path), comment="#", header=None, usecols=[0, 1], ).rename({0: "u", 1: "v"}, axis=1) new_edges = edges.merge(nodemap, left_on="u", right_on="original_id").merge( nodemap, left_on="v", right_on="original_id", suffixes=("_u", "_v") )[["julia_id_u", "julia_id_v"]] assert len(edges) == len(new_edges) nodes_to_structures = get_nodes_to_structures(nodes) G = nx.MultiGraph() G.add_nodes_from(range(1, len(nodes) + 1)) for u, v in zip(new_edges.julia_id_u, new_edges.julia_id_v): u_structures = nodes_to_structures.get(u, []) v_structures = nodes_to_structures.get(v, []) if ( u_structures and v_structures and not set(u_structures).intersection(v_structures) ): for us in u_structures: for vs in v_structures: G.add_edge(us, vs) wG = nx.Graph() wG.add_nodes_from(G.nodes()) wG.add_weighted_edges_from([(*k, v) for k, v in dict(Counter(G.edges())).items()]) return wG def get_nodes_to_structures(nodes): nodes_to_structures = {} for idx, nodeset in enumerate(nodes, start=1): for node in nodeset: nodes_to_structures[node] = nodes_to_structures.get(node, []) + [idx] return nodes_to_structures def get_node_color(node_type): if node_type == "star": return "orange" elif node_type == "clique": return "dodgerblue" elif node_type == "biclique": return "#BE271A" # red3 elif node_type == "starclique": return "orchid" else: raise def get_node_marker(node_type): if node_type == "star": return "^" elif node_type == "clique": return "o" elif node_type == "biclique": return "s" elif node_type == "starclique": return "d" else: raise def plot_structure_quotient_graph(wG, nodes, structures, save_path=None): pos = nx.layout.fruchterman_reingold_layout(wG, k=2.5, seed=0) _ = plt.figure(figsize=(12, 12)) nx.draw_networkx_edges( wG, pos=pos, edgelist=wG.edges(), width=[w / 100 for u, v, w in wG.edges(data="weight")], ) for node in wG.nodes(): plt.scatter( *pos[node], s=len(nodes[node - 1]) * 5, c=get_node_color(structures[node - 1]["structure_type"]), marker=get_node_marker(structures[node - 1]["structure_type"]), ) nx.draw_networkx_labels(wG, pos, zorder=100) plt.axis("off") plt.tight_layout() if save_path is not None: plt.savefig(save_path) plt.close() def create_overlap_quotient_graph(structures_added, abs_df, n_total): G = nx.Graph() for idx, structure in enumerate(structures_added, start=1): G.add_node( idx, **{**structure, "n_relative": structure["n_nodes_total"] / n_total} ) for i in range(len(abs_df)): for j in range(i + 1, len(abs_df)): edge_weight = abs_df.at[i, j] / n_total if edge_weight > 0: G.add_edge(i + 1, j + 1, weight=edge_weight) return G def plot_overlap_quotient_graph(G, df, n_total, save_path=None): np.random.seed(1234) pos = nx.layout.fruchterman_reingold_layout(G) _, ax = plt.subplots(1, 1, figsize=(12, 12)) for x, y, w in G.edges(data="weight"): if w * n_total > 1: ax.plot( [pos[x][0], pos[y][0]], [pos[x][1], pos[y][1]], "-k", linewidth=w * n_total / 100, zorder=-10, alpha=0.5, ) for node in G.nodes(data=True): ax.scatter( *pos[node[0]], s=5.0 * node[1]["n_nodes_total"], c=df.at[node[0] + 1, "structure_color"], marker=df.at[node[0] + 1, "structure_shape"], zorder=1, ) nx.draw_networkx_labels(G, pos, zorder=100) plt.axis("off") plt.tight_layout() if save_path is not None: plt.savefig(save_path, transparent=True) plt.close()
[ "networkx.layout.fruchterman_reingold_layout", "pandas.read_csv", "matplotlib.pyplot.ylabel", "networkx.traversal.bfs_tree", "seaborn.set_style", "networkx.draw_networkx_labels", "matplotlib.pyplot.xlabel", "networkx.MultiGraph", "matplotlib.pyplot.close", "numpy.random.seed", "networkx.dfs_post...
[((225, 251), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (238, 251), True, 'import seaborn as sns\n'), ((325, 345), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (339, 345), True, 'import numpy as np\n'), ((3269, 3356), 'pandas.DataFrame', 'pd.DataFrame', (['tuples'], {'columns': "['structure', 'structure_cost', 'description_length']"}), "(tuples, columns=['structure', 'structure_cost',\n 'description_length'])\n", (3281, 3356), True, 'import pandas as pd\n'), ((4606, 4638), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Selected structure"""'], {}), "('Selected structure')\n", (4616, 4638), True, 'import matplotlib.pyplot as plt\n'), ((4643, 4706), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Total description length after structure selected"""'], {}), "('Total description length after structure selected')\n", (4653, 4706), True, 'import matplotlib.pyplot as plt\n'), ((4711, 4731), 'matplotlib.pyplot.title', 'plt.title', (['save_path'], {}), '(save_path)\n', (4720, 4731), True, 'import matplotlib.pyplot as plt\n'), ((4736, 4754), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4752, 4754), True, 'import matplotlib.pyplot as plt\n'), ((5429, 5458), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Nodes"""'], {}), "('Number of Nodes')\n", (5439, 5458), True, 'import matplotlib.pyplot as plt\n'), ((5661, 5690), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Edges"""'], {}), "('Number of Edges')\n", (5671, 5690), True, 'import matplotlib.pyplot as plt\n'), ((5695, 5715), 'matplotlib.pyplot.title', 'plt.title', (['save_path'], {}), '(save_path)\n', (5704, 5715), True, 'import matplotlib.pyplot as plt\n'), ((5720, 5738), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5736, 5738), True, 'import matplotlib.pyplot as plt\n'), ((8244, 8272), 'seaborn.heatmap', 'sns.heatmap', (['df'], {'square': '(True)'}), '(df, square=True)\n', (8255, 8272), True, 'import seaborn as sns\n'), ((8445, 8477), 'networkx.tree.maximum_spanning_tree', 'nx.tree.maximum_spanning_tree', (['G'], {}), '(G)\n', (8474, 8477), True, 'import networkx as nx\n'), ((8868, 8913), 'networkx.traversal.bfs_tree', 'nx.traversal.bfs_tree', (['maxst', 'artificial_root'], {}), '(maxst, artificial_root)\n', (8889, 8913), True, 'import networkx as nx\n'), ((9359, 9390), 'networkx.dfs_postorder_nodes', 'nx.dfs_postorder_nodes', (['G', 'root'], {}), '(G, root)\n', (9381, 9390), True, 'import networkx as nx\n'), ((10106, 10142), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(12, 12)'}), '(1, 1, figsize=(12, 12))\n', (10118, 10142), True, 'import matplotlib.pyplot as plt\n'), ((10991, 11068), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'left': '(False)', 'labelleft': '(False)', 'bottom': '(False)', 'labelbottom': '(False)'}), '(left=False, labelleft=False, bottom=False, labelbottom=False)\n', (11006, 11068), True, 'import matplotlib.pyplot as plt\n'), ((11073, 11088), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (11081, 11088), True, 'import matplotlib.pyplot as plt\n'), ((11093, 11111), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (11109, 11111), True, 'import matplotlib.pyplot as plt\n'), ((11495, 11535), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', (['tree'], {'pos': 'layout'}), '(tree, pos=layout)\n', (11517, 11535), True, 'import networkx as nx\n'), ((11995, 12051), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['tree'], {'pos': 'layout', 'labels': 'labels'}), '(tree, pos=layout, labels=labels)\n', (12018, 12051), True, 'import networkx as nx\n'), ((12056, 12071), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (12064, 12071), True, 'import matplotlib.pyplot as plt\n'), ((14946, 14971), 'pandas.read_csv', 'pd.read_csv', (['nodemap_path'], {}), '(nodemap_path)\n', (14957, 14971), True, 'import pandas as pd\n'), ((15582, 15597), 'networkx.MultiGraph', 'nx.MultiGraph', ([], {}), '()\n', (15595, 15597), True, 'import networkx as nx\n'), ((16085, 16095), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (16093, 16095), True, 'import networkx as nx\n'), ((17136, 17192), 'networkx.layout.fruchterman_reingold_layout', 'nx.layout.fruchterman_reingold_layout', (['wG'], {'k': '(2.5)', 'seed': '(0)'}), '(wG, k=2.5, seed=0)\n', (17173, 17192), True, 'import networkx as nx\n'), ((17201, 17229), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (17211, 17229), True, 'import matplotlib.pyplot as plt\n'), ((17659, 17703), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['wG', 'pos'], {'zorder': '(100)'}), '(wG, pos, zorder=100)\n', (17682, 17703), True, 'import networkx as nx\n'), ((17708, 17723), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (17716, 17723), True, 'import matplotlib.pyplot as plt\n'), ((17728, 17746), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (17744, 17746), True, 'import matplotlib.pyplot as plt\n'), ((17908, 17918), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (17916, 17918), True, 'import networkx as nx\n'), ((18404, 18424), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (18418, 18424), True, 'import numpy as np\n'), ((18435, 18475), 'networkx.layout.fruchterman_reingold_layout', 'nx.layout.fruchterman_reingold_layout', (['G'], {}), '(G)\n', (18472, 18475), True, 'import networkx as nx\n'), ((18488, 18524), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(12, 12)'}), '(1, 1, figsize=(12, 12))\n', (18500, 18524), True, 'import matplotlib.pyplot as plt\n'), ((19109, 19152), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['G', 'pos'], {'zorder': '(100)'}), '(G, pos, zorder=100)\n', (19132, 19152), True, 'import networkx as nx\n'), ((19157, 19172), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (19165, 19172), True, 'import matplotlib.pyplot as plt\n'), ((19177, 19195), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (19193, 19195), True, 'import matplotlib.pyplot as plt\n'), ((2729, 2741), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2738, 2741), False, 'import json\n'), ((4426, 4500), 'matplotlib.pyplot.scatter', 'plt.scatter', (['t[0]', 't[1]'], {'s': "(t[2] if t[3] != 'k' else 10)", 'c': 't[3]', 'marker': '"""o"""'}), "(t[0], t[1], s=t[2] if t[3] != 'k' else 10, c=t[3], marker='o')\n", (4437, 4500), True, 'import matplotlib.pyplot as plt\n'), ((4793, 4815), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (4804, 4815), True, 'import matplotlib.pyplot as plt\n'), ((4824, 4835), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4833, 4835), True, 'import matplotlib.pyplot as plt\n'), ((5777, 5799), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (5788, 5799), True, 'import matplotlib.pyplot as plt\n'), ((5808, 5819), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5817, 5819), True, 'import matplotlib.pyplot as plt\n'), ((8311, 8333), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (8322, 8333), True, 'import matplotlib.pyplot as plt\n'), ((8342, 8353), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (8351, 8353), True, 'import matplotlib.pyplot as plt\n'), ((8535, 8561), 'networkx.connected_components', 'nx.connected_components', (['G'], {}), '(G)\n', (8558, 8561), True, 'import networkx as nx\n'), ((9029, 9078), 'networkx.layout.kamada_kawai_layout', 'nx.layout.kamada_kawai_layout', (['maxst'], {'weight': 'None'}), '(maxst, weight=None)\n', (9058, 9078), True, 'import networkx as nx\n'), ((11150, 11211), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {'transparent': '(True)', 'bbox_inches': '"""tight"""'}), "(save_path, transparent=True, bbox_inches='tight')\n", (11161, 11211), True, 'import matplotlib.pyplot as plt\n'), ((11220, 11231), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (11229, 11231), True, 'import matplotlib.pyplot as plt\n'), ((12110, 12132), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (12121, 12132), True, 'import matplotlib.pyplot as plt\n'), ((12141, 12152), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12150, 12152), True, 'import matplotlib.pyplot as plt\n'), ((17785, 17807), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {}), '(save_path)\n', (17796, 17807), True, 'import matplotlib.pyplot as plt\n'), ((17816, 17827), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (17825, 17827), True, 'import matplotlib.pyplot as plt\n'), ((19234, 19274), 'matplotlib.pyplot.savefig', 'plt.savefig', (['save_path'], {'transparent': '(True)'}), '(save_path, transparent=True)\n', (19245, 19274), True, 'import matplotlib.pyplot as plt\n'), ((19283, 19294), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (19292, 19294), True, 'import matplotlib.pyplot as plt\n'), ((7900, 7951), 'functools.reduce', 'functools.reduce', (['(lambda x, y: x + y)', 'node_sets', '[]'], {}), '(lambda x, y: x + y, node_sets, [])\n', (7916, 7951), False, 'import functools\n'), ((9256, 9307), 'networkx.dijkstra_path_length', 'nx.dijkstra_path_length', (['G', 'root', 'node'], {'weight': 'None'}), '(G, root, node, weight=None)\n', (9279, 9307), True, 'import networkx as nx\n'), ((12513, 12554), 're.sub', 're.sub', (['"""figure"""', '"""structures"""', 'save_base'], {}), "('figure', 'structures', save_base)\n", (12519, 12554), False, 'import re\n'), ((14857, 14899), 're.sub', 're.sub', (['"""graphics/"""', '"""results/"""', 'save_base'], {}), "('graphics/', 'results/', save_base)\n", (14863, 14899), False, 'import re\n'), ((15024, 15063), 're.sub', 're.sub', (['"""graphics/"""', '"""data/"""', 'save_base'], {}), "('graphics/', 'data/', save_base)\n", (15030, 15063), False, 'import re\n'), ((8657, 8686), 'networkx.degree', 'nx.degree', (['component_subgraph'], {}), '(component_subgraph)\n', (8666, 8686), True, 'import networkx as nx\n'), ((12785, 12840), 're.sub', 're.sub', (['"""figure"""', '"""structure_overlap_matrix"""', 'save_base'], {}), "('figure', 'structure_overlap_matrix', save_base)\n", (12791, 12840), False, 'import re\n'), ((13036, 13084), 're.sub', 're.sub', (['"""figure"""', '"""tree-hierarchical"""', 'save_base'], {}), "('figure', 'tree-hierarchical', save_base)\n", (13042, 13084), False, 'import re\n'), ((13164, 13206), 're.sub', 're.sub', (['"""figure"""', '"""tree-kamada"""', 'save_base'], {}), "('figure', 'tree-kamada', save_base)\n", (13170, 13206), False, 'import re\n'), ((13420, 13467), 're.sub', 're.sub', (['"""figure"""', '"""overlap-quotient"""', 'save_base'], {}), "('figure', 'overlap-quotient', save_base)\n", (13426, 13467), False, 'import re\n'), ((13947, 13986), 're.sub', 're.sub', (['"""figure"""', '"""progress"""', 'save_base'], {}), "('figure', 'progress', save_base)\n", (13953, 13986), False, 'import re\n'), ((14227, 14263), 're.sub', 're.sub', (['"""figure"""', '"""sizes"""', 'save_base'], {}), "('figure', 'sizes', save_base)\n", (14233, 14263), False, 'import re\n'), ((8836, 8851), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (8844, 8851), True, 'import numpy as np\n'), ((13683, 13732), 're.sub', 're.sub', (['"""figure"""', '"""structure-quotient"""', 'save_base'], {}), "('figure', 'structure-quotient', save_base)\n", (13689, 13732), False, 'import re\n')]
import sys sys.path.append("..") from osc_sdk_python import Gateway gw = Gateway() res = gw.CreateNet(IpRange='192.168.127.12/32') error = [error for error in res['Errors'] if error.get('Code') == '4014' and error.get('Details') == 'invalid-block-size'] assert len(error) == 1
[ "sys.path.append", "osc_sdk_python.Gateway" ]
[((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((73, 82), 'osc_sdk_python.Gateway', 'Gateway', ([], {}), '()\n', (80, 82), False, 'from osc_sdk_python import Gateway\n')]
""" Classification Main script for the simulation described in Hyvarinen and Morioka, NIPS 2016. Perform time-contrastive learning from artificial data. Source signals are generated based on segment-wise-modulated Laplace distribution (q = |.|). """ import os import pickle import shutil from subfunc.generate_artificial_data import generate_artificial_data from subfunc.preprocessing import pca from tcl.tcl_train import train # Parameters ================================================== # ============================================================= # Data generation --------------------------------------------- random_seed = 0 # random seed num_comp = 20 # number of components (dimension) num_segment = 256 # number of segments num_segmentdata = 512 # number of data-points in each segment num_layer = 5 # number of layers of mixing-MLP # MLP --------------------------------------------------------- list_hidden_nodes = [40, 40, 40, 40, 20] # list of the number of nodes of each hidden layer of feature-MLP # [layer1, layer2, ..., layer(num_layer)] # Training ---------------------------------------------------- initial_learning_rate = 0.01 # initial learning rate momentum = 0.9 # momentum parameter of SGD max_steps = int(7e5) # number of iterations (mini-batches) decay_steps = int(5e5) # decay steps (tf.train.exponential_decay) decay_factor = 0.1 # decay factor (tf.train.exponential_decay) batch_size = 512 # mini-batch size moving_average_decay = 0.999 # moving average decay of variables to be saved checkpoint_steps = 1e5 # interval to save checkpoint # for MLR initialization max_steps_init = int(7e4) # number of iterations (mini-batches) for initializing only MLR decay_steps_init = int(5e4) # decay steps for initializing only MLR # Other ------------------------------------------------------- # # Note: save folder must be under ./storage train_dir = './storage/temp' # save directory (Caution!! this folder will be removed at first) saveparmpath = os.path.join(train_dir, 'parm.pkl') # file name to save parameters # ============================================================= # ============================================================= # Prepare save folder ----------------------------------------- if train_dir.find("./storage/") > -1: if os.path.exists(train_dir): print("delete savefolder: {0:s}...".format(train_dir)) shutil.rmtree(train_dir) # Remove folder print("make savefolder: {0:s}...".format(train_dir)) os.makedirs(train_dir) # Make folder else: assert False, "savefolder looks wrong" # Generate sensor signal -------------------------------------- sensor, source, label = generate_artificial_data(num_comp=num_comp, num_segment=num_segment, num_segmentdata=num_segmentdata, num_layer=num_layer, random_seed=random_seed) # Preprocessing ----------------------------------------------- sensor, pca_parm = pca(sensor, num_comp=num_comp) # Train model (only MLR) -------------------------------------- train(sensor, label, num_class = num_segment, list_hidden_nodes = list_hidden_nodes, initial_learning_rate = initial_learning_rate, momentum = momentum, max_steps = max_steps_init, # For init decay_steps = decay_steps_init, # For init decay_factor = decay_factor, batch_size = batch_size, train_dir = train_dir, checkpoint_steps = checkpoint_steps, moving_average_decay = moving_average_decay, MLP_trainable = False, # For init save_file='model_init.ckpt', # For init random_seed = random_seed) init_model_path = os.path.join(train_dir, 'model_init.ckpt') # Train model ------------------------------------------------- train(sensor, label, num_class = num_segment, list_hidden_nodes = list_hidden_nodes, initial_learning_rate = initial_learning_rate, momentum = momentum, max_steps = max_steps, decay_steps = decay_steps, decay_factor = decay_factor, batch_size = batch_size, train_dir = train_dir, checkpoint_steps = checkpoint_steps, moving_average_decay = moving_average_decay, load_file=init_model_path, random_seed = random_seed) # Save parameters necessary for evaluation -------------------- model_parm = {'random_seed':random_seed, 'num_comp':num_comp, 'num_segment':num_segment, 'num_segmentdata':num_segmentdata, 'num_layer':num_layer, 'list_hidden_nodes':list_hidden_nodes, 'moving_average_decay':moving_average_decay, 'pca_parm':pca_parm} print("Save parameters...") with open(saveparmpath, 'wb') as f: pickle.dump(model_parm, f, pickle.HIGHEST_PROTOCOL) print("done.")
[ "os.path.exists", "tcl.tcl_train.train", "pickle.dump", "os.makedirs", "subfunc.generate_artificial_data.generate_artificial_data", "os.path.join", "subfunc.preprocessing.pca", "shutil.rmtree" ]
[((2002, 2037), 'os.path.join', 'os.path.join', (['train_dir', '"""parm.pkl"""'], {}), "(train_dir, 'parm.pkl')\n", (2014, 2037), False, 'import os\n'), ((2688, 2844), 'subfunc.generate_artificial_data.generate_artificial_data', 'generate_artificial_data', ([], {'num_comp': 'num_comp', 'num_segment': 'num_segment', 'num_segmentdata': 'num_segmentdata', 'num_layer': 'num_layer', 'random_seed': 'random_seed'}), '(num_comp=num_comp, num_segment=num_segment,\n num_segmentdata=num_segmentdata, num_layer=num_layer, random_seed=\n random_seed)\n', (2712, 2844), False, 'from subfunc.generate_artificial_data import generate_artificial_data\n'), ((3117, 3147), 'subfunc.preprocessing.pca', 'pca', (['sensor'], {'num_comp': 'num_comp'}), '(sensor, num_comp=num_comp)\n', (3120, 3147), False, 'from subfunc.preprocessing import pca\n'), ((3214, 3664), 'tcl.tcl_train.train', 'train', (['sensor', 'label'], {'num_class': 'num_segment', 'list_hidden_nodes': 'list_hidden_nodes', 'initial_learning_rate': 'initial_learning_rate', 'momentum': 'momentum', 'max_steps': 'max_steps_init', 'decay_steps': 'decay_steps_init', 'decay_factor': 'decay_factor', 'batch_size': 'batch_size', 'train_dir': 'train_dir', 'checkpoint_steps': 'checkpoint_steps', 'moving_average_decay': 'moving_average_decay', 'MLP_trainable': '(False)', 'save_file': '"""model_init.ckpt"""', 'random_seed': 'random_seed'}), "(sensor, label, num_class=num_segment, list_hidden_nodes=\n list_hidden_nodes, initial_learning_rate=initial_learning_rate,\n momentum=momentum, max_steps=max_steps_init, decay_steps=\n decay_steps_init, decay_factor=decay_factor, batch_size=batch_size,\n train_dir=train_dir, checkpoint_steps=checkpoint_steps,\n moving_average_decay=moving_average_decay, MLP_trainable=False,\n save_file='model_init.ckpt', random_seed=random_seed)\n", (3219, 3664), False, 'from tcl.tcl_train import train\n'), ((3818, 3860), 'os.path.join', 'os.path.join', (['train_dir', '"""model_init.ckpt"""'], {}), "(train_dir, 'model_init.ckpt')\n", (3830, 3860), False, 'import os\n'), ((3927, 4340), 'tcl.tcl_train.train', 'train', (['sensor', 'label'], {'num_class': 'num_segment', 'list_hidden_nodes': 'list_hidden_nodes', 'initial_learning_rate': 'initial_learning_rate', 'momentum': 'momentum', 'max_steps': 'max_steps', 'decay_steps': 'decay_steps', 'decay_factor': 'decay_factor', 'batch_size': 'batch_size', 'train_dir': 'train_dir', 'checkpoint_steps': 'checkpoint_steps', 'moving_average_decay': 'moving_average_decay', 'load_file': 'init_model_path', 'random_seed': 'random_seed'}), '(sensor, label, num_class=num_segment, list_hidden_nodes=\n list_hidden_nodes, initial_learning_rate=initial_learning_rate,\n momentum=momentum, max_steps=max_steps, decay_steps=decay_steps,\n decay_factor=decay_factor, batch_size=batch_size, train_dir=train_dir,\n checkpoint_steps=checkpoint_steps, moving_average_decay=\n moving_average_decay, load_file=init_model_path, random_seed=random_seed)\n', (3932, 4340), False, 'from tcl.tcl_train import train\n'), ((2310, 2335), 'os.path.exists', 'os.path.exists', (['train_dir'], {}), '(train_dir)\n', (2324, 2335), False, 'import os\n'), ((2511, 2533), 'os.makedirs', 'os.makedirs', (['train_dir'], {}), '(train_dir)\n', (2522, 2533), False, 'import os\n'), ((4912, 4963), 'pickle.dump', 'pickle.dump', (['model_parm', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(model_parm, f, pickle.HIGHEST_PROTOCOL)\n', (4923, 4963), False, 'import pickle\n'), ((2408, 2432), 'shutil.rmtree', 'shutil.rmtree', (['train_dir'], {}), '(train_dir)\n', (2421, 2432), False, 'import shutil\n')]
#! /usr/bin/env python # _*_ coding: utf-8 _*_ # Copyright(c) 2019 Nippon Telegraph and Telephone Corporation # Filename: EmControllerStatusGetManager.py import GlobalModule from EmControllerStatusGetExecutor import EmControllerStatusGetExecutor from EmControllerStatusGetTimeKeep import EmControllerStatusGetTimeKeep from EmPeriodicProcessing import EmPeriodicProcessing from EmCommonLog import decorater_log class EmControllerStatusGetManager(EmPeriodicProcessing): ''' Periodic notification management for controller status ''' @decorater_log def __init__(self): ''' Constructor ''' roop_interval = self._get_conf("Em_statusget_notify_interval", 60000) roop_interval = float(roop_interval) / 1000 stop_timeout = self._get_conf( "Timer_periodic_execution_thread_stop_watch", 200) stop_timeout = float(stop_timeout) / 1000 super(EmControllerStatusGetManager, self).__init__( exec_class=EmControllerStatusGetExecutor, roop_interval=roop_interval, stop_timeout=stop_timeout) self.time_keeper = EmControllerStatusGetTimeKeep(self.roop_interval) @decorater_log def _get_conf(self, key=None, default_val=None): ''' Necessary config is acquired from config management part. Argument: key ; key (str) default_val ; default value Return value; config definition to be acquired : depending on config definition type ''' is_ok, value = GlobalModule.EM_CONFIG.read_sys_common_conf(key) if not is_ok or value is None: value = default_val return value
[ "EmControllerStatusGetTimeKeep.EmControllerStatusGetTimeKeep", "GlobalModule.EM_CONFIG.read_sys_common_conf" ]
[((1166, 1215), 'EmControllerStatusGetTimeKeep.EmControllerStatusGetTimeKeep', 'EmControllerStatusGetTimeKeep', (['self.roop_interval'], {}), '(self.roop_interval)\n', (1195, 1215), False, 'from EmControllerStatusGetTimeKeep import EmControllerStatusGetTimeKeep\n'), ((1606, 1654), 'GlobalModule.EM_CONFIG.read_sys_common_conf', 'GlobalModule.EM_CONFIG.read_sys_common_conf', (['key'], {}), '(key)\n', (1649, 1654), False, 'import GlobalModule\n')]
import sqlalchemy as db class Queries: def __init__(self, session): self.session = session self.queries = db.Table('AIRAVAT_QUERY_PLAN_INFO', session.dbEngine.metadata, autoload=True, autoload_with=session.dbEngine.engine) def fetchAll(self): queries = db.select([self.queries]) resultSet = self.session.dbEngine.db_session.query(queries) return [r._asdict() for r in resultSet] # return resultSet.__dict__
[ "sqlalchemy.Table", "sqlalchemy.select" ]
[((128, 249), 'sqlalchemy.Table', 'db.Table', (['"""AIRAVAT_QUERY_PLAN_INFO"""', 'session.dbEngine.metadata'], {'autoload': '(True)', 'autoload_with': 'session.dbEngine.engine'}), "('AIRAVAT_QUERY_PLAN_INFO', session.dbEngine.metadata, autoload=\n True, autoload_with=session.dbEngine.engine)\n", (136, 249), True, 'import sqlalchemy as db\n'), ((384, 409), 'sqlalchemy.select', 'db.select', (['[self.queries]'], {}), '([self.queries])\n', (393, 409), True, 'import sqlalchemy as db\n')]
# Copyright 2020–2021 Cirq on IQM developers # # 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. """Tests for the Adonis device. """ # pylint: disable=redefined-outer-name,no-self-use,duplicate-code from __future__ import annotations import cirq import numpy as np import pytest import cirq_iqm.adonis as ad def dist(U: np.ndarray, W: np.ndarray) -> float: r"""Distance between two unitary matrices, modulo global phase. Returns: minimal squared Frobenius norm distance between the unitaries over all global phases .. math:: \mathrm{dist}(U, W) = \inf_{\phi \in \mathbb{R}} \|U - e^{i \phi} W\|_F^2 = 2 (\dim_A - |\mathrm{Tr}(U^\dagger W)|) """ return 2 * (len(U) - np.abs(np.trace(U.T.conj() @ W))) @pytest.fixture(scope='module') def adonis(): """Adonis device fixture.""" return ad.Adonis() # define various groups of gates to test native_1q_gates = [ cirq.X, cirq.Y, cirq.XPowGate(exponent=0.23), cirq.YPowGate(exponent=0.71), cirq.PhasedXPowGate(phase_exponent=1.7, exponent=-0.58), cirq.Z, cirq.ZPowGate(exponent=-0.23), ] finally_decomposed_1q_gates = [] native_2q_gates = [ cirq.CZ, ] non_native_1q_gates = [ cirq.H, cirq.HPowGate(exponent=-0.55), cirq.PhasedXZGate(x_exponent=0.2, z_exponent=-0.5, axis_phase_exponent=0.75), ] non_native_2q_gates = [ cirq.ISWAP, cirq.ISwapPowGate(exponent=0.27), cirq.SWAP, cirq.CNOT, cirq.CXPowGate(exponent=-2.2), cirq.CZPowGate(exponent=1.6), cirq.ZZPowGate(exponent=-0.94), ] class TestOperationValidation: """Nativity and validation of various operations.""" @pytest.mark.parametrize('gate', native_1q_gates) @pytest.mark.parametrize('q', [0, 2, 3]) def test_native_single_qubit_gates(self, adonis, gate, q): """Native operations must pass validation.""" adonis.validate_operation(gate(adonis.qubits[q])) adonis.validate_operation(gate(adonis.qubits[q]).with_tags('tag_foo')) @pytest.mark.parametrize('gate', native_2q_gates) def test_native_two_qubit_gates(self, adonis, gate): """Native operations must pass validation.""" q0, _, q2 = adonis.qubits[:3] adonis.validate_operation(gate(q0, q2)) adonis.validate_operation(gate(q2, q0)) @pytest.mark.parametrize('meas', [ cirq.measure, lambda q: cirq.measure(q, key='test'), ]) def test_native_measurements(self, adonis, meas): """Native operations must pass validation.""" adonis.validate_operation(meas(adonis.qubits[0])) @pytest.mark.parametrize('gate', non_native_1q_gates) def test_non_native_single_qubit_gates(self, adonis, gate): """Non-native operations must not pass validation.""" q0 = adonis.qubits[0] with pytest.raises(ValueError, match='Unsupported gate type'): adonis.validate_operation(gate(q0)) with pytest.raises(ValueError, match='Unsupported gate type'): adonis.validate_operation(gate(q0).with_tags('tag_foo')) @pytest.mark.parametrize('gate', non_native_2q_gates) def test_non_native_two_qubit_gates(self, adonis, gate): """Non-native operations must not pass validation.""" q0, _, q2 = adonis.qubits[:3] with pytest.raises(ValueError, match='Unsupported gate type'): adonis.validate_operation(gate(q0, q2)) with pytest.raises(ValueError, match='Unsupported gate type'): adonis.validate_operation(gate(q2, q0)) @pytest.mark.parametrize('qubit', [ cirq.NamedQubit('xxx'), cirq.NamedQubit('QB1'), # name ok, but not a device qubit cirq.GridQubit(0, 1), ]) def test_qubits_not_on_device(self, adonis, qubit): """Gates operating on qubits not on device must not pass validation.""" with pytest.raises(ValueError, match='Qubit not on device'): adonis.validate_operation(cirq.X(qubit)) @pytest.mark.parametrize('gate', native_2q_gates) def test_qubits_not_connected(self, adonis, gate): """Native two-qubit gates operating on non-connected qubits must not pass validation.""" q0, q1 = adonis.qubits[:2] with pytest.raises(ValueError, match='Unsupported qubit connectivity'): adonis.validate_operation(gate(q0, q1)) with pytest.raises(ValueError, match='Unsupported qubit connectivity'): adonis.validate_operation(gate(q1, q0)) class TestGateDecomposition: """Decomposing gates.""" @staticmethod def is_native(op_or_op_list) -> bool: """True iff the op_list consists of native operations only.""" if ad.Adonis.is_native_operation(op_or_op_list): return True for op in op_or_op_list: if not ad.Adonis.is_native_operation(op): raise TypeError('Non-native operation: {}'.format(op)) return True @pytest.mark.parametrize('gate', native_1q_gates) def test_native_single_qubit_gates(self, adonis, gate): """Native single-qubit gates do not decompose further.""" q0 = adonis.qubits[0] for op in ( gate.on(q0), gate.on(q0).with_tags('tag_baz'), ): decomposition = adonis.decompose_operation_full(op) assert decomposition == [op] assert TestGateDecomposition.is_native(decomposition) @pytest.mark.parametrize('gate', non_native_1q_gates) def test_non_native_single_qubit_gates(self, adonis, gate): """Non-native single qubit gates should decompose into native gates.""" q1 = adonis.qubits[1] for op in ( gate.on(q1), gate.on(q1).with_tags('tag_baz'), ): decomposition = adonis.decompose_operation_full(op) assert TestGateDecomposition.is_native(decomposition) @pytest.mark.parametrize('gate', native_2q_gates) def test_native_two_qubit_gate(self, adonis, gate): """Native two-qubit gates do not decompose further.""" q0, _, q2 = adonis.qubits[:3] for op in ( gate.on(q0, q2), gate.on(q2, q0).with_tags('tag_baz'), ): decomposition = adonis.decompose_operation_full(op) assert decomposition == [op] assert TestGateDecomposition.is_native(decomposition) @pytest.mark.parametrize('gate', non_native_2q_gates) def test_non_native_two_qubit_gates(self, adonis, gate): """Non-native two-qubit gates should decompose into native gates.""" q0, q1, q2 = adonis.qubits[:3] for op in ( gate.on(q0, q2), gate.on(q2, q0).with_tags('tag_baz'), gate.on(q2, q1), ): decomposition = adonis.decompose_operation_full(op) assert TestGateDecomposition.is_native(decomposition) # matrix representations must match up to global phase U = cirq.Circuit(op)._unitary_() W = cirq.Circuit(decomposition)._unitary_() assert dist(U, W) == pytest.approx(0) class TestCircuitValidation: """Validating entire circuits.""" def test_valid_circuit(self, adonis): """A valid circuit should pass validation.""" q0, q1 = adonis.qubits[:2] valid_circuit = cirq.Circuit(device=adonis) valid_circuit.append(cirq.Y(q0)) valid_circuit.append(cirq.measure(q0, key='a')) valid_circuit.append(cirq.measure(q1, key='b')) adonis.validate_circuit(valid_circuit) def test_invalid_circuit(self, adonis): """An invalid circuit should not pass validation.""" q0, q1 = adonis.qubits[:2] invalid_circuit = cirq.Circuit(device=adonis) invalid_circuit.append(cirq.Y(q0)) invalid_circuit.append(cirq.measure(q0, key='a')) invalid_circuit.append(cirq.measure(q1, key='a')) with pytest.raises(ValueError, match='Measurement key a repeated'): adonis.validate_circuit(invalid_circuit)
[ "cirq.GridQubit", "cirq.Circuit", "cirq.PhasedXZGate", "cirq.ISwapPowGate", "pytest.fixture", "cirq.HPowGate", "cirq.YPowGate", "cirq.ZZPowGate", "cirq_iqm.adonis.Adonis", "cirq.CZPowGate", "cirq.ZPowGate", "cirq.NamedQubit", "pytest.raises", "pytest.approx", "cirq.PhasedXPowGate", "ci...
[((1247, 1277), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1261, 1277), False, 'import pytest\n'), ((1336, 1347), 'cirq_iqm.adonis.Adonis', 'ad.Adonis', ([], {}), '()\n', (1345, 1347), True, 'import cirq_iqm.adonis as ad\n'), ((1440, 1468), 'cirq.XPowGate', 'cirq.XPowGate', ([], {'exponent': '(0.23)'}), '(exponent=0.23)\n', (1453, 1468), False, 'import cirq\n'), ((1474, 1502), 'cirq.YPowGate', 'cirq.YPowGate', ([], {'exponent': '(0.71)'}), '(exponent=0.71)\n', (1487, 1502), False, 'import cirq\n'), ((1508, 1563), 'cirq.PhasedXPowGate', 'cirq.PhasedXPowGate', ([], {'phase_exponent': '(1.7)', 'exponent': '(-0.58)'}), '(phase_exponent=1.7, exponent=-0.58)\n', (1527, 1563), False, 'import cirq\n'), ((1581, 1610), 'cirq.ZPowGate', 'cirq.ZPowGate', ([], {'exponent': '(-0.23)'}), '(exponent=-0.23)\n', (1594, 1610), False, 'import cirq\n'), ((1725, 1754), 'cirq.HPowGate', 'cirq.HPowGate', ([], {'exponent': '(-0.55)'}), '(exponent=-0.55)\n', (1738, 1754), False, 'import cirq\n'), ((1760, 1836), 'cirq.PhasedXZGate', 'cirq.PhasedXZGate', ([], {'x_exponent': '(0.2)', 'z_exponent': '(-0.5)', 'axis_phase_exponent': '(0.75)'}), '(x_exponent=0.2, z_exponent=-0.5, axis_phase_exponent=0.75)\n', (1777, 1836), False, 'import cirq\n'), ((1885, 1917), 'cirq.ISwapPowGate', 'cirq.ISwapPowGate', ([], {'exponent': '(0.27)'}), '(exponent=0.27)\n', (1902, 1917), False, 'import cirq\n'), ((1953, 1982), 'cirq.CXPowGate', 'cirq.CXPowGate', ([], {'exponent': '(-2.2)'}), '(exponent=-2.2)\n', (1967, 1982), False, 'import cirq\n'), ((1988, 2016), 'cirq.CZPowGate', 'cirq.CZPowGate', ([], {'exponent': '(1.6)'}), '(exponent=1.6)\n', (2002, 2016), False, 'import cirq\n'), ((2022, 2052), 'cirq.ZZPowGate', 'cirq.ZZPowGate', ([], {'exponent': '(-0.94)'}), '(exponent=-0.94)\n', (2036, 2052), False, 'import cirq\n'), ((2152, 2200), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'native_1q_gates'], {}), "('gate', native_1q_gates)\n", (2175, 2200), False, 'import pytest\n'), ((2206, 2245), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""q"""', '[0, 2, 3]'], {}), "('q', [0, 2, 3])\n", (2229, 2245), False, 'import pytest\n'), ((2507, 2555), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'native_2q_gates'], {}), "('gate', native_2q_gates)\n", (2530, 2555), False, 'import pytest\n'), ((3092, 3144), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'non_native_1q_gates'], {}), "('gate', non_native_1q_gates)\n", (3115, 3144), False, 'import pytest\n'), ((3569, 3621), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'non_native_2q_gates'], {}), "('gate', non_native_2q_gates)\n", (3592, 3621), False, 'import pytest\n'), ((4474, 4522), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'native_2q_gates'], {}), "('gate', native_2q_gates)\n", (4497, 4522), False, 'import pytest\n'), ((5434, 5482), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'native_1q_gates'], {}), "('gate', native_1q_gates)\n", (5457, 5482), False, 'import pytest\n'), ((5928, 5980), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'non_native_1q_gates'], {}), "('gate', non_native_1q_gates)\n", (5951, 5980), False, 'import pytest\n'), ((6403, 6451), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'native_2q_gates'], {}), "('gate', native_2q_gates)\n", (6426, 6451), False, 'import pytest\n'), ((6906, 6958), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""gate"""', 'non_native_2q_gates'], {}), "('gate', non_native_2q_gates)\n", (6929, 6958), False, 'import pytest\n'), ((5180, 5224), 'cirq_iqm.adonis.Adonis.is_native_operation', 'ad.Adonis.is_native_operation', (['op_or_op_list'], {}), '(op_or_op_list)\n', (5209, 5224), True, 'import cirq_iqm.adonis as ad\n'), ((7864, 7891), 'cirq.Circuit', 'cirq.Circuit', ([], {'device': 'adonis'}), '(device=adonis)\n', (7876, 7891), False, 'import cirq\n'), ((8262, 8289), 'cirq.Circuit', 'cirq.Circuit', ([], {'device': 'adonis'}), '(device=adonis)\n', (8274, 8289), False, 'import cirq\n'), ((3316, 3372), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Unsupported gate type"""'}), "(ValueError, match='Unsupported gate type')\n", (3329, 3372), False, 'import pytest\n'), ((3436, 3492), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Unsupported gate type"""'}), "(ValueError, match='Unsupported gate type')\n", (3449, 3492), False, 'import pytest\n'), ((3798, 3854), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Unsupported gate type"""'}), "(ValueError, match='Unsupported gate type')\n", (3811, 3854), False, 'import pytest\n'), ((3922, 3978), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Unsupported gate type"""'}), "(ValueError, match='Unsupported gate type')\n", (3935, 3978), False, 'import pytest\n'), ((4359, 4413), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Qubit not on device"""'}), "(ValueError, match='Qubit not on device')\n", (4372, 4413), False, 'import pytest\n'), ((4081, 4103), 'cirq.NamedQubit', 'cirq.NamedQubit', (['"""xxx"""'], {}), "('xxx')\n", (4096, 4103), False, 'import cirq\n'), ((4113, 4135), 'cirq.NamedQubit', 'cirq.NamedQubit', (['"""QB1"""'], {}), "('QB1')\n", (4128, 4135), False, 'import cirq\n'), ((4180, 4200), 'cirq.GridQubit', 'cirq.GridQubit', (['(0)', '(1)'], {}), '(0, 1)\n', (4194, 4200), False, 'import cirq\n'), ((4725, 4790), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Unsupported qubit connectivity"""'}), "(ValueError, match='Unsupported qubit connectivity')\n", (4738, 4790), False, 'import pytest\n'), ((4858, 4923), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Unsupported qubit connectivity"""'}), "(ValueError, match='Unsupported qubit connectivity')\n", (4871, 4923), False, 'import pytest\n'), ((7921, 7931), 'cirq.Y', 'cirq.Y', (['q0'], {}), '(q0)\n', (7927, 7931), False, 'import cirq\n'), ((7962, 7987), 'cirq.measure', 'cirq.measure', (['q0'], {'key': '"""a"""'}), "(q0, key='a')\n", (7974, 7987), False, 'import cirq\n'), ((8018, 8043), 'cirq.measure', 'cirq.measure', (['q1'], {'key': '"""b"""'}), "(q1, key='b')\n", (8030, 8043), False, 'import cirq\n'), ((8321, 8331), 'cirq.Y', 'cirq.Y', (['q0'], {}), '(q0)\n', (8327, 8331), False, 'import cirq\n'), ((8364, 8389), 'cirq.measure', 'cirq.measure', (['q0'], {'key': '"""a"""'}), "(q0, key='a')\n", (8376, 8389), False, 'import cirq\n'), ((8422, 8447), 'cirq.measure', 'cirq.measure', (['q1'], {'key': '"""a"""'}), "(q1, key='a')\n", (8434, 8447), False, 'import cirq\n'), ((8463, 8524), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Measurement key a repeated"""'}), "(ValueError, match='Measurement key a repeated')\n", (8476, 8524), False, 'import pytest\n'), ((2883, 2910), 'cirq.measure', 'cirq.measure', (['q'], {'key': '"""test"""'}), "(q, key='test')\n", (2895, 2910), False, 'import cirq\n'), ((4453, 4466), 'cirq.X', 'cirq.X', (['qubit'], {}), '(qubit)\n', (4459, 4466), False, 'import cirq\n'), ((5302, 5335), 'cirq_iqm.adonis.Adonis.is_native_operation', 'ad.Adonis.is_native_operation', (['op'], {}), '(op)\n', (5331, 5335), True, 'import cirq_iqm.adonis as ad\n'), ((7621, 7637), 'pytest.approx', 'pytest.approx', (['(0)'], {}), '(0)\n', (7634, 7637), False, 'import pytest\n'), ((7503, 7519), 'cirq.Circuit', 'cirq.Circuit', (['op'], {}), '(op)\n', (7515, 7519), False, 'import cirq\n'), ((7548, 7575), 'cirq.Circuit', 'cirq.Circuit', (['decomposition'], {}), '(decomposition)\n', (7560, 7575), False, 'import cirq\n')]
#https://github.com/ec500-software-engineering/exercise-1-modularity-mmark9/blob/master/heart_monitor/main_app.py import display import sensor_readers import prediction_engine import notification_manager import notifications_sender import realtime_data_processor from multiprocessing import Queue from common_types import Contact from database import InMemorySimpleDatabase def main(cmd_args): ''' Entry point of application; in here we spawn the sensor threads, AI thread and realtime data processing thread and then wait till we need to quit :param cmd_args: dictionary of expected command line arguments :return: 0 on success and non-zero on error ''' data_proc_queue = Queue() tty = display.TextTerminalDisplay() notification_man = notification_manager.FlexibleNotificationManager( Contact('<NAME>', None, None, None), notifications_sender.MockSMSSender(), notifications_sender.MockTelegramSender(), notifications_sender.MockEmailSender() ) database = InMemorySimpleDatabase() ai_engine = prediction_engine.PredictionEngine(10, notification_man, database) pulse_reader = sensor_readers.BloodPulseSensorReader(1, data_proc_queue, tty, database) oxy_reader = sensor_readers.BloodOxygenSensorReader(4, data_proc_queue, tty, database) pressure_reader = sensor_readers.BloodPressureSensorReader(2, data_proc_queue, tty, database) real_time_proc = realtime_data_processor.RealTimeDataProcessor(data_proc_queue, notification_man) pulse_reader.start() oxy_reader.start() pressure_reader.start() real_time_proc.start() ai_engine.start() oxy_reader.join() pressure_reader.join() pulse_reader.join() real_time_proc.join() return 0 if __name__ == '__main__': main(None)
[ "sensor_readers.BloodPulseSensorReader", "notifications_sender.MockTelegramSender", "database.InMemorySimpleDatabase", "common_types.Contact", "realtime_data_processor.RealTimeDataProcessor", "notifications_sender.MockEmailSender", "sensor_readers.BloodOxygenSensorReader", "prediction_engine.Predictio...
[((704, 711), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (709, 711), False, 'from multiprocessing import Queue\n'), ((722, 751), 'display.TextTerminalDisplay', 'display.TextTerminalDisplay', ([], {}), '()\n', (749, 751), False, 'import display\n'), ((1035, 1059), 'database.InMemorySimpleDatabase', 'InMemorySimpleDatabase', ([], {}), '()\n', (1057, 1059), False, 'from database import InMemorySimpleDatabase\n'), ((1076, 1142), 'prediction_engine.PredictionEngine', 'prediction_engine.PredictionEngine', (['(10)', 'notification_man', 'database'], {}), '(10, notification_man, database)\n', (1110, 1142), False, 'import prediction_engine\n'), ((1162, 1234), 'sensor_readers.BloodPulseSensorReader', 'sensor_readers.BloodPulseSensorReader', (['(1)', 'data_proc_queue', 'tty', 'database'], {}), '(1, data_proc_queue, tty, database)\n', (1199, 1234), False, 'import sensor_readers\n'), ((1252, 1325), 'sensor_readers.BloodOxygenSensorReader', 'sensor_readers.BloodOxygenSensorReader', (['(4)', 'data_proc_queue', 'tty', 'database'], {}), '(4, data_proc_queue, tty, database)\n', (1290, 1325), False, 'import sensor_readers\n'), ((1348, 1423), 'sensor_readers.BloodPressureSensorReader', 'sensor_readers.BloodPressureSensorReader', (['(2)', 'data_proc_queue', 'tty', 'database'], {}), '(2, data_proc_queue, tty, database)\n', (1388, 1423), False, 'import sensor_readers\n'), ((1445, 1530), 'realtime_data_processor.RealTimeDataProcessor', 'realtime_data_processor.RealTimeDataProcessor', (['data_proc_queue', 'notification_man'], {}), '(data_proc_queue, notification_man\n )\n', (1490, 1530), False, 'import realtime_data_processor\n'), ((833, 868), 'common_types.Contact', 'Contact', (['"""<NAME>"""', 'None', 'None', 'None'], {}), "('<NAME>', None, None, None)\n", (840, 868), False, 'from common_types import Contact\n'), ((878, 914), 'notifications_sender.MockSMSSender', 'notifications_sender.MockSMSSender', ([], {}), '()\n', (912, 914), False, 'import notifications_sender\n'), ((924, 965), 'notifications_sender.MockTelegramSender', 'notifications_sender.MockTelegramSender', ([], {}), '()\n', (963, 965), False, 'import notifications_sender\n'), ((975, 1013), 'notifications_sender.MockEmailSender', 'notifications_sender.MockEmailSender', ([], {}), '()\n', (1011, 1013), False, 'import notifications_sender\n')]
import tensorflow as tf class Module(object): def __init__(self, l2_reg=False, l2_reg_scale=0.0001, trainable=False): self._l2_reg = l2_reg if self._l2_reg: self._l2_reg_scale = l2_reg_scale self._trainable = trainable def Residual(self, x, args): input = x assert len(args) == 5, '[Residual] Not enough Argument -> [kernel, filter, strides, bottleneck, No]' with tf.variable_scope('Residual_{}'.format(args[4])): if args[3]: x = self.BN(x=x, args=None) x = self.ReLU(x=x, args=None) x = self.conv(x=x, args=[1, args[1], 1, None]) x = self.BN(x=x, args=None) x = self.ReLU(x=x, args=None) x = self.conv(x=x, args=[args[0], args[1], args[2], None]) x = self.BN(x=x, args=None) x = self.ReLU(x=x, args=None) x = self.conv(x=x, args=[1, args[1],1, None]) else: x = self.BN(x=x, args=None) x = self.ReLU(x=x, args=None) x = self.conv(x=x, args=[args[0], args[1], 1, None]) x = self.BN(x=x, args=None) x = self.ReLU(x=x, args=None) x = self.conv(x=x, args=[args[0], args[1], args[2], None]) if input.shape[1] != x.shape[1] or input.shape[3] != x.shape[3]: input = self.conv(x=input, args=[1, args[1], args[2], None]) return x + input def conv1d(self, x, args, name=None): """ convolutionを行う parameters ---------- x : tensor input image 4D args : list [kernel, filter, strides, activation, dilation_rate, padding] or [kernel, filter, strides, activation, dilation_rate] name : str layer name returns ---------- feature map : tensor 畳み込みした特徴マップ Else ---------- padding = same """ assert len(args) >= 4, '[conv] Not enough Argument -> [kernel, filter, strides, activation]' assert len(args) < 7, '[conv] Not enough Argument -> [kernel, filter, strides, dilation_rate, activation, padding]' if len(args) == 4: args.append(1) args.append('same') elif len(args) == 5: args.append('same') regularizer = tf.contrib.layers.l2_regularizer(scale=self._l2_reg_scale) if self._l2_reg else None return tf.layers.conv1d(inputs=x, filters=args[1], kernel_size=args[0], strides=args[2], padding=args[5], activation=args[3], dilation_rate=args[4], kernel_regularizer=regularizer, trainable=self._trainable, name=name) def conv(self, x, args, name=None): """ convolutionを行う parameters ---------- x : tensor input image 4D args : list [kernel, filter, strides, activation] name : str layer name returns ---------- feature map : tensor 畳み込みした特徴マップ Else ---------- padding = same """ assert len(args) >= 4, '[conv] Not enough Argument -> [kernel, filter, strides, activation, padding]' assert len(args) < 6, '[conv] Not enough Argument -> [kernel, filter, strides, activation, padding]' if len(args) == 4: args.append('same') regularizer = tf.contrib.layers.l2_regularizer(scale=self._l2_reg_scale) if self._l2_reg else None return tf.layers.conv2d(inputs=x, filters=args[1], kernel_size=[args[0], args[0]], strides=[args[2], args[2]], padding=args[4], activation=args[3], kernel_regularizer=regularizer, trainable=self._trainable, name=name) def deconv(self, x, args, name=None): """ de-convolutionを行う parameters ---------- x : tensor input image 4D args : list [kernel, filter, strides, activation, padding] name : str layer name returns ---------- feature map : tensor 畳み込みした特徴マップ Else ---------- padding = same """ assert len(args) >= 4, '[deconv] Not enough Argument -> [kernel, filter, strides, activation, padding]' assert len(args) < 6, '[deconv] Not enough Argument -> [kernel, filter, strides, activation, padding]' if len(args) == 4: args.append('same') assert len(x.shape) == 4 regularizer = tf.contrib.layers.l2_regularizer(scale=self._l2_reg_scale) if self._l2_reg else None return tf.layers.conv2d_transpose(inputs=x, filters=args[1], kernel_size=[args[0], args[0]], strides=[args[2], args[2]], padding=args[4], activation=args[3], kernel_regularizer=regularizer, trainable=self._trainable) def reshape(self, x, args): """ Reshapeを行う parameters ---------- x : tensor input image 4D args : list [reshapeしたいサイズ] ex) [-1, 28, 28, 1] returns ---------- reshape : tensor reshapeしたtensor """ return tf.reshape(tensor=x, shape=args[0]) def max_pool(self, x, args): """ Max poolingを行う parameters ---------- x : tensor input image 4D args : list [pool_size, strides, padding] returns ---------- feature map : tensor Poolingした特徴マップ """ assert len(args) == 3, '[max_pool] Not enough Argument -> [pool_size, strides, padding]' return tf.layers.max_pooling2d(inputs=x, pool_size=[args[0], args[0]], strides=[args[1], args[1]], padding=args[2]) def avg_pool(self, x, args): """ Average poolingを行う parameters ---------- x : tensor input image 4D args : list [pool_size, strides, padding] returns ---------- feature map : tensor Poolingした特徴マップ """ assert len(args) == 3, '[avg_pool] Not enough Argument -> [pool_size, strides, padding]' return tf.layers.average_pooling2d(inputs=x, pool_size=[args[0], args[0]], strides=[args[1], args[1]], padding=args[2]) def gap(self, x, args): #global_average_pooling """ Global Average poolingを行う parameters ---------- x : tensor input image 4D args : list [output_dimension] returns ---------- x : tensor GAPしたtensor """ assert len(args) == 1, '[gap] Not enough Argument -> [output_dim]' with tf.variable_scope('GAP'): if len(x.shape) == 4: x = self.conv(x,[1, args[0], 1, None]) for _ in range(2): x = tf.reduce_mean(x, axis=1) else: x = self.conv1d(x,[1, args[0], 1, None]) x = tf.reduce_mean(x, axis=1) return x def BN(self, x, args): """ Batch Normalizationを行う parameters ---------- x : tensor input image 4D args : list [None]で良い returns ---------- x : tensor BNしたtensor attention ---------- tf.get_collection(tf.GraphKeys.UPDATE_OPS)が必須 """ return tf.layers.batch_normalization(inputs=x, trainable=self._trainable) def ReLU(self, x, args): """ ReLU : Activation function parameters ---------- x : tensor input image 4D args : list [None]で良い returns ---------- x : ReLU(x) """ with tf.variable_scope('ReLU'): return tf.nn.relu(x) def Leaky_ReLU(self, x, args): """ Leaky_ReLU : Activation function parameters ---------- x : tensor input image 4D args : list [None]で良い returns ---------- x : Leaky_ReLU(x) """ with tf.variable_scope('Leaky_ReLU'): return tf.nn.leaky_relu(x) def tanh(self, x, args): """ tanh : Activation function parameters ---------- x : tensor input image 4D args : list [None]で良い returns ---------- x : tanh(x) """ with tf.variable_scope('tanh'): return tf.nn.tanh(x) def sigmoid(self, x, args): """ sigmoid : Activation function parameters ---------- x : tensor input image 4D args : list [None]で良い returns ---------- x : sigmoid(x) """ with tf.variable_scope('Sigmoid'): return tf.nn.sigmoid(x) def fc(self, x, args): # args = [units, activation=tf.nn.relu] """ Fully connect parameters ---------- x : tensor input image 4D args : list [units, activation] returns ---------- feature map : tensor 全結合の特徴ベクトル """ assert len(args) == 2, '[FC] Not enough Argument -> [units, activation]' if len(x.shape) > 2: x = tf.layers.flatten(x, name='flatten') regularizer = tf.contrib.layers.l2_regularizer(scale=self._l2_reg_scale) if self._l2_reg else None x = tf.layers.dense(inputs=x, units=args[0], activation=args[1], kernel_regularizer=regularizer, use_bias=True) return x def dropout(self, x, args): """ Fully connect + Dropout parameters ---------- x : tensor input image 4D args : list [units, activation, rate] returns ---------- feature map : tensor 全結合の特徴ベクトル """ assert len(args) == 3, '[Dropout] Not enough Argument -> [units, activation, rate]' x = self.fc(x=x, args=args[:2]) return tf.layers.dropout(inputs=x, rate=args[2], training=self._trainable)
[ "tensorflow.layers.dense", "tensorflow.layers.average_pooling2d", "tensorflow.nn.tanh", "tensorflow.variable_scope", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.layers.max_pooling2d", "tensorflow.nn.relu", "tensorflow.layers.flatten", "tensorflow.nn.leaky_relu", "tensorflow.layers.conv...
[((2575, 2795), 'tensorflow.layers.conv1d', 'tf.layers.conv1d', ([], {'inputs': 'x', 'filters': 'args[1]', 'kernel_size': 'args[0]', 'strides': 'args[2]', 'padding': 'args[5]', 'activation': 'args[3]', 'dilation_rate': 'args[4]', 'kernel_regularizer': 'regularizer', 'trainable': 'self._trainable', 'name': 'name'}), '(inputs=x, filters=args[1], kernel_size=args[0], strides=\n args[2], padding=args[5], activation=args[3], dilation_rate=args[4],\n kernel_regularizer=regularizer, trainable=self._trainable, name=name)\n', (2591, 2795), True, 'import tensorflow as tf\n'), ((3913, 4131), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', ([], {'inputs': 'x', 'filters': 'args[1]', 'kernel_size': '[args[0], args[0]]', 'strides': '[args[2], args[2]]', 'padding': 'args[4]', 'activation': 'args[3]', 'kernel_regularizer': 'regularizer', 'trainable': 'self._trainable', 'name': 'name'}), '(inputs=x, filters=args[1], kernel_size=[args[0], args[0]],\n strides=[args[2], args[2]], padding=args[4], activation=args[3],\n kernel_regularizer=regularizer, trainable=self._trainable, name=name)\n', (3929, 4131), True, 'import tensorflow as tf\n'), ((5272, 5490), 'tensorflow.layers.conv2d_transpose', 'tf.layers.conv2d_transpose', ([], {'inputs': 'x', 'filters': 'args[1]', 'kernel_size': '[args[0], args[0]]', 'strides': '[args[2], args[2]]', 'padding': 'args[4]', 'activation': 'args[3]', 'kernel_regularizer': 'regularizer', 'trainable': 'self._trainable'}), '(inputs=x, filters=args[1], kernel_size=[args[0],\n args[0]], strides=[args[2], args[2]], padding=args[4], activation=args[\n 3], kernel_regularizer=regularizer, trainable=self._trainable)\n', (5298, 5490), True, 'import tensorflow as tf\n'), ((6128, 6163), 'tensorflow.reshape', 'tf.reshape', ([], {'tensor': 'x', 'shape': 'args[0]'}), '(tensor=x, shape=args[0])\n', (6138, 6163), True, 'import tensorflow as tf\n'), ((6603, 6716), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'x', 'pool_size': '[args[0], args[0]]', 'strides': '[args[1], args[1]]', 'padding': 'args[2]'}), '(inputs=x, pool_size=[args[0], args[0]], strides=[\n args[1], args[1]], padding=args[2])\n', (6626, 6716), True, 'import tensorflow as tf\n'), ((7276, 7393), 'tensorflow.layers.average_pooling2d', 'tf.layers.average_pooling2d', ([], {'inputs': 'x', 'pool_size': '[args[0], args[0]]', 'strides': '[args[1], args[1]]', 'padding': 'args[2]'}), '(inputs=x, pool_size=[args[0], args[0]], strides\n =[args[1], args[1]], padding=args[2])\n', (7303, 7393), True, 'import tensorflow as tf\n'), ((8683, 8749), 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', ([], {'inputs': 'x', 'trainable': 'self._trainable'}), '(inputs=x, trainable=self._trainable)\n', (8712, 8749), True, 'import tensorflow as tf\n'), ((10835, 10946), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'x', 'units': 'args[0]', 'activation': 'args[1]', 'kernel_regularizer': 'regularizer', 'use_bias': '(True)'}), '(inputs=x, units=args[0], activation=args[1],\n kernel_regularizer=regularizer, use_bias=True)\n', (10850, 10946), True, 'import tensorflow as tf\n'), ((11434, 11501), 'tensorflow.layers.dropout', 'tf.layers.dropout', ([], {'inputs': 'x', 'rate': 'args[2]', 'training': 'self._trainable'}), '(inputs=x, rate=args[2], training=self._trainable)\n', (11451, 11501), True, 'import tensorflow as tf\n'), ((2475, 2533), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', ([], {'scale': 'self._l2_reg_scale'}), '(scale=self._l2_reg_scale)\n', (2507, 2533), True, 'import tensorflow as tf\n'), ((3813, 3871), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', ([], {'scale': 'self._l2_reg_scale'}), '(scale=self._l2_reg_scale)\n', (3845, 3871), True, 'import tensorflow as tf\n'), ((5172, 5230), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', ([], {'scale': 'self._l2_reg_scale'}), '(scale=self._l2_reg_scale)\n', (5204, 5230), True, 'import tensorflow as tf\n'), ((7939, 7963), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""GAP"""'], {}), "('GAP')\n", (7956, 7963), True, 'import tensorflow as tf\n'), ((9046, 9071), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""ReLU"""'], {}), "('ReLU')\n", (9063, 9071), True, 'import tensorflow as tf\n'), ((9092, 9105), 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {}), '(x)\n', (9102, 9105), True, 'import tensorflow as tf\n'), ((9416, 9447), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Leaky_ReLU"""'], {}), "('Leaky_ReLU')\n", (9433, 9447), True, 'import tensorflow as tf\n'), ((9468, 9487), 'tensorflow.nn.leaky_relu', 'tf.nn.leaky_relu', (['x'], {}), '(x)\n', (9484, 9487), True, 'import tensorflow as tf\n'), ((9780, 9805), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""tanh"""'], {}), "('tanh')\n", (9797, 9805), True, 'import tensorflow as tf\n'), ((9826, 9839), 'tensorflow.nn.tanh', 'tf.nn.tanh', (['x'], {}), '(x)\n', (9836, 9839), True, 'import tensorflow as tf\n'), ((10141, 10169), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Sigmoid"""'], {}), "('Sigmoid')\n", (10158, 10169), True, 'import tensorflow as tf\n'), ((10190, 10206), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['x'], {}), '(x)\n', (10203, 10206), True, 'import tensorflow as tf\n'), ((10679, 10715), 'tensorflow.layers.flatten', 'tf.layers.flatten', (['x'], {'name': '"""flatten"""'}), "(x, name='flatten')\n", (10696, 10715), True, 'import tensorflow as tf\n'), ((10738, 10796), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', ([], {'scale': 'self._l2_reg_scale'}), '(scale=self._l2_reg_scale)\n', (10770, 10796), True, 'import tensorflow as tf\n'), ((8234, 8259), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (8248, 8259), True, 'import tensorflow as tf\n'), ((8113, 8138), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (8127, 8138), True, 'import tensorflow as tf\n')]
#! /usr/bin/python3 # Copyright 2018 <NAME> # # 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. """ Optimize number of refreshes in bitslice implementation of Fantomas """ import logging logging.basicConfig(level=logging.DEBUG) import networkx as nx import matplotlib.pyplot as plt import paths_dag import opt_sni import parse import graph_tools from utils import draw_graph # like formatted but removes NOT operations s = open('fantomas/f2.txt').read() g = parse.parse(s, tag_output_fn=lambda g, n: n.startswith('y')) draw_graph(g) plt.show() split_c_d = graph_tools.add_split_nodes(g) split_c = list(split_c_d.values()) print('baseline cut', sum(len(x)*(len(x)-1) for x in split_c)) draw_graph(g) plt.show() cut_edges = opt_sni.opt_sni(g, split_c, max_seconds=60) g2 = graph_tools.without_edges(g, cut_edges) print('Cut is NI', paths_dag.is_graph_NI(g2)) print('Cut is SNI', paths_dag.is_graph_SNI(g2)) draw_graph(g, cut_edges) plt.show() g3 = graph_tools.simplified(g2, preserve_IO=False) cut_edges2 = [x for x in cut_edges if x in g3.edges] draw_graph(g3, cut_edges2) plt.show() g4 = graph_tools.without_unncessary_splits(g, cut_edges, split_c_d) draw_graph(g4, [x for x in cut_edges if x in g4.edges]) plt.show() draw_graph(g, cut_edges)
[ "logging.basicConfig", "paths_dag.is_graph_SNI", "utils.draw_graph", "paths_dag.is_graph_NI", "opt_sni.opt_sni", "graph_tools.add_split_nodes", "graph_tools.simplified", "graph_tools.without_edges", "graph_tools.without_unncessary_splits", "matplotlib.pyplot.show" ]
[((684, 724), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (703, 724), False, 'import logging\n'), ((1021, 1034), 'utils.draw_graph', 'draw_graph', (['g'], {}), '(g)\n', (1031, 1034), False, 'from utils import draw_graph\n'), ((1035, 1045), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1043, 1045), True, 'import matplotlib.pyplot as plt\n'), ((1059, 1089), 'graph_tools.add_split_nodes', 'graph_tools.add_split_nodes', (['g'], {}), '(g)\n', (1086, 1089), False, 'import graph_tools\n'), ((1189, 1202), 'utils.draw_graph', 'draw_graph', (['g'], {}), '(g)\n', (1199, 1202), False, 'from utils import draw_graph\n'), ((1203, 1213), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1211, 1213), True, 'import matplotlib.pyplot as plt\n'), ((1227, 1270), 'opt_sni.opt_sni', 'opt_sni.opt_sni', (['g', 'split_c'], {'max_seconds': '(60)'}), '(g, split_c, max_seconds=60)\n', (1242, 1270), False, 'import opt_sni\n'), ((1276, 1315), 'graph_tools.without_edges', 'graph_tools.without_edges', (['g', 'cut_edges'], {}), '(g, cut_edges)\n', (1301, 1315), False, 'import graph_tools\n'), ((1412, 1436), 'utils.draw_graph', 'draw_graph', (['g', 'cut_edges'], {}), '(g, cut_edges)\n', (1422, 1436), False, 'from utils import draw_graph\n'), ((1437, 1447), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1445, 1447), True, 'import matplotlib.pyplot as plt\n'), ((1454, 1499), 'graph_tools.simplified', 'graph_tools.simplified', (['g2'], {'preserve_IO': '(False)'}), '(g2, preserve_IO=False)\n', (1476, 1499), False, 'import graph_tools\n'), ((1553, 1579), 'utils.draw_graph', 'draw_graph', (['g3', 'cut_edges2'], {}), '(g3, cut_edges2)\n', (1563, 1579), False, 'from utils import draw_graph\n'), ((1580, 1590), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1588, 1590), True, 'import matplotlib.pyplot as plt\n'), ((1597, 1659), 'graph_tools.without_unncessary_splits', 'graph_tools.without_unncessary_splits', (['g', 'cut_edges', 'split_c_d'], {}), '(g, cut_edges, split_c_d)\n', (1634, 1659), False, 'import graph_tools\n'), ((1660, 1715), 'utils.draw_graph', 'draw_graph', (['g4', '[x for x in cut_edges if x in g4.edges]'], {}), '(g4, [x for x in cut_edges if x in g4.edges])\n', (1670, 1715), False, 'from utils import draw_graph\n'), ((1716, 1726), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1724, 1726), True, 'import matplotlib.pyplot as plt\n'), ((1727, 1751), 'utils.draw_graph', 'draw_graph', (['g', 'cut_edges'], {}), '(g, cut_edges)\n', (1737, 1751), False, 'from utils import draw_graph\n'), ((1336, 1361), 'paths_dag.is_graph_NI', 'paths_dag.is_graph_NI', (['g2'], {}), '(g2)\n', (1357, 1361), False, 'import paths_dag\n'), ((1383, 1409), 'paths_dag.is_graph_SNI', 'paths_dag.is_graph_SNI', (['g2'], {}), '(g2)\n', (1405, 1409), False, 'import paths_dag\n')]
# Generated by Django 2.2.5 on 2019-09-16 17:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0005_board_photo'), ] operations = [ migrations.AlterField( model_name='board', name='photo', field=models.ImageField(blank=True, null=True, upload_to='images/'), ), ]
[ "django.db.models.ImageField" ]
[((323, 384), 'django.db.models.ImageField', 'models.ImageField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""images/"""'}), "(blank=True, null=True, upload_to='images/')\n", (340, 384), False, 'from django.db import migrations, models\n')]
#!/usr/bin/python #-*-coding:utf-8-*- #By <NAME> from numpy import * from lattice import Lattice from bzone import BZone from group import C6vGroup,C4vGroup,C3vGroup __all__=['Honeycomb_Lattice','Square_Lattice','Triangular_Lattice','Chain','construct_lattice','resize_lattice'] class Honeycomb_Lattice(Lattice): ''' HoneyComb Lattice class. Construct ---------------- Honeycomb_Lattice(N,form=1.) form: The form of lattice. `1` -> traditional one with 0 point at a vertex, using C3v group. `2` -> the C6v form with 0 point at the center of hexagon, using C6v group. ''' def __init__(self,N,form=1): if form==1: catoms=[(0.,0.),(0.5,sqrt(3.)/6)] pg=C3vGroup() elif form==2: catoms=array[(0.,1./sqrt(3.)),(0.5,sqrt(3.)/6)] pg=C6vGroup() else: raise ValueError('Form %s not defined.'%form) super(Honeycomb_Lattice,self).__init__(name='honeycomb',a=array([(1.,0),(0.5,sqrt(3.)/2)]),N=N,catoms=catoms) self.usegroup(pg) @property def kspace(self): ''' Get the <KSpace> instance. ''' ks=super(Honeycomb_Lattice,self).kspace M0=ks.b[1]/2.0 K0=(ks.b[0]+2*ks.b[1])/3.0 c6vg=C6vGroup() M=[] K=[] for i in xrange(6): M.append(c6vg.actonK(M0,i)) K.append(c6vg.actonK(K0,i)) ks.special_points['M']=M ks.special_points['K']=K ks.usegroup(c6vg) return ks class Square_Lattice(Lattice): ''' Square Lattice, using C4v Group. Construct ---------------- Square_Lattice(N,catoms=[(0.,0.)]) ''' def __init__(self,N,catoms=[(0.,0.)]): a=array([(1.,0),(0.,1.)]) super(Square_Lattice,self).__init__(N=N,a=a,catoms=catoms,name='square') c4vg=C4vGroup() self.usegroup(c4vg) @property def kspace(self): ''' Get the <KSpace> instance. ''' ks=super(Square_Lattice,self).kspace M0=ks.b[1]/2.0 K0=(ks.b[0]+ks.b[1])/2.0 c4vg=C4vGroup() M=[] K=[] for i in xrange(4): M.append(c4vg.actonK(M0,i)) K.append(c4vg.actonK(K0,i)) ks.special_points['M']=M ks.special_points['K']=K ks.usegroup(c4vg) return ks class Triangular_Lattice(Lattice): ''' Triangular Lattice, using C6v Group. Construct ---------------- Triangular_Lattice(N,catoms=[(0.,0.)]) ''' def __init__(self,N,catoms=[(0.,0.)]): '''Basic information of Triangular Lattice''' a=array([(1.,0),(0.5,sqrt(3.)/2)]) super(Triangular_Lattice,self).__init__(a=a,catoms=catoms,name='triangular',N=N) c6vg=C6vGroup() self.usegroup(c6vg) @property def kspace(self): ''' Get the <KSpace> instance. ''' ks=super(Triangular_Lattice,self).kspace M0=ks.b[1]/2.0 K0=(ks.b[0]+2*ks.b[1])/3.0 c6vg=C6vGroup() M=[] K=[] for i in xrange(6): M.append(c6vg.actonK(M0,i)) K.append(c6vg.actonK(K0,i)) ks.special_points['M']=M ks.special_points['K']=K ks.usegroup(c6vg) return ks class Chain(Lattice): ''' Lattice of Chain. Construct ---------------- Chain(N,a=(1.),catoms=[(0.,0.)]) ''' def __init__(self,N,a=(1.),catoms=[(0.)]): ''' N: Number of cells, integer. a: Lattice vector, 1D array. catoms: Atom positions in a unit cell. ''' super(Chain,self).__init__(a=[a],N=[N],name='chain',catoms=catoms) @property def kspace(self): '''The <KSpace> instance correspond to a chain.''' a=self.a[0] b=2*pi*a/a.dot(a) ks=KSpace(N=self.N,b=b) ks.special_points['K']=array([-b/2.,b/2.]) return ks def construct_lattice(N,lattice_shape='',a=None,catoms=None,args={}): ''' Uniform construct method for lattice. N: The size of lattice. lattice_shape: The shape of lattice. * '' -> the anonymous lattice. * 'square' -> square lattice. * 'honeycomb' -> honeycomb lattice. * 'triangular' -> triangular lattice. * 'chain' -> a chain. a: The unit vector. catoms: The atoms in a unit cell. args: Other arguments, * `form` -> the form used in constructing honeycomb lattice. ''' if lattice_shape=='': assert(a is not None) if catoms is None: catoms=zeros(shape(a)[-1]) return Lattice(name='anonymous',N=N,a=a,catoms=catoms) elif lattice_shape=='honeycomb': return Honeycomb_Lattice(N=N,form=args.get('form',1)) elif lattice_shape=='square': if catoms is None: catoms=zeros([1,2]) return Square_Lattice(N=N,catoms=catoms) elif lattice_shape=='triangular': if catoms is None: catoms=zeros([1,2]) return Triangular_Lattice(N=N,catoms=catoms) elif lattice_shape=='chain': if a is None: a=[1.] if catoms is None: catoms=zeros([1,1]) if ndim(N)==1: N=N[0] return Chain(N=N,catoms=catoms) def resize_lattice(lattice,N): ''' Resize the lattice to specific size. lattice: The target lattice. N: 1D - array, the size of new lattice. ''' return construct_lattice(a=lattice.a,N=N,catoms=lattice.catoms,args={'form':getattr(lattice,'form',None)})
[ "group.C6vGroup", "group.C4vGroup", "group.C3vGroup", "lattice.Lattice" ]
[((1338, 1348), 'group.C6vGroup', 'C6vGroup', ([], {}), '()\n', (1346, 1348), False, 'from group import C6vGroup, C4vGroup, C3vGroup\n'), ((1948, 1958), 'group.C4vGroup', 'C4vGroup', ([], {}), '()\n', (1956, 1958), False, 'from group import C6vGroup, C4vGroup, C3vGroup\n'), ((2208, 2218), 'group.C4vGroup', 'C4vGroup', ([], {}), '()\n', (2216, 2218), False, 'from group import C6vGroup, C4vGroup, C3vGroup\n'), ((2902, 2912), 'group.C6vGroup', 'C6vGroup', ([], {}), '()\n', (2910, 2912), False, 'from group import C6vGroup, C4vGroup, C3vGroup\n'), ((3168, 3178), 'group.C6vGroup', 'C6vGroup', ([], {}), '()\n', (3176, 3178), False, 'from group import C6vGroup, C4vGroup, C3vGroup\n'), ((4922, 4972), 'lattice.Lattice', 'Lattice', ([], {'name': '"""anonymous"""', 'N': 'N', 'a': 'a', 'catoms': 'catoms'}), "(name='anonymous', N=N, a=a, catoms=catoms)\n", (4929, 4972), False, 'from lattice import Lattice\n'), ((769, 779), 'group.C3vGroup', 'C3vGroup', ([], {}), '()\n', (777, 779), False, 'from group import C6vGroup, C4vGroup, C3vGroup\n'), ((880, 890), 'group.C6vGroup', 'C6vGroup', ([], {}), '()\n', (888, 890), False, 'from group import C6vGroup, C4vGroup, C3vGroup\n')]
import os # os.environ['CUDA_VISIBLE_DEVICES'] = '7' import torch from PIL import Image from torchvision import transforms from train_crnn.config import opt from train_crnn.crnn import crnn class resizeNormalize(object): def __init__(self, size, interpolation=Image.BILINEAR): self.size = size self.interpolation = interpolation self.toTensor = transforms.ToTensor() def __call__(self, img): img = img.resize(self.size, self.interpolation) img = self.toTensor(img) img.sub_(0.5).div_(0.5) return img def decode(preds,char_set): pred_text = '' for i in range(len(preds)): if preds[i] != 0 and ((i == 0) or (i != 0 and preds[i] != preds[i-1])): pred_text += char_set[int(preds[i])-1] return pred_text # test if crnn work if __name__ == '__main__': imagepath = './test.jpg' img_h = opt.img_h use_gpu = opt.use_gpu modelpath = opt.modelpath char_set = open('char_std_5990.txt', 'r', encoding='utf-8').readlines() char_set = ''.join([ch.strip('\n') for ch in char_set[1:]] + ['卍']) n_class = len(char_set) model = crnn.CRNN(img_h, 1, n_class, 256) if torch.cuda.is_available and use_gpu: model.cuda() if os.path.exists(modelpath): print('Load model from "%s" ...' % modelpath) model.load_state_dict(torch.load(modelpath)) print('Done!') image = Image.open(imagepath).convert('L') (w,h) = image.size size_h = 32 ratio = size_h / float(h) size_w = int(w * ratio) # keep the ratio transform = resizeNormalize((size_w, size_h)) image = transform(image) image = image.unsqueeze(0) if torch.cuda.is_available and use_gpu: image = image.cuda() model.eval() preds = model(image) preds = preds.max(2)[1] preds = preds.squeeze() pred_text = decode(preds,char_set) print('predict == >',pred_text)
[ "train_crnn.crnn.crnn.CRNN", "os.path.exists", "PIL.Image.open", "torch.load", "torchvision.transforms.ToTensor" ]
[((1052, 1085), 'train_crnn.crnn.crnn.CRNN', 'crnn.CRNN', (['img_h', '(1)', 'n_class', '(256)'], {}), '(img_h, 1, n_class, 256)\n', (1061, 1085), False, 'from train_crnn.crnn import crnn\n'), ((1147, 1172), 'os.path.exists', 'os.path.exists', (['modelpath'], {}), '(modelpath)\n', (1161, 1172), False, 'import os\n'), ((354, 375), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (373, 375), False, 'from torchvision import transforms\n'), ((1246, 1267), 'torch.load', 'torch.load', (['modelpath'], {}), '(modelpath)\n', (1256, 1267), False, 'import torch\n'), ((1296, 1317), 'PIL.Image.open', 'Image.open', (['imagepath'], {}), '(imagepath)\n', (1306, 1317), False, 'from PIL import Image\n')]
import logging class GpioException(Exception): def __init__(self,errors): self.errors = errors def toString(self): return ' '.join(self.errors) # str(self.errors).replace('\'','').replace('[','').replace(']','') class GpioDummy(object): def __init__(self): self.args = {'mode':'BCM'} self.bcm = {1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0 ,11:0,12:0,13:0,14:0,15:0,16:0,17:0,18:0,19:0,20:0 ,21:0,22:0,23:0,24:0,25:0,26:0,27:0} # inital bcm gpio setting self.board = {} # inital board gpio setting for key in range(0,40): self.board[key] = 0 self.setting = {} # runtime gpio setting self.mode = None def setmode(self,mode): if 'GPIO.BCM' == mode: self.setting = self.bcm self.mode = mode elif 'GPIO.BOARD' == mode: self.setting = self.board self.mode = mode else: self.setting = {} self.mode = None def getmode(self): return self.mode def setwarnings(self,val): logging.info('dummy gpio set warnings %s'%val) pass def setup(self,key,val,initial=0): self.setting[key] = val def output(self,key,val): self.setting[key] = val logging.info('dummy gpio set %s to %s.'%(key,val)) def input(self,key): return self.setting[key] def cleanup(self): self.setmode(self.mode) logging.info('dummy gpio cleaned up') pass # --------------------------------------------------------------- # Rapsberry Pi 3/Zero BCM # --------------------------------------------------------------- # +3V3 [ ] [ ] +5V # SDA1 / GPIO 2 [ ] [ ] +5V # SCL1 / GPIO 3 [ ] [ ] GND # GPIO 4 [ ] [ ] GPIO 14 / TXD0 # GND [ ] [ ] GPIO 15 / RXD0 # GPIO 17 [ ] [ ] GPIO 18 # GPIO 27 [ ] [ ] GND # GPIO 22 [ ] [ ] GPIO 23 # +3V3 [ ] [ ] GPIO 24 # MOSI / GPIO 10 [ ] [ ] GND # MISO / GPIO 9 [ ] [ ] GPIO 25 # SCLK / GPIO 11 [ ] [ ] GPIO 8 / CE0# # GND [ ] [ ] GPIO 7 / CE1# # ID_SD / GPIO 0 [ ] [ ] GPIO 1 / ID_SC # GPIO 5 [ ] [ ] GND # GPIO 6 [ ] [ ] GPIO 12 # GPIO 13 [ ] [ ] GND # MISO / GPIO 19 [ ] [ ] GPIO 16 / CE2# # GPIO 26 [ ] [ ] GPIO 20 / MOSI # GND [ ] [ ] GPIO 21 / SCLK # --------------------------------------------------------------- # Rapsberry Pi 3/Zero BOARD # --------------------------------------------------------------- # +3V3 1 [ ] [ ] 2 +5V # SDA1 / GPIO 3 [ ] [ ] 4 +5V # SCL1 / GPIO 5 [ ] [ ] 6 GND # GPIO 7 [ ] [ ] 8 GPIO 14 / TXD0 # GND 9 [ ] [ ] 10 GPIO 15 / RXD0 # GPIO 11 [ ] [ ] 12 GPIO 18 # GPIO 13 [ ] [ ] 14 GND # GPIO 15 [ ] [ ] 16 GPIO 23 # +3V3 17 [ ] [ ] 18 GPIO 24 # MOSI / GPIO 19 [ ] [ ] 20 GND # MISO / GPIO 21 [ ] [ ] 22 GPIO 25 # SCLK / GPIO 23 [ ] [ ] 24 GPIO 8 / CE0# # GND 25 [ ] [ ] 26 GPIO 7 / CE1# # ID_SD / GPIO 27 [ ] [ ] 28 GPIO 1 / ID_SC # GPIO 29 [ ] [ ] 30 GND # GPIO 31 [ ] [ ] 32 GPIO 12 # GPIO 33 [ ] [ ] 34 GND # MISO / GPIO 35 [ ] [ ] 36 GPIO 16 / CE2# # GPIO 37 [ ] [ ] 38 GPIO 20 / MOSI # GND 39 [ ] [ ] 40 GPIO 21 / SCLK # --------------------------------------------------------------- class Gpios(object): def __init__(self): self.args = {'emitter':None,'warn':False} # mode:GPIO.BOARD|GPIO.BCM self.events = {'create-gpio':self.create,'kill-gpio':self.kill} self.emitter = None def decorate(self,arguments): from Process import decorate return decorate(self,arguments) def create(self,data={}): self.emitter = self.args.get('emitter') try: import RPi.GPIO as GPIO self.gpio = GPIO self.gpio.setmode(GPIO.BCM) except ImportError as e: logging.error('pi gpio import failed %s'%(str(e))) self.gpio = GpioDummy() self.gpio.setmode('GPIO.BCM') logging.warning('pi gpio dummy initialized in %s mode'%self.gpio.getmode()) self.gpio.setwarnings(self.args.get('warn')) logging.debug('pi gpio initialized as %s'%self.gpio.getmode()) self.emitter.emit('gpio-created',{'id':'create-gpio','call':'gpio-created','gpio':self.gpio}) return self def register(self,data): # self.gpio.setup(7,GPIO.OUT) # out:0|in:1 initial=0 # response self.gpio # GPIO.output(7, 1) #Set TRIG as HIGH # GPIO.output(7, 0) #Set TRIG as LOW # GPIO.input(7)==0: #Check whether the 7 is LOW # GPIO.input(7)==1: #Check whether the 7 is HIGH return self def kill(self,data={}): self.gpio.cleanup() logging.debug('gpios cleaned.') self.emitter.emit('gpio-killed',{'id':'kill-gpio','call':'gpio-killed'}) return self
[ "logging.info", "logging.debug", "Process.decorate" ]
[((1116, 1164), 'logging.info', 'logging.info', (["('dummy gpio set warnings %s' % val)"], {}), "('dummy gpio set warnings %s' % val)\n", (1128, 1164), False, 'import logging\n'), ((1319, 1372), 'logging.info', 'logging.info', (["('dummy gpio set %s to %s.' % (key, val))"], {}), "('dummy gpio set %s to %s.' % (key, val))\n", (1331, 1372), False, 'import logging\n'), ((1493, 1530), 'logging.info', 'logging.info', (['"""dummy gpio cleaned up"""'], {}), "('dummy gpio cleaned up')\n", (1505, 1530), False, 'import logging\n'), ((3876, 3901), 'Process.decorate', 'decorate', (['self', 'arguments'], {}), '(self, arguments)\n', (3884, 3901), False, 'from Process import decorate\n'), ((5015, 5046), 'logging.debug', 'logging.debug', (['"""gpios cleaned."""'], {}), "('gpios cleaned.')\n", (5028, 5046), False, 'import logging\n')]
#!/usr/bin/env python # coding: utf-8 import copy testInstructionString = '''nop +0 acc +1 jmp +4 acc +3 jmp -3 acc -99 acc +1 jmp -4 acc +6''' def parseInstructions(instructionsString): instructions = [] for i in instructionsString.split("\n"): thisInstruction = {} thisInstruction["command"] = i.split(" ")[0] thisInstruction["value"] = int(i.split(" ")[1]) thisInstruction["executionTimes"] = 0 instructions.append(thisInstruction) return instructions def runProgramUntilLoop(instructions, loopCount): pointer = 0 accumulator = 0 finished = False while not finished: instructions[pointer]["executionTimes"] += 1 if instructions[pointer]["executionTimes"] > loopCount: finished = True else: if instructions[pointer]["command"] == "nop": pointer += 1 elif instructions[pointer]["command"] == "acc": accumulator += instructions[pointer]["value"] pointer += 1 elif instructions[pointer]["command"] == "jmp": pointer += instructions[pointer]["value"] return accumulator def runProgramUntilEnd(instructions, maxExecutions): pointer = 0 accumulator = 0 finished = False while not finished: if pointer >= len(instructions): finished = True return accumulator instructions[pointer]["executionTimes"] += 1 if instructions[pointer]["executionTimes"] > maxExecutions: # This is stuck in an infinite loop. Stop! finished = True return False else: if instructions[pointer]["command"] == "nop": pointer += 1 elif instructions[pointer]["command"] == "acc": accumulator += instructions[pointer]["value"] pointer += 1 elif instructions[pointer]["command"] == "jmp": pointer += instructions[pointer]["value"] return accumulator def resetLoopCount(instructions): for i in instructions: i["executionTimes"] = 0 def findCorruptInstructionIndex(instructions, loopCount): foundIndex = False swapIndex = 0 while not foundIndex: #print("Testing Index: %d" % (swapIndex)) testInstructions = copy.deepcopy(instructions) # We want to swap this instruction to see if it fixes things if testInstructions[swapIndex]["command"] == "jmp": #print("Swapping a JMP for a NOP...") testInstructions[swapIndex]["command"] = "nop" elif testInstructions[swapIndex]["command"] == "nop": #print("Swapping a NOP for a JMP...") testInstructions[swapIndex]["command"] = "jmp" else: #print("Found a command that wasn't jmp or nop: %s" % (testInstructions[swapIndex]["command"])) swapIndex += 1 foundResult = runProgramUntilEnd(testInstructions, 5) if not foundResult: #print("Stuck in a loop still...trying the next one") swapIndex += 1 else: #print("Found a program that fixes the issue") foundIndex = True return swapIndex, foundResult if swapIndex >= len(testInstructions): #print("Reached the end of the instructions with no known fix") foundIndex = True return swapIndex, foundResult def openFile(filename): with open (filename, "r") as dataFile: data = parseInstructions(dataFile.read()) return data # Part 1 Test testInstructions = parseInstructions(testInstructionString) index = runProgramUntilLoop(testInstructions, 1) print("The first time the program loops is here: %d" % (index)) # Part 1 Real Run instructions = openFile("day08.txt") result = runProgramUntilLoop(instructions, 1) print("The Accumulator's value is: %d" % (result)) # Part 2 Test resetLoopCount(testInstructions) index = findCorruptInstructionIndex(testInstructions,1) indexToSwap, accumulator = findCorruptInstructionIndex(testInstructions, 5) print("If you swap index %d, then the program finishes with an accumulator value of %d" % (indexToSwap, accumulator)) # Part 2 Real resetLoopCount(instructions) index = findCorruptInstructionIndex(instructions,1) indexToSwap, accumulator = findCorruptInstructionIndex(instructions, 5) print("If you swap index %d, then the program finishes with an accumulator value of %d" % (indexToSwap, accumulator))
[ "copy.deepcopy" ]
[((2337, 2364), 'copy.deepcopy', 'copy.deepcopy', (['instructions'], {}), '(instructions)\n', (2350, 2364), False, 'import copy\n')]
from __future__ import with_statement # this is to work with python2.5 import terapyps from pyps import workspace workspace.delete("convol3x3") with terapyps.workspace("convol3x3.c", name="convol3x3", deleteOnClose=False,recoverInclude=False) as w: for f in w.fun: f.terapix_code_generation(debug=True) # w.compile(terapyps.Maker())
[ "terapyps.workspace", "pyps.workspace.delete" ]
[((114, 143), 'pyps.workspace.delete', 'workspace.delete', (['"""convol3x3"""'], {}), "('convol3x3')\n", (130, 143), False, 'from pyps import workspace\n'), ((149, 247), 'terapyps.workspace', 'terapyps.workspace', (['"""convol3x3.c"""'], {'name': '"""convol3x3"""', 'deleteOnClose': '(False)', 'recoverInclude': '(False)'}), "('convol3x3.c', name='convol3x3', deleteOnClose=False,\n recoverInclude=False)\n", (167, 247), False, 'import terapyps\n')]
from pymapper.layer import LayerType, GeoPandasLayer def test_layer_types(): """Test the LayerType enum.""" assert list(LayerType.__members__.keys()) == [GeoPandasLayer.LAYER_TYPE] assert LayerType[GeoPandasLayer.LAYER_TYPE].value == GeoPandasLayer
[ "pymapper.layer.LayerType.__members__.keys" ]
[((130, 158), 'pymapper.layer.LayerType.__members__.keys', 'LayerType.__members__.keys', ([], {}), '()\n', (156, 158), False, 'from pymapper.layer import LayerType, GeoPandasLayer\n')]
# # Copyright (c) 2018-2019 Intel Corporation # # 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. # import falcon import numpy as np from grpc import StatusCode from tensorflow.core.framework import tensor_pb2 from tensorflow.python.framework import tensor_shape from tensorflow_serving.apis import predict_pb2 from tensorflow.python.framework import dtypes as dtypes from tensorflow.python.framework import tensor_util as tensor_util import tensorflow.contrib.util as tf_contrib_util # import tensorflow.contrib.util as tf_contrib_util from ie_serving.models.shape_management.utils import BatchingMode, ShapeMode from ie_serving.server.constants import \ INVALID_INPUT_KEY, INVALID_SHAPE, INVALID_BATCHSIZE, GRPC, REST from ie_serving.logger import get_logger logger = get_logger(__name__) statusCodes = { 'invalid_arg': {GRPC: StatusCode.INVALID_ARGUMENT, REST: falcon.HTTP_BAD_REQUEST}, } def prepare_input_data(target_engine, data, service_type): # returns: # inference_input, None on success # None, error_message on error model_inputs_in_input_request = list(dict(data).keys()) input_keys = target_engine.input_key_names inference_input = {} for requested_input_blob in model_inputs_in_input_request: if requested_input_blob not in input_keys: message = INVALID_INPUT_KEY % (model_inputs_in_input_request, input_keys) logger.debug("PREDICT error: {}".format(message)) return None, message tensor_name = target_engine.model_keys['inputs'][requested_input_blob] if service_type == GRPC: try: tensor_input = tf_contrib_util. \ make_ndarray(data[requested_input_blob]) except Exception as e: message = str(e) logger.debug("PREDICT prepare_input_data make_ndarray error: " "{}".format(message)) return None, message else: tensor_input = np.asarray(data[requested_input_blob]) # Validate shape if shape not in auto mode if target_engine.shape_info.mode != ShapeMode.AUTO: shape_required_in_model = target_engine.net.inputs[ tensor_name].shape # For reshapable models check all dimensions, # for non-reshapable, check all starting from the second (omit # batch size) if target_engine.shape_info.mode == ShapeMode.DISABLED: starting_dim = 1 else: starting_dim = 0 # check requested shape and model shape if shape_required_in_model[starting_dim:] != list( tensor_input.shape)[starting_dim:]: message = INVALID_SHAPE.format(list(tensor_input.shape), shape_required_in_model) logger.debug("PREDICT error: {}".format(message)) return None, message # check if input batch size match the model only if not auto mode if target_engine.batching_info.mode != \ BatchingMode.AUTO and shape_required_in_model[0] != \ tensor_input.shape[0]: message = INVALID_BATCHSIZE.format( tensor_input.shape[0], target_engine.batching_info.batch_size) logger.debug("PREDICT error,Invalid batchsize:{}".format( message)) return None, message inference_input[tensor_name] = tensor_input return inference_input, None def prepare_output_as_list(inference_output, model_available_outputs): response = predict_pb2.PredictResponse() for key, value in model_available_outputs.items(): if value in inference_output: dtype = dtypes.as_dtype(inference_output[value].dtype) output_tensor = tensor_pb2.TensorProto( dtype=dtype.as_datatype_enum, tensor_shape=tensor_shape.as_shape( inference_output[value].shape).as_proto()) result = inference_output[value].flatten() tensor_util._NP_TO_APPEND_FN[dtype.as_numpy_dtype](output_tensor, result) response.outputs[key].CopyFrom(output_tensor) return response ''' The function is not used. Probably preparing the output would be faster, but you need a change of grpc clients. def prepare_output_with_tf(inference_output, model_available_outputs): response = predict_pb2.PredictResponse() for output in model_available_outputs: response.outputs[output].CopyFrom( tf_contrib_util.make_tensor_proto(inference_output[output], shape=inference_output[output]. shape, dtype=dtypes.as_dtype( inference_output [output].dtype). as_datatype_enum)) return response '''
[ "tensorflow_serving.apis.predict_pb2.PredictResponse", "tensorflow.python.framework.dtypes.as_dtype", "numpy.asarray", "tensorflow.python.framework.tensor_shape.as_shape", "ie_serving.logger.get_logger", "tensorflow.contrib.util.make_ndarray", "ie_serving.server.constants.INVALID_BATCHSIZE.format" ]
[((1302, 1322), 'ie_serving.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (1312, 1322), False, 'from ie_serving.logger import get_logger\n'), ((4355, 4384), 'tensorflow_serving.apis.predict_pb2.PredictResponse', 'predict_pb2.PredictResponse', ([], {}), '()\n', (4382, 4384), False, 'from tensorflow_serving.apis import predict_pb2\n'), ((2621, 2659), 'numpy.asarray', 'np.asarray', (['data[requested_input_blob]'], {}), '(data[requested_input_blob])\n', (2631, 2659), True, 'import numpy as np\n'), ((4501, 4547), 'tensorflow.python.framework.dtypes.as_dtype', 'dtypes.as_dtype', (['inference_output[value].dtype'], {}), '(inference_output[value].dtype)\n', (4516, 4547), True, 'from tensorflow.python.framework import dtypes as dtypes\n'), ((2257, 2313), 'tensorflow.contrib.util.make_ndarray', 'tf_contrib_util.make_ndarray', (['data[requested_input_blob]'], {}), '(data[requested_input_blob])\n', (2285, 2313), True, 'import tensorflow.contrib.util as tf_contrib_util\n'), ((3899, 3991), 'ie_serving.server.constants.INVALID_BATCHSIZE.format', 'INVALID_BATCHSIZE.format', (['tensor_input.shape[0]', 'target_engine.batching_info.batch_size'], {}), '(tensor_input.shape[0], target_engine.batching_info\n .batch_size)\n', (3923, 3991), False, 'from ie_serving.server.constants import INVALID_INPUT_KEY, INVALID_SHAPE, INVALID_BATCHSIZE, GRPC, REST\n'), ((4678, 4730), 'tensorflow.python.framework.tensor_shape.as_shape', 'tensor_shape.as_shape', (['inference_output[value].shape'], {}), '(inference_output[value].shape)\n', (4699, 4730), False, 'from tensorflow.python.framework import tensor_shape\n')]
import numpy as np import matplotlib.pyplot as plt # plt.style.use('ggplot') ''' Shot Accuracy Plot ticks = [5,6,7,8,9,10,11,12,13,14,15]#[1,2,3,4,5] data_lists = [ [92.35,92.52,93.2,93.71,93.85,94.15,94.22,94.37,94.68,94.73,94.82], [89.15,89.74,90.41,90.88,91.31,91.47,91.84,92.03,92.2,92.3,92.48], [86.13,86.98,87.8,88.15,88.71,89.22,89.43,89.6,89.87,90.05,90.16], [80.04,81.38,82.39,83.09,83.61,84.21,84.6,85.16,85.35,85.79,85.99] ]#[[0.4,1.2,2.3,4,5.5]] label_lists = [ 'VirusShare_00177 5-way', 'VirusShare_00177 10-way', 'APIMDS 5-way', 'APIMDS 10-way' ]#['test1'] color_lists = ['red', 'red', 'royalblue', 'royalblue'] #['red'] marker_lists = ['o', '^', 'o', "^"]#['.'] ''' acc_data_lists = [ [91.04,91.71,92.11,92.35,91.8,91.55,90.71,91.05,90.22,90.12, 91.13, 90.32, 90.48, 90.84, 90.42, 91.14, 90.49, 90.49, 90.87, 90.77], [87.44, 88.64, 88.7, 89.15, 88.07, 87.88, 87.77, 87.64, 87.46, 87.02, 86.93, 87.05, 86.87, 87.43, 87.56, 87.72, 87.38, 86.98, 87.31, 87.28] ] time_data_lists = [ [14.2, 19.6, 25.1, 29.4, 36.9, 42.4, 48.8, 53.6, 58.6, 64.5, 70.1, 75.1, 80.5, 83.2, 90.5, 93.4, 100.6, 106.1, 111.5, 115.6], [22.4, 32.0, 41.1, 50.2, 61.5, 71.4, 79.9, 89.8, 98.8, 108.5, 116.3, 122.4, 131.8, 142.6, 154.5, 164.3, 170.7, 187.9, 195.2, 201.9] ] acc_label_lists = [ "VirusShare_00177 5-shot 5-way accuracy", "VirusShare_00177 5-shot 10-way accuracy", # "APIMDS 5-shot 5-way", # "APIMDS 5-shot 10-way" ] time_label_list = [ "VirusShare_00177 5-shot 5-way test time per episode", "VirusShare_00177 5-shot 10-way test time per episode" ] color_lists = ['orange', 'green'] marker_lists = ['s', 's'] bar_width = 10 ticks = np.arange(50, 1050, 50) num_list = len(time_data_lists) bar_ticks = [ np.arange(50, 1050, 50) - (num_list/2 - i - 0.5) * bar_width for i in range(num_list) ] marker_size = 6 title = '' x_title = 'Sequence Length' acc_y_title = 'Accuracy(%)' time_y_title = 'ms / Episode' fig_size = (15,6) dpi = 300 fig = plt.figure(figsize=fig_size, dpi=dpi) plt.xticks(ticks) plt.title(title) # plt.xlabel(x_title) # plt.ylabel(y_title) plt.grid(True, axis='y') acc_axis = fig.add_subplot(111) time_axis = acc_axis.twinx() acc_axis.set_xlabel('Maximum Sequence Length') acc_axis.set_ylabel(acc_y_title) time_axis.set_ylabel(time_y_title) acc_axis.set_ylim(75, 95) time_axis.set_ylim(0, 350) for acc_data, time_data, bar_tick, acc_label, time_label, color, marker in zip(acc_data_lists, time_data_lists, bar_ticks, acc_label_lists, time_label_list, color_lists, marker_lists): acc_axis.plot(ticks, acc_data, color=color, marker=marker, label=acc_label, markersize=marker_size) time_axis.bar(bar_tick, time_data, color=color, width=10, label=time_label, zorder=2) acc_axis.legend(loc='upper left') time_axis.legend(loc='upper right') # plt.legend() plt.show() # plt.savefig('C:/Users/Asichurter/Desktop/截图/virushare.jpg', format='JPEG', dpi=300)
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.xticks", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.show" ]
[((1704, 1727), 'numpy.arange', 'np.arange', (['(50)', '(1050)', '(50)'], {}), '(50, 1050, 50)\n', (1713, 1727), True, 'import numpy as np\n'), ((2020, 2057), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'fig_size', 'dpi': 'dpi'}), '(figsize=fig_size, dpi=dpi)\n', (2030, 2057), True, 'import matplotlib.pyplot as plt\n'), ((2058, 2075), 'matplotlib.pyplot.xticks', 'plt.xticks', (['ticks'], {}), '(ticks)\n', (2068, 2075), True, 'import matplotlib.pyplot as plt\n'), ((2076, 2092), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2085, 2092), True, 'import matplotlib.pyplot as plt\n'), ((2137, 2161), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'axis': '"""y"""'}), "(True, axis='y')\n", (2145, 2161), True, 'import matplotlib.pyplot as plt\n'), ((2860, 2870), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2868, 2870), True, 'import matplotlib.pyplot as plt\n'), ((1778, 1801), 'numpy.arange', 'np.arange', (['(50)', '(1050)', '(50)'], {}), '(50, 1050, 50)\n', (1787, 1801), True, 'import numpy as np\n')]
# --------------------------------------------------------------------------------------------- # MIT License # Copyright (c) 2020, Solace Corporation, <NAME> (<EMAIL>) # Copyright (c) 2020, Solace Corporation, <NAME> (<EMAIL>) # --------------------------------------------------------------------------------------------- import glob import os.path from os import path from .common_base import CommonBase from .constants import * from .perf_error import PerfError from .run import Run from .run_result_location import RunResultLocation class RunDefinition(CommonBase): def __init__(self, location: RunResultLocation): """ RunDefinition triggers processing all runs within RunResultLocation and provides functions to extract data ++ :param location: """ CommonBase.__init__(self) self._location = location self._list_runs = list() self._process_distinct_latency_samples=True #just metadata read self._processed_samples = False def process_run_samples(self, process_distinct_latency_samples:bool=True): rootExists = self._check_root_folder_in_run_location() self._process_distinct_latency_samples = process_distinct_latency_samples if not rootExists: raise SystemExit(f'[ERROR] [EXITING] Root folder does not exist:{self._location.root_folder}') for run_dir in self._read_list_runs(): self._list_runs.append(Run(self,run_dir)) self._processed_samples = True def _file_path_in_run_location(self, filename: str) -> str: return self._location.root_folder + "/" + filename def _check_file_in_run_location(self, filename: str) -> bool: return path.exists(self._file_path_in_run_location(filename)) def _check_root_folder_in_run_location(self) -> bool: return path.exists(self._location.root_folder) def _files_in_run_location(self, pattern): return glob.glob(self._file_path_in_run_location(perf_pattern_run_dir)) def _dirs_in_run_location(self, pattern): candidates = glob.glob(self._file_path_in_run_location(perf_pattern_run_dir)) return list(filter(lambda file: os.path.isdir(file), candidates)) def _check_processed_sampled(self): if not self._processed_samples: raise SystemExit(f'[ERROR] [EXITING] RunDefinition not initialized. Execute >process_run_samples() once to read all sample data.<') def _read_list_runs(self) -> list: return self._dirs_in_run_location(perf_pattern_run_dir) def all_runs(self) -> list: """ All runs :return: list of all runs """ self._check_processed_sampled() return self._list_runs def find_run(self, run_id, read_samples:bool=True): """ Searches for run with run_id :param run_id: :param read_samples: read also the latencies before handing over the run :return: Run :raise: PerfError: if run_id was not found """ self._check_processed_sampled() try: run = next(filter(lambda item: item.run_meta.run_id==run_id, self._list_runs)) if read_samples: #idempotent - samples will be read just once run.read_samples() return run except StopIteration: raise PerfError(f'run_id: {run_id} not found') def find_sample(self,run_id, metrics_type, sample_num): """ Searches for specific sample :param run_id: :param metrics_type: {c_sample_metric_type_latency_node | c_sample_metric_type_latency_broker | c_sample_metric_type_ping | c_sample_metric_vpn} :param sample_num: :return: sample :raises PerfError """ self._check_processed_sampled() run = self.find_run(run_id) #idempotent - samples will be read just once run.read_samples() if (metrics_type==c_sample_metric_type_latency_node): return run.latency_node_latency_series.find_sample(sample_num) if (metrics_type==c_sample_metric_type_latency_broker): return run.broker_node_latency_series.find_sample(sample_num) if (metrics_type==c_sample_metric_type_ping): return run.ping_series.find_sample(sample_num) if (metrics_type==c_sample_metric_vpn): return run.broker_series.find_sample(sample_num) raise PerfError(f'Unsupported metric_type: {metrics_type}')
[ "os.path.exists" ]
[((1860, 1899), 'os.path.exists', 'path.exists', (['self._location.root_folder'], {}), '(self._location.root_folder)\n', (1871, 1899), False, 'from os import path\n')]
from Treap import Treap from math import log class IKS: def __init__(self): self.treap = None self.n = [0, 0] @staticmethod def KSThresholdForPValue(pvalue, N): '''Threshold for KS Test given a p-value Args: pval (float): p-value. N (int): the size of the samples. Returns: Threshold t to compare groups 0 and 1. The null-hypothesis is discarded if KS() > t. ''' ca = (-0.5 * log(pvalue)) ** 0.5 return ca * (2.0 * N / N ** 2) @staticmethod def CAForPValue(pvalue): '''ca for KS Test given a p-value Args: pval (float): p-value. Returns: Threshold the "ca" that can be used to compute a threshold for KS(). ''' return (-0.5 * log(pvalue)) ** 0.5 def KS(self): '''Kolmogorov-Smirnov statistic. Both groups must have the same number of observations. Returns: The KS statistic D. ''' assert(self.n[0] == self.n[1]) N = self.n[0] if N == 0: return 0 return max(self.treap.max_value, -self.treap.min_value) / N def Kuiper(self): '''Kuiper statistic. Both groups must have the same number of observations. Returns: The Kuiper statistic. ''' assert(self.n[0] == self.n[1]) N = self.n[0] if N == 0: return 0 return (self.treap.max_value - self.treap.min_value) / N def Add(self, obs, group): '''Insert new observation into one of the groups. Args: obs: the value of the obseration. Tip: a tuple (actual value, random value) is recommended when there is overlap between groups or if values are not guaranteed to be mostly unique. group (int): which group the observation belongs to. Must be either 0 or 1. ''' group = 0 if group == 2 else group assert(group == 0 or group == 1) key = (obs, group) self.n[group] += 1 left, left_g, right, val = None, None, None, None left, right = Treap.SplitKeepRight(self.treap, key) left, left_g = Treap.SplitGreatest(left) val = 0 if left_g is None else left_g.value left = Treap.Merge(left, left_g) right = Treap.Merge(Treap(key, val), right) Treap.SumAll(right, 1 if group == 0 else -1) self.treap = Treap.Merge(left, right) def Remove(self, obs, group): '''Remove observation from one of the groups. Args: obs: the value of the obseration. Must be identical to a previously inserted observation (including the random element of a tuple, if this was the case). group (int): which group the observation belongs to. Must be either 0 or 1. ''' group = 0 if group == 2 else group assert(group == 0 or group == 1) key = (obs, group) self.n[group] -= 1 left, right, right_l = None, None, None left, right = Treap.SplitKeepRight(self.treap, key) right_l, right = Treap.SplitSmallest(right) if right_l is not None and right_l.key == key: Treap.SumAll(right, -1 if group == 0 else 1) else: right = Treap.Merge(right_l, right) self.treap = Treap.Merge(left, right) def Test(self, ca = 1.95): '''Test whether the reference and sliding window follow the different probability distributions according to KS Test. Args: ca: ca is a parameter used to calculate the threshold for the Kolmogorov-Smirnov statistic. The default value corresponds to a p-value of 0.001. Use IKS.CAForPValue to obtain an appropriate ca. Returns: True if we **reject** the null-hypothesis that states that both windows have the same distribution. In other words, we can consider that the windows have now different distributions. ''' ca = ca or 1.95 n = self.n[0] return self.KS() > ca * (2 * n / n ** 2) ** 0.5 IKS.AddObservation = IKS.Add IKS.RemoveObservation = IKS.Remove
[ "Treap.Treap.Merge", "Treap.Treap.SplitGreatest", "math.log", "Treap.Treap.SplitSmallest", "Treap.Treap.SumAll", "Treap.Treap", "Treap.Treap.SplitKeepRight" ]
[((1986, 2023), 'Treap.Treap.SplitKeepRight', 'Treap.SplitKeepRight', (['self.treap', 'key'], {}), '(self.treap, key)\n', (2006, 2023), False, 'from Treap import Treap\n'), ((2046, 2071), 'Treap.Treap.SplitGreatest', 'Treap.SplitGreatest', (['left'], {}), '(left)\n', (2065, 2071), False, 'from Treap import Treap\n'), ((2133, 2158), 'Treap.Treap.Merge', 'Treap.Merge', (['left', 'left_g'], {}), '(left, left_g)\n', (2144, 2158), False, 'from Treap import Treap\n'), ((2217, 2261), 'Treap.Treap.SumAll', 'Treap.SumAll', (['right', '(1 if group == 0 else -1)'], {}), '(right, 1 if group == 0 else -1)\n', (2229, 2261), False, 'from Treap import Treap\n'), ((2282, 2306), 'Treap.Treap.Merge', 'Treap.Merge', (['left', 'right'], {}), '(left, right)\n', (2293, 2306), False, 'from Treap import Treap\n'), ((2855, 2892), 'Treap.Treap.SplitKeepRight', 'Treap.SplitKeepRight', (['self.treap', 'key'], {}), '(self.treap, key)\n', (2875, 2892), False, 'from Treap import Treap\n'), ((2915, 2941), 'Treap.Treap.SplitSmallest', 'Treap.SplitSmallest', (['right'], {}), '(right)\n', (2934, 2941), False, 'from Treap import Treap\n'), ((3126, 3150), 'Treap.Treap.Merge', 'Treap.Merge', (['left', 'right'], {}), '(left, right)\n', (3137, 3150), False, 'from Treap import Treap\n'), ((2186, 2201), 'Treap.Treap', 'Treap', (['key', 'val'], {}), '(key, val)\n', (2191, 2201), False, 'from Treap import Treap\n'), ((3003, 3047), 'Treap.Treap.SumAll', 'Treap.SumAll', (['right', '(-1 if group == 0 else 1)'], {}), '(right, -1 if group == 0 else 1)\n', (3015, 3047), False, 'from Treap import Treap\n'), ((3074, 3101), 'Treap.Treap.Merge', 'Treap.Merge', (['right_l', 'right'], {}), '(right_l, right)\n', (3085, 3101), False, 'from Treap import Treap\n'), ((449, 460), 'math.log', 'log', (['pvalue'], {}), '(pvalue)\n', (452, 460), False, 'from math import log\n'), ((753, 764), 'math.log', 'log', (['pvalue'], {}), '(pvalue)\n', (756, 764), False, 'from math import log\n')]
# third-party from pycallgraph import PyCallGraph from pycallgraph import GlobbingFilter from pycallgraph import Config from pycallgraph.output import GraphvizOutput # this package from ape.interface.ubootkommandant import UbootKommandant subcommand = UbootKommandant() graphviz = GraphvizOutput() graphviz.output_file = 'figures/callgraphtest.png' with PyCallGraph(output=graphviz): subcommand.list_plugins(None) config = Config() config.trace_filter = GlobbingFilter(exclude='*interface.arguments*'.split()) graphviz = GraphvizOutput() graphviz.output_file = 'figures/filtered_graph.png' with PyCallGraph(output=graphviz, config=config): subcommand.list_plugins(None) DEPTH = 100 config = Config(max_depth=DEPTH) graphviz = GraphvizOutput() graphviz.output_file = 'figures/trimmed_graph.png' with PyCallGraph(output=graphviz, config=config): subcommand.list_plugins(None)
[ "pycallgraph.Config", "ape.interface.ubootkommandant.UbootKommandant", "pycallgraph.PyCallGraph", "pycallgraph.output.GraphvizOutput" ]
[((256, 273), 'ape.interface.ubootkommandant.UbootKommandant', 'UbootKommandant', ([], {}), '()\n', (271, 273), False, 'from ape.interface.ubootkommandant import UbootKommandant\n'), ((285, 301), 'pycallgraph.output.GraphvizOutput', 'GraphvizOutput', ([], {}), '()\n', (299, 301), False, 'from pycallgraph.output import GraphvizOutput\n'), ((432, 440), 'pycallgraph.Config', 'Config', ([], {}), '()\n', (438, 440), False, 'from pycallgraph import Config\n'), ((530, 546), 'pycallgraph.output.GraphvizOutput', 'GraphvizOutput', ([], {}), '()\n', (544, 546), False, 'from pycallgraph.output import GraphvizOutput\n'), ((705, 728), 'pycallgraph.Config', 'Config', ([], {'max_depth': 'DEPTH'}), '(max_depth=DEPTH)\n', (711, 728), False, 'from pycallgraph import Config\n'), ((740, 756), 'pycallgraph.output.GraphvizOutput', 'GraphvizOutput', ([], {}), '()\n', (754, 756), False, 'from pycallgraph.output import GraphvizOutput\n'), ((358, 386), 'pycallgraph.PyCallGraph', 'PyCallGraph', ([], {'output': 'graphviz'}), '(output=graphviz)\n', (369, 386), False, 'from pycallgraph import PyCallGraph\n'), ((604, 647), 'pycallgraph.PyCallGraph', 'PyCallGraph', ([], {'output': 'graphviz', 'config': 'config'}), '(output=graphviz, config=config)\n', (615, 647), False, 'from pycallgraph import PyCallGraph\n'), ((813, 856), 'pycallgraph.PyCallGraph', 'PyCallGraph', ([], {'output': 'graphviz', 'config': 'config'}), '(output=graphviz, config=config)\n', (824, 856), False, 'from pycallgraph import PyCallGraph\n')]
import json from Recommender import RecommendationEngine from numpy import unique import plotly import pandas as pd from flask import Flask from flask import render_template, request, jsonify from plotly.graph_objs import Bar from load import load_data, load_model from figures import load_figures app = Flask(__name__) # load data df = load_data() # load model model = load_model() # index webpage displays cool visuals and receives user input text for model @app.route('/index') @app.route('/') def index(): # load figures and ids ids, graph_json = load_figures() # render web page with plotly graphs return render_template('master.html', ids=ids, graphJSON=graph_json) # web page that handles user query and displays model results @app.route('/go') def go(): # save user input in query # query = request.args.get('query', '') model_brand_name = [request.args.get('model_brand_name', '')] model_name = [request.args.get('model_name', '')] year = [int(request.args.get('year', ''))] transmission = [request.args.get('transmission', '')] engine_type = [request.args.get('engine_type', '')] body_type = [request.args.get('body_type', '')] mileage = [int(request.args.get('mileage', ''))] mileage_unit = [request.args.get('mileage_unit', '')] fuel_type = [request.args.get('fuel_type', '')] grade_score = [float(request.args.get('grade_score', ''))] first_owner = [request.args.get('first_owner', '')] selling_condition = [request.args.get('selling_condition', '')] interior_color = [request.args.get('interior_color', '')] # exterior_color = [request.args.get('exterior_color', '')] query = "Make: ", model_brand_name, '\n' " Model: ", model_name, "\n year: ", year, \ "\n Transmission: ", transmission, "\n Engine Type: ", engine_type, \ "\n Body Type: ", body_type pred_df = {'year': year, 'mileage': mileage, 'model_name': model_name, 'model_brand_name': model_brand_name, 'transmission': transmission, 'fuelType': fuel_type, 'sellingCondition': selling_condition, 'bodyType': body_type, 'mileageUnit': mileage_unit, 'interiorColor': interior_color, 'engineType': engine_type, 'gradeScore': grade_score, 'isFirstOwner': first_owner } pred_df = pd.DataFrame(pred_df) pred_df['model_name'] = pred_df['model_name'].apply(lambda row: row.strip().lower()) pred_df['model_brand_name'] = pred_df['model_brand_name'].apply(lambda row: row.strip().lower()) pred_df['interiorColor'] = pred_df['interiorColor'].apply(lambda row: row.strip().lower()) pred_df['bodyType'] = pred_df['bodyType'].apply(lambda row: row.strip().lower()) pred_df['engineType'] = pred_df['engineType'].apply(lambda row: row.strip().lower()) pred_df['isFirstOwner'] = pred_df['isFirstOwner'].apply(lambda row: row.strip().lower()) x_clean_pd = pd.read_csv('data/clean.csv') to_pred = pd.concat([x_clean_pd, pred_df], ignore_index=True) to_pred['isFirstOwnerDummy'] = pd.get_dummies(to_pred['isFirstOwner'].astype(str).apply(lambda row: row.strip().lower()), drop_first=True) to_pred['transmissionDummy'] = pd.get_dummies(to_pred['transmission'], drop_first=True) to_pred['fuelTypeDummy'] = pd.get_dummies(to_pred['fuelType'].astype(str), drop_first=True) to_pred['mileageUnitDummy'] = pd.get_dummies(to_pred['mileageUnit'].astype(str), drop_first=True) to_pred.drop(['isFirstOwner', 'transmission', 'fuelType', 'mileageUnit'], axis=1, inplace=True) to_pred = pd.get_dummies(to_pred) _pred = to_pred.loc[to_pred.shape[0] - 1] pred_price = model.predict(_pred.values.reshape(1, -1)) cars_df = pd.read_csv('data/cars.csv') trucks_df = pd.read_csv('data/trucks.csv') vehicles_df = pd.concat([cars_df, trucks_df], ignore_index=True) # convert values to lower case # vehicles_df_dtypes = list(vehicles_df.dtypes[(vehicles_df.dtypes == object)].index) vehicles_df_dtypes = ['model_name', 'model_brand_name', 'transmission', 'fuelType', 'sellingCondition', 'bodyType', 'engineType'] for t in vehicles_df_dtypes: vehicles_df[t] = vehicles_df[t].apply(lambda row: row.strip().lower()) recommender_engine = RecommendationEngine() recommendations = recommender_engine.get_recommendations(vehicles_df, model_name[0], model_brand_name[0], year[0], body_type[0]) # This will render the go.html Please see that file. return render_template( 'go.html', pred_df="{:,}".format(round(pred_price[0])), recommendations=recommendations ) @app.route('/html_table') def html_table(): return render_template('html_table.html') # def main(): # app.run(host='127.0.0.1', port=5000, debug=True) if __name__ == '__main__': app.run(debug=True)
[ "figures.load_figures", "flask.render_template", "flask.request.args.get", "pandas.read_csv", "flask.Flask", "pandas.get_dummies", "Recommender.RecommendationEngine", "pandas.DataFrame", "pandas.concat", "load.load_model", "load.load_data" ]
[((308, 323), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (313, 323), False, 'from flask import Flask\n'), ((342, 353), 'load.load_data', 'load_data', ([], {}), '()\n', (351, 353), False, 'from load import load_data, load_model\n'), ((377, 389), 'load.load_model', 'load_model', ([], {}), '()\n', (387, 389), False, 'from load import load_data, load_model\n'), ((569, 583), 'figures.load_figures', 'load_figures', ([], {}), '()\n', (581, 583), False, 'from figures import load_figures\n'), ((641, 702), 'flask.render_template', 'render_template', (['"""master.html"""'], {'ids': 'ids', 'graphJSON': 'graph_json'}), "('master.html', ids=ids, graphJSON=graph_json)\n", (656, 702), False, 'from flask import render_template, request, jsonify\n'), ((2344, 2365), 'pandas.DataFrame', 'pd.DataFrame', (['pred_df'], {}), '(pred_df)\n', (2356, 2365), True, 'import pandas as pd\n'), ((2938, 2967), 'pandas.read_csv', 'pd.read_csv', (['"""data/clean.csv"""'], {}), "('data/clean.csv')\n", (2949, 2967), True, 'import pandas as pd\n'), ((2983, 3034), 'pandas.concat', 'pd.concat', (['[x_clean_pd, pred_df]'], {'ignore_index': '(True)'}), '([x_clean_pd, pred_df], ignore_index=True)\n', (2992, 3034), True, 'import pandas as pd\n'), ((3220, 3276), 'pandas.get_dummies', 'pd.get_dummies', (["to_pred['transmission']"], {'drop_first': '(True)'}), "(to_pred['transmission'], drop_first=True)\n", (3234, 3276), True, 'import pandas as pd\n'), ((3597, 3620), 'pandas.get_dummies', 'pd.get_dummies', (['to_pred'], {}), '(to_pred)\n', (3611, 3620), True, 'import pandas as pd\n'), ((3752, 3780), 'pandas.read_csv', 'pd.read_csv', (['"""data/cars.csv"""'], {}), "('data/cars.csv')\n", (3763, 3780), True, 'import pandas as pd\n'), ((3797, 3827), 'pandas.read_csv', 'pd.read_csv', (['"""data/trucks.csv"""'], {}), "('data/trucks.csv')\n", (3808, 3827), True, 'import pandas as pd\n'), ((3847, 3897), 'pandas.concat', 'pd.concat', (['[cars_df, trucks_df]'], {'ignore_index': '(True)'}), '([cars_df, trucks_df], ignore_index=True)\n', (3856, 3897), True, 'import pandas as pd\n'), ((4297, 4319), 'Recommender.RecommendationEngine', 'RecommendationEngine', ([], {}), '()\n', (4317, 4319), False, 'from Recommender import RecommendationEngine\n'), ((4716, 4750), 'flask.render_template', 'render_template', (['"""html_table.html"""'], {}), "('html_table.html')\n", (4731, 4750), False, 'from flask import render_template, request, jsonify\n'), ((895, 935), 'flask.request.args.get', 'request.args.get', (['"""model_brand_name"""', '""""""'], {}), "('model_brand_name', '')\n", (911, 935), False, 'from flask import render_template, request, jsonify\n'), ((955, 989), 'flask.request.args.get', 'request.args.get', (['"""model_name"""', '""""""'], {}), "('model_name', '')\n", (971, 989), False, 'from flask import render_template, request, jsonify\n'), ((1058, 1094), 'flask.request.args.get', 'request.args.get', (['"""transmission"""', '""""""'], {}), "('transmission', '')\n", (1074, 1094), False, 'from flask import render_template, request, jsonify\n'), ((1115, 1150), 'flask.request.args.get', 'request.args.get', (['"""engine_type"""', '""""""'], {}), "('engine_type', '')\n", (1131, 1150), False, 'from flask import render_template, request, jsonify\n'), ((1169, 1202), 'flask.request.args.get', 'request.args.get', (['"""body_type"""', '""""""'], {}), "('body_type', '')\n", (1185, 1202), False, 'from flask import render_template, request, jsonify\n'), ((1277, 1313), 'flask.request.args.get', 'request.args.get', (['"""mileage_unit"""', '""""""'], {}), "('mileage_unit', '')\n", (1293, 1313), False, 'from flask import render_template, request, jsonify\n'), ((1332, 1365), 'flask.request.args.get', 'request.args.get', (['"""fuel_type"""', '""""""'], {}), "('fuel_type', '')\n", (1348, 1365), False, 'from flask import render_template, request, jsonify\n'), ((1449, 1484), 'flask.request.args.get', 'request.args.get', (['"""first_owner"""', '""""""'], {}), "('first_owner', '')\n", (1465, 1484), False, 'from flask import render_template, request, jsonify\n'), ((1511, 1552), 'flask.request.args.get', 'request.args.get', (['"""selling_condition"""', '""""""'], {}), "('selling_condition', '')\n", (1527, 1552), False, 'from flask import render_template, request, jsonify\n'), ((1576, 1614), 'flask.request.args.get', 'request.args.get', (['"""interior_color"""', '""""""'], {}), "('interior_color', '')\n", (1592, 1614), False, 'from flask import render_template, request, jsonify\n'), ((1007, 1035), 'flask.request.args.get', 'request.args.get', (['"""year"""', '""""""'], {}), "('year', '')\n", (1023, 1035), False, 'from flask import render_template, request, jsonify\n'), ((1223, 1254), 'flask.request.args.get', 'request.args.get', (['"""mileage"""', '""""""'], {}), "('mileage', '')\n", (1239, 1254), False, 'from flask import render_template, request, jsonify\n'), ((1392, 1427), 'flask.request.args.get', 'request.args.get', (['"""grade_score"""', '""""""'], {}), "('grade_score', '')\n", (1408, 1427), False, 'from flask import render_template, request, jsonify\n')]
import argparse import os import random from PIL import Image import cv2 import gym import numpy as np def save_as_image(observation, save_dir, img_name, prefix="img_"): # donwnscaling the image im_array = cv2.resize(observation, IMAGE_SIZE) im = Image.fromarray(im_array, 'RGB') imname = '{}{}.png'.format(prefix, img_name) im.save(os.path.join(save_dir, imname)) if __name__ == "__main__": arg_parser = argparse.ArgumentParser() # Adding the arguments arg_parser.add_argument("--save_dir", type=str, default=SAVE_DIR, help="Relative path to the directory to store " "the data (default value is 'data/'") arg_parser.add_argument("--num_images", type=int, default=IMAGES_TO_GENERATE, help="Number of images to generate (default " "value is 10000)") args = arg_parser.parse_args() save_dir = args.save_dir num_images = args.num_images if not os.path.exists(save_dir): os.makedirs(save_dir) envs = [(gym.make(name)) for name in ENV_NAMES] env = random.choice(envs) env.reset() i, current_env_images = 0, 0 while i < num_images: obs, _, is_done, _ = env.step(env.action_space.sample()) if np.mean(obs) > 0.01: save_as_image(obs, save_dir, str(i)) current_env_images += 1 i += 1 else: continue if is_done or current_env_images % MAX_IMAGES_PER_ENV_INSTANCE == 0: current_env_images = 0 env = random.choice(envs) env.reset()
[ "os.path.exists", "PIL.Image.fromarray", "random.choice", "numpy.mean", "argparse.ArgumentParser", "os.makedirs", "os.path.join", "cv2.resize", "gym.make" ]
[((270, 305), 'cv2.resize', 'cv2.resize', (['observation', 'IMAGE_SIZE'], {}), '(observation, IMAGE_SIZE)\n', (280, 305), False, 'import cv2\n'), ((315, 347), 'PIL.Image.fromarray', 'Image.fromarray', (['im_array', '"""RGB"""'], {}), "(im_array, 'RGB')\n", (330, 347), False, 'from PIL import Image\n'), ((487, 512), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (510, 512), False, 'import argparse\n'), ((1224, 1243), 'random.choice', 'random.choice', (['envs'], {}), '(envs)\n', (1237, 1243), False, 'import random\n'), ((409, 439), 'os.path.join', 'os.path.join', (['save_dir', 'imname'], {}), '(save_dir, imname)\n', (421, 439), False, 'import os\n'), ((1105, 1129), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (1119, 1129), False, 'import os\n'), ((1139, 1160), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n', (1150, 1160), False, 'import os\n'), ((1175, 1189), 'gym.make', 'gym.make', (['name'], {}), '(name)\n', (1183, 1189), False, 'import gym\n'), ((1396, 1408), 'numpy.mean', 'np.mean', (['obs'], {}), '(obs)\n', (1403, 1408), True, 'import numpy as np\n'), ((1686, 1705), 'random.choice', 'random.choice', (['envs'], {}), '(envs)\n', (1699, 1705), False, 'import random\n')]
'''Algorithms for converting grammars to Chomsky Normal Form.''' from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, \ ProductionRule, SubscriptedNonterminal from util.moreitertools import powerset def is_cnf_rule(r, start): '''Return whether a production rule is in CNF. Must indicate the grammar's start variable.''' rs = r.right_side return (len(rs) == 1 and rs[0].is_terminal()) or \ (len(rs) == 2 and all(map(lambda x: x.is_nonterminal() and \ x != start, rs))) or \ (r.left_side == start and not rs) def is_cnf(G): '''Return whether a grammar is in CNF.''' return all(map(lambda x: is_cnf_rule(x, G.start), G.productions)) def _first_rule_that(productions, pred): for i, p in enumerate(productions): if pred(p): return i def _first_empty_rule(productions, start): return _first_rule_that(productions, \ lambda x: not x.right_side and \ not x.left_side == start) def _first_unit_rule(productions): return _first_rule_that(productions, \ lambda x: len(x.right_side) == 1 \ and isinstance(x.right_side[0], Nonterminal)) def substitutions(sentence, production): '''Returns all of the distinct ways of applying a derivation rule to a sentence, including no change at all.''' indices = [i for i, s in enumerate(sentence) if s == production.left_side] result = [] for subset in powerset(indices): substitution = [] for i, symbol in enumerate(sentence): if i in subset: substitution.extend(production.right_side) else: substitution.append(symbol) if substitution not in result: result.append(substitution) return result def chain(p, used_variables): '''Given a production rule p, return a list of equivalent rules such that the right side of each rule is no more than two symbols long.''' rs = p.right_side if len(rs) <= 2: return [p] first = rs[0] second_name = ''.join([str(s) for s in rs[1:]]) second = SubscriptedNonterminal.next_unused(second_name, used_variables) first_new_rule = ProductionRule(p.left_side, (first, second)) second_new_rule = ProductionRule(second, rs[1:]) return [first_new_rule] + \ chain(second_new_rule, used_variables | set([second])) def get_variables(productions): '''Return a set of all the variables which appear in a list of productions. ''' result = set() for p in productions: result.add(p.left_side) for s in p.right_side: if isinstance(s, Nonterminal): result.add(s) return result def replace_terminals(p, proxy_rules): '''Replace all the terminal symbols in a production rule with equivalent variables, given a mapping from terminals to proxy production rules. Return a pair containing the fixed rule and a list of the terminals replaced.''' rs = p.right_side if len(rs) < 2 or p in proxy_rules.itervalues(): return p, [] new_rs = [] replaced = [] for s in rs: if isinstance(s, Terminal): new_rs.append(proxy_rules[s].left_side) replaced.append(s) else: new_rs.append(s) return ProductionRule(p.left_side, new_rs), replaced def ChomskyNormalForm(G): '''Given a CFG G, return an equivalent CFG in Chomsky normal form.''' productions = list(G.productions) # Add a new start variable S0 and add the rule S0 -> S S0 = SubscriptedNonterminal(G.start.name, 0) productions[:0] = [ProductionRule(S0, [G.start])] # Remove e rules removed_rules = [] while True: i = _first_empty_rule(productions, S0) if i is None: break pe = productions[i] removed_rules.append(pe) del productions[i] new_rules = [ProductionRule(rule.left_side, sentence) \ for rule in productions[1:] \ for sentence in substitutions(rule.right_side, pe)] productions[1:] = [r for r in new_rules if r not in removed_rules] # Remove unit rules removed_rules = [] while True: i = _first_unit_rule(productions) if i is None: break pu = productions[i] removed_rules.append(pu) new_rules = [ProductionRule(pu.left_side, p.right_side) \ for p in productions if p.left_side == pu.right_side[0]] productions[i:i+1] = [r for r in new_rules if r not in productions \ and r not in removed_rules] # Chain right sides of rules i = 0 while i < len(productions): new_rules = chain(productions[i], get_variables(productions)) productions[i:i+1] = new_rules i += len(new_rules) # Replace terminal symbols with proxy variables terminals = G.terminals variables = get_variables(productions) proxy_rules = \ {t : ProductionRule( SubscriptedNonterminal.next_unused(t.name.upper(), variables), [t] ) for t in terminals} added = {t : False for t in terminals} i = 0 while i < len(productions): new_rule, replaced = replace_terminals(productions[i], proxy_rules) productions[i] = new_rule for t in replaced: if not added[t]: productions.append(proxy_rules[t]) added[t] = True i += len(new_rules) return ContextFreeGrammar(productions)
[ "cfg.core.SubscriptedNonterminal", "cfg.core.SubscriptedNonterminal.next_unused", "cfg.core.ProductionRule", "cfg.core.ContextFreeGrammar", "util.moreitertools.powerset" ]
[((1564, 1581), 'util.moreitertools.powerset', 'powerset', (['indices'], {}), '(indices)\n', (1572, 1581), False, 'from util.moreitertools import powerset\n'), ((2224, 2287), 'cfg.core.SubscriptedNonterminal.next_unused', 'SubscriptedNonterminal.next_unused', (['second_name', 'used_variables'], {}), '(second_name, used_variables)\n', (2258, 2287), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((2309, 2353), 'cfg.core.ProductionRule', 'ProductionRule', (['p.left_side', '(first, second)'], {}), '(p.left_side, (first, second))\n', (2323, 2353), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((2376, 2406), 'cfg.core.ProductionRule', 'ProductionRule', (['second', 'rs[1:]'], {}), '(second, rs[1:])\n', (2390, 2406), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((3691, 3730), 'cfg.core.SubscriptedNonterminal', 'SubscriptedNonterminal', (['G.start.name', '(0)'], {}), '(G.start.name, 0)\n', (3713, 3730), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((5664, 5695), 'cfg.core.ContextFreeGrammar', 'ContextFreeGrammar', (['productions'], {}), '(productions)\n', (5682, 5695), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((3420, 3455), 'cfg.core.ProductionRule', 'ProductionRule', (['p.left_side', 'new_rs'], {}), '(p.left_side, new_rs)\n', (3434, 3455), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((3754, 3783), 'cfg.core.ProductionRule', 'ProductionRule', (['S0', '[G.start]'], {}), '(S0, [G.start])\n', (3768, 3783), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((4042, 4082), 'cfg.core.ProductionRule', 'ProductionRule', (['rule.left_side', 'sentence'], {}), '(rule.left_side, sentence)\n', (4056, 4082), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n'), ((4512, 4554), 'cfg.core.ProductionRule', 'ProductionRule', (['pu.left_side', 'p.right_side'], {}), '(pu.left_side, p.right_side)\n', (4526, 4554), False, 'from cfg.core import ContextFreeGrammar, Terminal, Nonterminal, ProductionRule, SubscriptedNonterminal\n')]
import torch.nn as nn from .classification import ClassificationBranch from .attribute import AttributeBranch from .baseline import BaselineReidBranch from .pose import Pose2DHead from .semantic_segmentation import FpnSemHead from models import register_model, BaseModel from builders import model_builder from models.utils import grad_reverse @register_model("multi_head_sem_multi_task") class MultiHeadSemMultiTaskNetwork(BaseModel): @staticmethod def create_endpoints(task_heads): endpoints = {} for task_head in task_heads: endpoints.update(task_head.create_endpoints()) endpoints['emb'] = None endpoints['sem-logits'] = None return endpoints def __init__(self, backbone, sem_head, task_heads): super().__init__() self.task_heads = nn.ModuleList(task_heads) self.endpoints = self.create_endpoints(task_heads) self.backbone = backbone self.sem_head = sem_head self.trained_on = {} self.trained_on['num_seg_classes'] = sem_head.num_classes def forward(self, data, endpoints, **kwargs): _, _, h, w = data['img'].size() feature_pyramid, task_xs = self.backbone(data, endpoints, **kwargs) endpoints = self.sem_head(feature_pyramid, (h, w), endpoints) for task_head, task_x in zip(self.task_heads, task_xs): endpoints = task_head(task_x, endpoints) if 'reid_emb' in endpoints: endpoints["emb"] = endpoints['reid_emb'] return endpoints @staticmethod def build(cfg): task_cfgs = cfg['tasks'] tasks = [] for task, task_cfg in task_cfgs.items(): # depending on the backbone model task_cfg['input_dim'] = 2048 if task == "attribute": tasks.append(AttributeBranch.build(task_cfg)) elif task == "classification": task_cfg['num_classes'] = cfg['num_classes'] tasks.append(ClassificationBranch.build(task_cfg)) elif task == "pose": task_cfg['num_joints'] = cfg['num_joints'] tasks.append(Pose2DHead.build(task_cfg)) elif task == 'reid': print("created reid") tasks.append(BaselineReidBranch.build(task_cfg)) else: raise ValueError("Unknown task: {}".format(task)) num_seg_classes = cfg['num_seg_classes'] sem_head = FpnSemHead(num_seg_classes, 256) backbone = model_builder.build(cfg['backbone']) model = MultiHeadSemMultiTaskNetwork(backbone, sem_head, tasks) return model, [], []
[ "models.register_model", "torch.nn.ModuleList", "builders.model_builder.build" ]
[((347, 390), 'models.register_model', 'register_model', (['"""multi_head_sem_multi_task"""'], {}), "('multi_head_sem_multi_task')\n", (361, 390), False, 'from models import register_model, BaseModel\n'), ((819, 844), 'torch.nn.ModuleList', 'nn.ModuleList', (['task_heads'], {}), '(task_heads)\n', (832, 844), True, 'import torch.nn as nn\n'), ((2519, 2555), 'builders.model_builder.build', 'model_builder.build', (["cfg['backbone']"], {}), "(cfg['backbone'])\n", (2538, 2555), False, 'from builders import model_builder\n')]
from datetime import datetime def execution_time(func): def wrapper(*args, **kwargs): # *args and **kwargs --> Doesn't matter the number of arguments # or key arguments gived to the nested function initial_time = datetime.now() func(*args, **kwargs) final_time = datetime.now() time_elapsed = final_time - initial_time print("Pasaron " + str(time_elapsed.total_seconds()) + " segundos") return wrapper @execution_time def Random_func(): for _ in range(1, 10000000): pass @execution_time def Addition(a: int, b: int) -> int: return a + b @execution_time def Greeting(name = " "): print("Hey " + name + "!") def run(): Random_func() Addition(5, 5) Greeting("Yery") if __name__ == '__main__': run()
[ "datetime.datetime.now" ]
[((266, 280), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (278, 280), False, 'from datetime import datetime\n'), ((332, 346), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (344, 346), False, 'from datetime import datetime\n')]
#!/usr/bin/env python3 # Copyright 2019 The NeuroPy Authors # # 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. import os import sys import virtualenv import pip import subprocess from termcolor import cprint def initialize(arguments): # Load virtualenv if (not arguments.environment): return print('Initializing environment...', end=' ') venv_dir = os.path.abspath(os.path.join(arguments.project_path, ".venv")) if not os.path.exists(venv_dir): cprint('failed\nVirtual environment not found, Creating...', 'yellow', end=' ') # create and activate the virtual environment virtualenv.create_environment(venv_dir) # pip install a package using the venv as a prefix # pip.main(["install", "--prefix", venv_dir, ]) subprocess.check_call([sys.executable, '-m', '{venv_dir}/bin/pip', 'install', os.path.join(arguments.project_path,'requirements.txt')]) cprint('done', 'green') print('Loading virtualenv...', end=' ') # Activate virtualenv activation_script = os.path.join(venv_dir, 'bin/activate_this.py') exec(open(activation_script).read(), {'__file__': activation_script}) cprint('done', 'green')
[ "virtualenv.create_environment", "os.path.exists", "os.path.join", "termcolor.cprint" ]
[((1563, 1609), 'os.path.join', 'os.path.join', (['venv_dir', '"""bin/activate_this.py"""'], {}), "(venv_dir, 'bin/activate_this.py')\n", (1575, 1609), False, 'import os\n'), ((1688, 1711), 'termcolor.cprint', 'cprint', (['"""done"""', '"""green"""'], {}), "('done', 'green')\n", (1694, 1711), False, 'from termcolor import cprint\n'), ((887, 932), 'os.path.join', 'os.path.join', (['arguments.project_path', '""".venv"""'], {}), "(arguments.project_path, '.venv')\n", (899, 932), False, 'import os\n'), ((946, 970), 'os.path.exists', 'os.path.exists', (['venv_dir'], {}), '(venv_dir)\n', (960, 970), False, 'import os\n'), ((980, 1066), 'termcolor.cprint', 'cprint', (['"""failed\nVirtual environment not found, Creating..."""', '"""yellow"""'], {'end': '""" """'}), '("""failed\nVirtual environment not found, Creating...""", \'yellow\',\n end=\' \')\n', (986, 1066), False, 'from termcolor import cprint\n'), ((1122, 1161), 'virtualenv.create_environment', 'virtualenv.create_environment', (['venv_dir'], {}), '(venv_dir)\n', (1151, 1161), False, 'import virtualenv\n'), ((1439, 1462), 'termcolor.cprint', 'cprint', (['"""done"""', '"""green"""'], {}), "('done', 'green')\n", (1445, 1462), False, 'from termcolor import cprint\n'), ((1364, 1420), 'os.path.join', 'os.path.join', (['arguments.project_path', '"""requirements.txt"""'], {}), "(arguments.project_path, 'requirements.txt')\n", (1376, 1420), False, 'import os\n')]
from typing import Tuple import torch from candlelight.vector_sampler import VectorSampler def cubic( input: torch.Tensor, value: torch.Tensor, domain: Tuple[float, float] = (0, 1) ) -> torch.Tensor: n = value.size(0) - 1 h = (domain[1] - domain[0]) / n A = torch.eye(n + 1) + torch.diagflat(torch.full((n,), 0.5), 1) A += A.T A[0, 1] = A[-1, -2] = 0 d = 3 * (value[2:] - 2 * value[1:-1] + value[:-2]) / h ** 2 d = torch.cat((torch.zeros(1), d, torch.zeros(1))).unsqueeze_(-1) z, _ = torch.solve(d, A) sampler = VectorSampler(input, domain, n) x = torch.linspace( domain[0], domain[1], n + 1, dtype=torch.float32, device=input.device ) distance_left = input - sampler.get_left(x) distance_right = h - distance_left cubic_left = torch.pow(distance_left, 3) cubic_right = torch.pow(distance_right, 3) z_left = sampler.get_left(z) z_right = sampler.get_right(z) value_left = sampler.get_left(value) value_right = sampler.get_right(value) f = z_left * cubic_right + z_right * cubic_left f /= 6 * h f += (value_right / h - z_right * h / 6) * distance_left f += (value_left / h - z_left * h / 6) * distance_right return f
[ "torch.full", "torch.eye", "torch.solve", "torch.pow", "candlelight.vector_sampler.VectorSampler", "torch.zeros", "torch.linspace" ]
[((524, 541), 'torch.solve', 'torch.solve', (['d', 'A'], {}), '(d, A)\n', (535, 541), False, 'import torch\n'), ((557, 588), 'candlelight.vector_sampler.VectorSampler', 'VectorSampler', (['input', 'domain', 'n'], {}), '(input, domain, n)\n', (570, 588), False, 'from candlelight.vector_sampler import VectorSampler\n'), ((597, 687), 'torch.linspace', 'torch.linspace', (['domain[0]', 'domain[1]', '(n + 1)'], {'dtype': 'torch.float32', 'device': 'input.device'}), '(domain[0], domain[1], n + 1, dtype=torch.float32, device=\n input.device)\n', (611, 687), False, 'import torch\n'), ((801, 828), 'torch.pow', 'torch.pow', (['distance_left', '(3)'], {}), '(distance_left, 3)\n', (810, 828), False, 'import torch\n'), ((847, 875), 'torch.pow', 'torch.pow', (['distance_right', '(3)'], {}), '(distance_right, 3)\n', (856, 875), False, 'import torch\n'), ((278, 294), 'torch.eye', 'torch.eye', (['(n + 1)'], {}), '(n + 1)\n', (287, 294), False, 'import torch\n'), ((312, 333), 'torch.full', 'torch.full', (['(n,)', '(0.5)'], {}), '((n,), 0.5)\n', (322, 333), False, 'import torch\n'), ((462, 476), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (473, 476), False, 'import torch\n'), ((481, 495), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (492, 495), False, 'import torch\n')]
# -*- coding: utf-8 -*- # @Author: Administrator # @Date: 2019-04-28 02:23:29 # @Last Modified by: Administrator # @Last Modified time: 2019-05-26 23:57:30 __all__ = [ "BotzoneClient", ] import os import time from .const import USER_AGENT from .const import BOTZONE_URL_HOST, BOTZONE_URL_LOGIN, BOTZONE_URL_MYBOTS, BOTZONE_URL_BOT_DETAIL,\ BOTZONE_URL_GLOBAL_MATCH_LIST, BOTZONE_URL_CONTEST_DETAIL, BOTZONE_URL_GROUP,\ BOTZONE_URL_FAVORITES, BOTZONE_URL_REMOVE_FAVORITE_MATCH from .base import BaseClient from .cookies import CookiesManagerMixin from .hooks import get_hooks, hook_check_status_code, hook_botzone_check_success_field from ..utils import Singleton from ..log import ConsoleLogger _logger = ConsoleLogger("client.botzone") class BotzoneClient(BaseClient, CookiesManagerMixin, metaclass=Singleton): USE_HTTP20 = False HOST = BOTZONE_URL_HOST HEADERS = { "User-Agent": USER_AGENT, "Origin": BOTZONE_URL_HOST, "x-requested-with": "XMLHttpRequest", } def __init__(self): _logger.info("Botzone client launched") BaseClient.__init__(self) CookiesManagerMixin.__init__(self) _logger.info("load cookies") self._load_cookies() # 创建时自动导入本地 cookies 缓存 def login(self, email, password): """ 登录 API """ _logger.info("Email: %s" % email) _logger.info("login ...") r = self._post( url=BOTZONE_URL_LOGIN, data={ "email": email, "password": password, }, headers={ "Referer": BOTZONE_URL_HOST, }, hooks=get_hooks(hook_check_status_code, hook_botzone_check_success_field), ) _logger.info("login successfully") self._save_cookies() # 保存 cookies _logger.info("save login cookies") #self._save_content(r, "login.html") return r def get_favorites(self): """ 获取玩家收藏 """ _logger.info("get favorites") r = self._get( url=BOTZONE_URL_FAVORITES, headers={ "Referer": BOTZONE_URL_HOST, }, hooks=get_hooks(hook_check_status_code), ) _logger.info("get favorites successfully") #self._save_content(r, "favorites.json") return r def remove_fovorite_match(self, matchID): """ 删除收藏的比赛 """ _logger.info("remove favorite match %s" % matchID) r = self._post( url=BOTZONE_URL_REMOVE_FAVORITE_MATCH, data={ "matchid": matchID, }, headers={ "Referer": BOTZONE_URL_HOST, }, hooks=get_hooks(hook_check_status_code, hook_botzone_check_success_field), ) _logger.info("remove favorite match %s successfully" % matchID) return r def get_mybots(self): """ 获取 My Bots 页 """ _logger.info("get mybots ...") r = self._get( url=BOTZONE_URL_MYBOTS, hooks=get_hooks(hook_check_status_code), ) _logger.info("get mybots successfully") #self._save_content(r, "mybots.html") return r def get_bot_detail(self, botID): """ 获取 Bot 全部具体信息的 """ _logger.info("BotID: %s" % botID) _logger.info("get bot detail ...") r = self._get( url=BOTZONE_URL_BOT_DETAIL.format(botID=botID), params={ "_": int( time.time() * 1000 ), }, headers={ "Referer": BOTZONE_URL_MYBOTS, }, hooks=get_hooks(hook_check_status_code), ) _logger.info("get bot detail successfully") #self._save_content(r, "bot_detail_%s.json" % botID) return r def get_global_match_list(self, gameID, startID="", endID=""): """ 获取全局的比赛记录 """ _logger.info("GameID: %s" % gameID) if startID != "": _logger.info("StartID: %s" % startID) _logger.info("get global match list ...") r = self._get( url=BOTZONE_URL_GLOBAL_MATCH_LIST, params={ "startid": startID, "endid": endID, "game": gameID, }, hooks=get_hooks(hook_check_status_code), ) _logger.info("get global match list successfully") #self._save_content(r, "global_match_list.html") return r def get_contest_detail(self, contestID, groupID): """ 获取小组赛的描述、玩家列表、比赛记录等 """ _logger.info("ContestID: %s" % contestID) _logger.info("get contest detail ...") r = self._get( url=BOTZONE_URL_CONTEST_DETAIL.format(contestID=contestID), headers={ "Referer": BOTZONE_URL_GROUP.format(groupID=groupID) }, hooks=get_hooks(hook_check_status_code), ) _logger.info("get contest detail successfully") #self._save_content(r, "contest_detail.json") return r
[ "time.time" ]
[((3806, 3817), 'time.time', 'time.time', ([], {}), '()\n', (3815, 3817), False, 'import time\n')]
import praw import re import tweepy import secrets def cleantitle(title): return re.findall("^\[.*\](.*)", title)[0] def parsepost(post): if not post.is_self: if "reddituploads" in post.url: status = "" else: status = cleantitle(post.title) + ": " + post.url else: status = cleantitle(post.title) return status def main(): secrets.init() reddit = praw.Reddit(user_agent="twitter.com:tweets_iaf v 0.0.2 by /u/umeshunni") hotposts = reddit.get_subreddit('gameofthrones').get_top(limit=10) auth = tweepy.OAuthHandler(secrets.consumer_key, secrets.consumer_secret) auth.set_access_token(secrets.access_token, secrets.access_token_secret) twitter = tweepy.API(auth) for post in hotposts: status = parsepost(post) if post.is_self or not status: print ("Skipped: " + status) else: print ("Tweeting: " + status ) #twitter.update_status(status) if __name__ == "__main__": main()
[ "tweepy.API", "praw.Reddit", "re.findall", "secrets.init", "tweepy.OAuthHandler" ]
[((350, 364), 'secrets.init', 'secrets.init', ([], {}), '()\n', (362, 364), False, 'import secrets\n'), ((376, 448), 'praw.Reddit', 'praw.Reddit', ([], {'user_agent': '"""twitter.com:tweets_iaf v 0.0.2 by /u/umeshunni"""'}), "(user_agent='twitter.com:tweets_iaf v 0.0.2 by /u/umeshunni')\n", (387, 448), False, 'import praw\n'), ((528, 594), 'tweepy.OAuthHandler', 'tweepy.OAuthHandler', (['secrets.consumer_key', 'secrets.consumer_secret'], {}), '(secrets.consumer_key, secrets.consumer_secret)\n', (547, 594), False, 'import tweepy\n'), ((681, 697), 'tweepy.API', 'tweepy.API', (['auth'], {}), '(auth)\n', (691, 697), False, 'import tweepy\n'), ((83, 117), 're.findall', 're.findall', (['"""^\\\\[.*\\\\](.*)"""', 'title'], {}), "('^\\\\[.*\\\\](.*)', title)\n", (93, 117), False, 'import re\n')]
import pandas as pd from joblib import load, dump from matplotlib import pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.metrics import plot_confusion_matrix # train the model with inbuilt classifier def train(): """Data set reading""" df = pd.read_csv("../dataset/train.csv.csv") X = df.iloc[:, :-1] y = df['class'] model = LogisticRegression(n_jobs=-1) model.fit(X, y) dump(model, '../model/lr_model_inbuilt.joblib') print('Model saved') # do prediction from the saved model def prediction(data, plot=True): model = load('../model/lr_model_inbuilt.joblib') predictions = model.predict(data) if plot: plot_confusion_matrix(model, data, predictions) plt.show() return predictions def controller_predict(controller, test_data, test_labels, plot=True): clf = load('model/lr_model_inbuilt.joblib') predictions = clf.predict(test_data) if plot: plot_confusion_matrix(clf, test_data, test_labels) plt.show() controller.setLRInbuilt(round(accuracy_score(test_labels, predictions) * 100, 3))
[ "pandas.read_csv", "joblib.dump", "sklearn.linear_model.LogisticRegression", "joblib.load", "sklearn.metrics.plot_confusion_matrix", "sklearn.metrics.accuracy_score", "matplotlib.pyplot.show" ]
[((325, 364), 'pandas.read_csv', 'pd.read_csv', (['"""../dataset/train.csv.csv"""'], {}), "('../dataset/train.csv.csv')\n", (336, 364), True, 'import pandas as pd\n'), ((422, 451), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'n_jobs': '(-1)'}), '(n_jobs=-1)\n', (440, 451), False, 'from sklearn.linear_model import LogisticRegression\n'), ((476, 523), 'joblib.dump', 'dump', (['model', '"""../model/lr_model_inbuilt.joblib"""'], {}), "(model, '../model/lr_model_inbuilt.joblib')\n", (480, 523), False, 'from joblib import load, dump\n'), ((633, 673), 'joblib.load', 'load', (['"""../model/lr_model_inbuilt.joblib"""'], {}), "('../model/lr_model_inbuilt.joblib')\n", (637, 673), False, 'from joblib import load, dump\n'), ((907, 944), 'joblib.load', 'load', (['"""model/lr_model_inbuilt.joblib"""'], {}), "('model/lr_model_inbuilt.joblib')\n", (911, 944), False, 'from joblib import load, dump\n'), ((734, 781), 'sklearn.metrics.plot_confusion_matrix', 'plot_confusion_matrix', (['model', 'data', 'predictions'], {}), '(model, data, predictions)\n', (755, 781), False, 'from sklearn.metrics import plot_confusion_matrix\n'), ((790, 800), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (798, 800), True, 'from matplotlib import pyplot as plt\n'), ((1007, 1057), 'sklearn.metrics.plot_confusion_matrix', 'plot_confusion_matrix', (['clf', 'test_data', 'test_labels'], {}), '(clf, test_data, test_labels)\n', (1028, 1057), False, 'from sklearn.metrics import plot_confusion_matrix\n'), ((1066, 1076), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1074, 1076), True, 'from matplotlib import pyplot as plt\n'), ((1112, 1152), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['test_labels', 'predictions'], {}), '(test_labels, predictions)\n', (1126, 1152), False, 'from sklearn.metrics import accuracy_score\n')]
# Generated by Django 3.2.6 on 2021-10-12 06:54 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contact_book', '0003_merge_0002_auto_20211004_0132_0002_auto_20211010_2348'), ] operations = [ migrations.AddField( model_name='importantdatetype', name='author', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='socialmediasite', name='author', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='socialmediasite', name='url_format', field=models.CharField(default='', max_length=255), ), migrations.AlterField( model_name='importantdatetype', name='icon', field=models.CharField(default='', max_length=30), preserve_default=False, ), migrations.AlterField( model_name='socialmediasite', name='icon', field=models.CharField(default='', max_length=30), ), migrations.AlterUniqueTogether( name='importantdatetype', unique_together={('label', 'author')}, ), migrations.AlterUniqueTogether( name='socialmediasite', unique_together={('site', 'author')}, ), migrations.RemoveField( model_name='importantdatetype', name='is_default', ), migrations.RemoveField( model_name='socialmediasite', name='is_default', ), ]
[ "django.db.migrations.AlterUniqueTogether", "django.db.migrations.RemoveField", "django.db.models.ForeignKey", "django.db.migrations.swappable_dependency", "django.db.models.CharField" ]
[((227, 284), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (258, 284), False, 'from django.db import migrations, models\n'), ((1455, 1555), 'django.db.migrations.AlterUniqueTogether', 'migrations.AlterUniqueTogether', ([], {'name': '"""importantdatetype"""', 'unique_together': "{('label', 'author')}"}), "(name='importantdatetype', unique_together={(\n 'label', 'author')})\n", (1485, 1555), False, 'from django.db import migrations, models\n'), ((1595, 1692), 'django.db.migrations.AlterUniqueTogether', 'migrations.AlterUniqueTogether', ([], {'name': '"""socialmediasite"""', 'unique_together': "{('site', 'author')}"}), "(name='socialmediasite', unique_together={(\n 'site', 'author')})\n", (1625, 1692), False, 'from django.db import migrations, models\n'), ((1732, 1805), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""importantdatetype"""', 'name': '"""is_default"""'}), "(model_name='importantdatetype', name='is_default')\n", (1754, 1805), False, 'from django.db import migrations, models\n'), ((1850, 1921), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""socialmediasite"""', 'name': '"""is_default"""'}), "(model_name='socialmediasite', name='is_default')\n", (1872, 1921), False, 'from django.db import migrations, models\n'), ((518, 637), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': 'settings.AUTH_USER_MODEL'}), '(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to=settings.AUTH_USER_MODEL)\n', (535, 637), False, 'from django.db import migrations, models\n'), ((761, 880), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': 'settings.AUTH_USER_MODEL'}), '(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to=settings.AUTH_USER_MODEL)\n', (778, 880), False, 'from django.db import migrations, models\n'), ((1008, 1052), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(255)'}), "(default='', max_length=255)\n", (1024, 1052), False, 'from django.db import migrations, models\n'), ((1183, 1226), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(30)'}), "(default='', max_length=30)\n", (1199, 1226), False, 'from django.db import migrations, models\n'), ((1391, 1434), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(30)'}), "(default='', max_length=30)\n", (1407, 1434), False, 'from django.db import migrations, models\n')]
import numpy as np def hermitegaussian(coeffs,x,sigma): xhat = (x/sigma) herms = np.polynomial.hermite.Hermite(coeffs) return herms(xhat) * np.exp(-xhat**2) def continuous_convolve(kernels,obj): out = np.empty(obj.shape) for i in range(kernels.shape[0]): out[jj] = np.dot(obj[max(0,jj-centering):min(size,jj+n-centering)], kernels[i,max(0,centering-jj):min(n,size-jj+centering)]) return out def convolve_hermites(f_in,coeffs,center_kw,sigma,sigma_range,spacing): x = np.arange(-sigma_range * max(sigma),sigma_range * max(sigma),step=spacing) if center_kw == 'centered': centering = int(x.shape[0]/2) elif center_kw == 'right': centering = 0 elif center_kw == 'left': centering = x.shape[0]-1 else: print('setting lsf centering to middle') centering = int(x.shape[0]/2) f_out = np.empty(f_in.shape) size = f_in.shape[0] n = x.shape[0] for jj in range(f_out.shape[0]): kernel = hermitegaussian(coeffs[jj,:],x,sigma[jj]) # L1 normalize the kernel so the total flux is conserved kernel /= np.sum(kernel) f_out[jj] = np.dot(f_in[max(0,jj-centering):min(size,jj+n-centering)]\ ,kernel[max(0,centering-jj):min(n,size-jj+centering)]) return f_out
[ "numpy.exp", "numpy.sum", "numpy.polynomial.hermite.Hermite", "numpy.empty" ]
[((90, 127), 'numpy.polynomial.hermite.Hermite', 'np.polynomial.hermite.Hermite', (['coeffs'], {}), '(coeffs)\n', (119, 127), True, 'import numpy as np\n'), ((219, 238), 'numpy.empty', 'np.empty', (['obj.shape'], {}), '(obj.shape)\n', (227, 238), True, 'import numpy as np\n'), ((878, 898), 'numpy.empty', 'np.empty', (['f_in.shape'], {}), '(f_in.shape)\n', (886, 898), True, 'import numpy as np\n'), ((153, 171), 'numpy.exp', 'np.exp', (['(-xhat ** 2)'], {}), '(-xhat ** 2)\n', (159, 171), True, 'import numpy as np\n'), ((1126, 1140), 'numpy.sum', 'np.sum', (['kernel'], {}), '(kernel)\n', (1132, 1140), True, 'import numpy as np\n')]
from torch import nn def init_weight(weight, init, init_range, init_std): if init == "uniform": nn.init.uniform_(weight, -init_range, init_range) elif init == "normal": nn.init.normal_(weight, 0.0, init_std) def init_bias(bias): nn.init.constant_(bias, 0.0) def weights_init(m, init, init_range, init_std, proj_init_std): classname = m.__class__.__name__ if classname.find("Linear") != -1: if hasattr(m, "weight") and m.weight is not None: init_weight(m.weight, init, init_range, init_std) if hasattr(m, "bias") and m.bias is not None: init_bias(m.bias) elif classname.find("Embedding") != -1: if hasattr(m, "weight"): init_weight(m.weight, init, init_range, init_std) elif classname.find("LayerNorm") != -1: if hasattr(m, "weight"): nn.init.normal_(m.weight, 1.0, init_std) if hasattr(m, "bias") and m.bias is not None: init_bias(m.bias) else: if hasattr(m, "r_emb"): init_weight(m.r_emb, init, init_range, init_std) if hasattr(m, "r_w_bias"): init_weight(m.r_w_bias, init, init_range, init_std) if hasattr(m, "r_r_bias"): init_weight(m.r_r_bias, init, init_range, init_std) if hasattr(m, "r_bias"): init_bias(m.r_bias)
[ "torch.nn.init.normal_", "torch.nn.init.uniform_", "torch.nn.init.constant_" ]
[((261, 289), 'torch.nn.init.constant_', 'nn.init.constant_', (['bias', '(0.0)'], {}), '(bias, 0.0)\n', (278, 289), False, 'from torch import nn\n'), ((110, 159), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['weight', '(-init_range)', 'init_range'], {}), '(weight, -init_range, init_range)\n', (126, 159), False, 'from torch import nn\n'), ((195, 233), 'torch.nn.init.normal_', 'nn.init.normal_', (['weight', '(0.0)', 'init_std'], {}), '(weight, 0.0, init_std)\n', (210, 233), False, 'from torch import nn\n'), ((864, 904), 'torch.nn.init.normal_', 'nn.init.normal_', (['m.weight', '(1.0)', 'init_std'], {}), '(m.weight, 1.0, init_std)\n', (879, 904), False, 'from torch import nn\n')]
import warnings from collections import OrderedDict from pathlib import Path import numpy as np import pandas as pd import torch from tqdm import tqdm import librosa import model_utils import utils def long_clip_to_images(y, sample_rate, composer): len_y = len(y) start = 0 end = sample_rate * 5 images = [] while len_y > start: y_batch = y[start:end].astype(np.float32) if len(y_batch) != (sample_rate * 5): break start = end end = end + sample_rate * 5 image = composer(y_batch) images.append(image) return images def proba_to_label_string(proba, threshold): events = proba >= threshold all_events = set(np.argwhere(events)[:, 1]) labels = list(all_events) if len(labels) == 0: label_string = "nocall" else: labels_str_list = list(map(lambda x: utils.INV_BIRD_CODE[x], labels)) label_string = " ".join(labels_str_list) # print(label_string) return label_string def prediction_for_clip( test_df: pd.DataFrame, clip: np.ndarray, ds_class, sample_rate, model, composer=None, threshold=0.5, ): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) model.eval() prediction_dict = {} for idx in tqdm(range(len(test_df))): record = test_df.loc[idx, :] # print(record) row_id = record.row_id site = record.site if site in {"site_1", "site_2"}: end_seconds = int(record.seconds) start_seconds = int(end_seconds - 5) start_index = sample_rate * start_seconds end_index = sample_rate * end_seconds y = clip[start_index:end_index].astype(np.float32) image = composer(y) image = image[np.newaxis, :, :, :] image = torch.Tensor(image) image = image.to(device) with torch.no_grad(): prediction = torch.sigmoid(model(image)) proba = prediction.detach().cpu().numpy() else: # to avoid prediction on large batch y = clip.astype(np.float32) images = long_clip_to_images(y, sample_rate, composer) image = np.asarray(images) image = torch.Tensor(image) image = image.to(device) image = image.squeeze(0) batch_size = 16 whole_size = image.size(0) if whole_size % batch_size == 0: n_iter = whole_size // batch_size else: n_iter = whole_size // batch_size + 1 # all_events = set() proba = np.zeros([0, len(utils.BIRD_CODE)]) for batch_i in range(n_iter): batch = image[batch_i * batch_size : (batch_i + 1) * batch_size] if batch.ndim == 3: batch = batch.unsqueeze(0) batch = batch.to(device) with torch.no_grad(): prediction = torch.sigmoid(model(batch)) _proba = prediction.detach().cpu().numpy() # print(proba.shape) proba = np.concatenate([proba, _proba]) # label_string = proba_to_label_string(proba, threshold) # prediction_dict[row_id] = label_string prediction_dict[row_id] = proba return prediction_dict def prediction( test_df: pd.DataFrame, test_audio: Path, ds_class, model_list, composer=None, sample_rate=32000, threshold=0.5, denoise=False, ): unique_audio_id = test_df.audio_id.unique() warnings.filterwarnings("ignore") # ================================ all_prediction_dict = OrderedDict() print(model_list) for audio_id in unique_audio_id: clip, _ = librosa.load( test_audio / (audio_id + ".mp3"), sr=sample_rate, mono=True, res_type="kaiser_fast", ) if denoise: clip = utils.noise_reduce( clip, rate=sample_rate, threshold=0.25, verbose=True ) test_df_for_audio_id = test_df.query(f"audio_id == '{audio_id}'").reset_index( drop=True ) agg_dict = OrderedDict() for model_config in model_list: # print(model_config) model = model_utils.load_pytorch_model(**model_config) prediction_dict = prediction_for_clip( test_df_for_audio_id, clip=clip, ds_class=ds_class, sample_rate=sample_rate, model=model, composer=composer, threshold=threshold, ) # aggregate model prediction for key in prediction_dict.keys(): if key in agg_dict: agg_dict[key] += prediction_dict[key] else: agg_dict[key] = prediction_dict[key] all_prediction_dict.update(agg_dict) # print(all_prediction_dict) # proba to label string for k, v in all_prediction_dict.items(): v /= len(model_list) all_prediction_dict[k] = proba_to_label_string(v, threshold) print(all_prediction_dict) row_id = list(all_prediction_dict.keys()) birds = list(all_prediction_dict.values()) prediction_df = pd.DataFrame({"row_id": row_id, "birds": birds}) return prediction_df
[ "collections.OrderedDict", "model_utils.load_pytorch_model", "utils.noise_reduce", "torch.Tensor", "numpy.asarray", "numpy.argwhere", "torch.cuda.is_available", "numpy.concatenate", "pandas.DataFrame", "torch.no_grad", "warnings.filterwarnings", "librosa.load" ]
[((3641, 3674), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (3664, 3674), False, 'import warnings\n'), ((3740, 3753), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3751, 3753), False, 'from collections import OrderedDict\n'), ((5386, 5434), 'pandas.DataFrame', 'pd.DataFrame', (["{'row_id': row_id, 'birds': birds}"], {}), "({'row_id': row_id, 'birds': birds})\n", (5398, 5434), True, 'import pandas as pd\n'), ((3831, 3932), 'librosa.load', 'librosa.load', (["(test_audio / (audio_id + '.mp3'))"], {'sr': 'sample_rate', 'mono': '(True)', 'res_type': '"""kaiser_fast"""'}), "(test_audio / (audio_id + '.mp3'), sr=sample_rate, mono=True,\n res_type='kaiser_fast')\n", (3843, 3932), False, 'import librosa\n'), ((4269, 4282), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4280, 4282), False, 'from collections import OrderedDict\n'), ((706, 725), 'numpy.argwhere', 'np.argwhere', (['events'], {}), '(events)\n', (717, 725), True, 'import numpy as np\n'), ((1203, 1228), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1226, 1228), False, 'import torch\n'), ((1870, 1889), 'torch.Tensor', 'torch.Tensor', (['image'], {}), '(image)\n', (1882, 1889), False, 'import torch\n'), ((2267, 2285), 'numpy.asarray', 'np.asarray', (['images'], {}), '(images)\n', (2277, 2285), True, 'import numpy as np\n'), ((2306, 2325), 'torch.Tensor', 'torch.Tensor', (['image'], {}), '(image)\n', (2318, 2325), False, 'import torch\n'), ((4027, 4099), 'utils.noise_reduce', 'utils.noise_reduce', (['clip'], {'rate': 'sample_rate', 'threshold': '(0.25)', 'verbose': '(True)'}), '(clip, rate=sample_rate, threshold=0.25, verbose=True)\n', (4045, 4099), False, 'import utils\n'), ((4377, 4423), 'model_utils.load_pytorch_model', 'model_utils.load_pytorch_model', ([], {}), '(**model_config)\n', (4407, 4423), False, 'import model_utils\n'), ((1944, 1959), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1957, 1959), False, 'import torch\n'), ((3195, 3226), 'numpy.concatenate', 'np.concatenate', (['[proba, _proba]'], {}), '([proba, _proba])\n', (3209, 3226), True, 'import numpy as np\n'), ((2993, 3008), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3006, 3008), False, 'import torch\n')]
#!/usr/bin/env python # # # Train TuneNet on position-position bouncing ball data, which is very similar to the dataset of Ajay et al 2018. import matplotlib.pyplot as plt import numpy as np import torch import torch.utils import torch.utils import torch.utils.data import torch.utils.data from tune.utils import get_torch_device, create_tensorboard_writer device = get_torch_device() writer = create_tensorboard_writer() TIME_LENGTH = 400 SERIES_COUNT = 2 INPUT_DIM = TIME_LENGTH OUT_DIM = 1 BATCH_SIZE = 50 ax = None loss_fn = torch.nn.MSELoss() def train(epoch, model, sim, data_loader, optimizer, train_eval_iterations, should_eval=False, display_graphs=False, incremental=True): train_loss = 0 batch_idx = 0 for (zeta_batch, s_batch, _) in data_loader: zeta_batch = zeta_batch.float().to(device) s_batch = s_batch.float().to(device).permute(0, 2, 1) input_i = torch.tensor( np.reshape(s_batch[:, :, :SERIES_COUNT].cpu(), ([-1, TIME_LENGTH * SERIES_COUNT]), order="F")).to(device) input_i.requires_grad = True # TODO: the naming on delta_zeta_batch is misleading. If the network is not incremental, this is # not delta_zeta, but just zeta. if incremental: delta_zeta_batch = zeta_batch[:, 1].sub(zeta_batch[:, 0]) else: delta_zeta_batch = zeta_batch[:, 1] delta_zeta_hat = model(input_i).squeeze() delta_zeta = delta_zeta_batch[:, 0].squeeze() optimizer.zero_grad() loss = loss_fn(delta_zeta_hat, delta_zeta) train_loss += loss.item() loss.backward() optimizer.step() batch_idx += 1 err_s = None err_zeta = None print('====> Epoch: {} Average loss: {}'.format( epoch, train_loss / len(data_loader.dataset))) if should_eval: err_zeta, err_s, _, _ = test(epoch, model, sim, data_loader, train_eval_iterations, display_graphs, test_type="train", incremental=incremental) return err_zeta, err_s def test(epoch, model, sim, data_loader, tuning_iterations=1, display_graphs=False, test_type="test", incremental=True): """ Perform tests over a dataset to calculate the error in parameter and simulated state :param epoch: the epoch at evaluation time (used for tensorboard logging :param model: the model to use for evaluation :param tuning_iterations: number of tuning iterations to perform :param display_graphs: if True, display graphs after tuning showing some examples :param data_loader: the ground truth data to test over :param test_type: a string describing why this test is run. The tests can be run during training, which can make printouts confusing, so this string is used to disambiguate. :param incremental: if True, then each iteration will add to the starting value (the model estimates the difference) rather than simply setting the value (the model estimates the value). :return: """ print("Testing over " + test_type + "...") dataset_size = len(data_loader.dataset) print('dataset size is ' + str(dataset_size)) s = torch.zeros((dataset_size, TIME_LENGTH, 2)).to(device) v = torch.zeros((dataset_size, TIME_LENGTH, 2)).to(device) s_hat = torch.zeros((dataset_size, TIME_LENGTH)).to(device) v_hat = torch.zeros((dataset_size, TIME_LENGTH)).to(device) zeta_list = torch.zeros((dataset_size, 1)).to(device) zeta_hat_history_list = torch.zeros((dataset_size, tuning_iterations + 1)).to(device) # generate predictions with torch.no_grad(): # count = 0 for batch_idx, batch_data in enumerate(data_loader): zeta_batch = batch_data[0] s_batch = batch_data[1] if len(batch_data) > 2: v_batch = batch_data[2] for idx_in_batch in range(zeta_batch.shape[0]): # print(idx_in_batch) idx = batch_idx * BATCH_SIZE + idx_in_batch # print(idx) # pull out the first datapoint from the batch. zeta_i = zeta_batch[idx_in_batch].float() s[idx] = s_batch.float().to(device).permute(0, 2, 1)[idx_in_batch] if len(batch_data) > 2: v[idx] = v_batch.float().to(device).permute(0, 2, 1)[idx_in_batch] # extract relevant physics information from datapoint. # zeta_i is a vstack. Row 1 is the source sim, row 2 is the target sim # each row is a list of all the physics params, such as (restitution, drop_height). # print(zeta_i) zeta_list[idx] = zeta_i[1, 0] zeta_hat_history_list[idx, :], s_hat[idx, :], v_hat[idx, :] = \ tune_iter(model, sim, s, zeta_i, idx, tuning_iterations, display_graphs, incremental=incremental) # print("zeta_list evolution: " + str(zeta_hat_history_list[idx, :])) # count += 1 # print("{} datapoints processed.".format(count)) err_s = torch.abs(s[:, :, 1] - s_hat[:, :]).cpu().numpy() # err_s_percentage = np.abs(np.divide(err_s, s[:, :, 1].cpu().numpy() + 0.0000001) * 100.) # err_v = torch.abs(v[:, :, 1] - v_hat[:, :]).cpu().numpy() # compare the last iteration of zeta_hat_history_list with zeta_list to compute the mean absolute error err_zeta = torch.abs(zeta_list - zeta_hat_history_list).cpu().numpy() last_err_zeta = err_zeta[:, -1] # writer.add_scalar('{}_mae_s'.format(test_type), np.mean(err_s, keepdims=False), epoch) writer.add_scalar('{}_mae_zeta'.format(test_type), np.mean(last_err_zeta, keepdims=False), epoch) print("mae of zeta_list: {:6.4f}".format(np.mean(last_err_zeta, keepdims=False))) print("mse of zeta_list: {:f}".format(np.mean(last_err_zeta * last_err_zeta, keepdims=False))) return np.mean(err_zeta, keepdims=False), np.mean(err_s, keepdims=False), zeta_hat_history_list, err_zeta def tune_iter(model, sim, s_start, zeta_start, idx, tuning_iterations, display_graphs, incremental): assert tuning_iterations > 0 # zeta = zeta_start.clone() s = s_start.clone() position_list = linear_velocity_list = None zeta_hat_history = torch.tensor(np.zeros([tuning_iterations + 1])) zeta_hat_history[0] = zeta_start[0, 0] # print("starting zeta value: " + str(zeta_start[0, 0])) for iters in range(tuning_iterations): input_i = torch.tensor( np.reshape(s[idx, :, :SERIES_COUNT].cpu(), ([-1, TIME_LENGTH * SERIES_COUNT]), order="F")).to(device) delta_zeta_hat = model(input_i).item() # calculate new parameters previous_zeta = zeta_hat_history[iters] if incremental: new_zeta = previous_zeta + delta_zeta_hat else: new_zeta = delta_zeta_hat new_zeta = max(0, new_zeta) if tuning_iterations == 1: # special case to speed things up: don't run the sim position_list = torch.zeros(TIME_LENGTH, 3) linear_velocity_list = torch.zeros(TIME_LENGTH, 3) zeta_hat_history[iters + 1] = new_zeta return zeta_hat_history, torch.tensor(position_list[:, 2]), torch.tensor(linear_velocity_list[:, 2]) # get new rollout obj_pos = [0, 0, zeta_start[1, 1]] _, _, position_list, _, linear_velocity_list, _, _, _, _ = sim.run(zeta=[new_zeta, obj_pos], render=False) if display_graphs: # do_display(input_i, position_list, zeta_start, new_zeta, s[idx]) pass s[idx, :, 0] = torch.tensor(position_list[:, 2]) zeta_hat_history[iters + 1] = new_zeta # print("zeta hat history: " + str(zeta_hat_history)) return zeta_hat_history, torch.tensor(position_list[:, 2]), torch.tensor(linear_velocity_list[:, 2]) def do_display(input_i, position_list, zeta_target, zeta_hat, s_i): global ax if ax is None: _, ax = plt.subplots(2, 1) ax[0].cla() ax[0].set_ylim([0, 5]) ax[1].cla() ax[1].set_ylim([0, 5]) # note: rho is the symbol for COR, but this should be changed if the semantic meaning # of the zeta parameter changes. ax[0].plot(position_list[:, 2], label="approximate run 1 (rho={:.4f})".format(zeta_hat), color=(0.0, 0.5, 0.0, 1.0), ls="dashed") ax[1].plot(input_i[0, :].detach().cpu().squeeze().numpy()) ax[0].plot(s_i[:, 0].detach().squeeze().cpu().numpy(), label="actual run 0 (rho={:.4f})".format(zeta_target[0, 0]), color=(0.0, 0.0, 0.0)) ax[0].plot(s_i[:, 1].detach().squeeze().cpu().numpy(), label="actual run 1 (rho={:.4f})".format(zeta_target[1, 0]), color=(0.0, 0.5, 0.0)) ax[0].legend() plt.pause(1e-6)
[ "numpy.mean", "torch.abs", "tune.utils.get_torch_device", "tune.utils.create_tensorboard_writer", "torch.nn.MSELoss", "numpy.zeros", "torch.tensor", "torch.zeros", "matplotlib.pyplot.pause", "torch.no_grad", "matplotlib.pyplot.subplots" ]
[((370, 388), 'tune.utils.get_torch_device', 'get_torch_device', ([], {}), '()\n', (386, 388), False, 'from tune.utils import get_torch_device, create_tensorboard_writer\n'), ((398, 425), 'tune.utils.create_tensorboard_writer', 'create_tensorboard_writer', ([], {}), '()\n', (423, 425), False, 'from tune.utils import get_torch_device, create_tensorboard_writer\n'), ((535, 553), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (551, 553), False, 'import torch\n'), ((9169, 9185), 'matplotlib.pyplot.pause', 'plt.pause', (['(1e-06)'], {}), '(1e-06)\n', (9178, 9185), True, 'import matplotlib.pyplot as plt\n'), ((3946, 3961), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3959, 3961), False, 'import torch\n'), ((6042, 6080), 'numpy.mean', 'np.mean', (['last_err_zeta'], {'keepdims': '(False)'}), '(last_err_zeta, keepdims=False)\n', (6049, 6080), True, 'import numpy as np\n'), ((6286, 6319), 'numpy.mean', 'np.mean', (['err_zeta'], {'keepdims': '(False)'}), '(err_zeta, keepdims=False)\n', (6293, 6319), True, 'import numpy as np\n'), ((6321, 6351), 'numpy.mean', 'np.mean', (['err_s'], {'keepdims': '(False)'}), '(err_s, keepdims=False)\n', (6328, 6351), True, 'import numpy as np\n'), ((6675, 6708), 'numpy.zeros', 'np.zeros', (['[tuning_iterations + 1]'], {}), '([tuning_iterations + 1])\n', (6683, 6708), True, 'import numpy as np\n'), ((8019, 8052), 'torch.tensor', 'torch.tensor', (['position_list[:, 2]'], {}), '(position_list[:, 2])\n', (8031, 8052), False, 'import torch\n'), ((8188, 8221), 'torch.tensor', 'torch.tensor', (['position_list[:, 2]'], {}), '(position_list[:, 2])\n', (8200, 8221), False, 'import torch\n'), ((8223, 8263), 'torch.tensor', 'torch.tensor', (['linear_velocity_list[:, 2]'], {}), '(linear_velocity_list[:, 2])\n', (8235, 8263), False, 'import torch\n'), ((8383, 8401), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (8395, 8401), True, 'import matplotlib.pyplot as plt\n'), ((3514, 3557), 'torch.zeros', 'torch.zeros', (['(dataset_size, TIME_LENGTH, 2)'], {}), '((dataset_size, TIME_LENGTH, 2))\n', (3525, 3557), False, 'import torch\n'), ((3577, 3620), 'torch.zeros', 'torch.zeros', (['(dataset_size, TIME_LENGTH, 2)'], {}), '((dataset_size, TIME_LENGTH, 2))\n', (3588, 3620), False, 'import torch\n'), ((3644, 3684), 'torch.zeros', 'torch.zeros', (['(dataset_size, TIME_LENGTH)'], {}), '((dataset_size, TIME_LENGTH))\n', (3655, 3684), False, 'import torch\n'), ((3708, 3748), 'torch.zeros', 'torch.zeros', (['(dataset_size, TIME_LENGTH)'], {}), '((dataset_size, TIME_LENGTH))\n', (3719, 3748), False, 'import torch\n'), ((3777, 3807), 'torch.zeros', 'torch.zeros', (['(dataset_size, 1)'], {}), '((dataset_size, 1))\n', (3788, 3807), False, 'import torch\n'), ((3847, 3897), 'torch.zeros', 'torch.zeros', (['(dataset_size, tuning_iterations + 1)'], {}), '((dataset_size, tuning_iterations + 1))\n', (3858, 3897), False, 'import torch\n'), ((6134, 6172), 'numpy.mean', 'np.mean', (['last_err_zeta'], {'keepdims': '(False)'}), '(last_err_zeta, keepdims=False)\n', (6141, 6172), True, 'import numpy as np\n'), ((6217, 6271), 'numpy.mean', 'np.mean', (['(last_err_zeta * last_err_zeta)'], {'keepdims': '(False)'}), '(last_err_zeta * last_err_zeta, keepdims=False)\n', (6224, 6271), True, 'import numpy as np\n'), ((7432, 7459), 'torch.zeros', 'torch.zeros', (['TIME_LENGTH', '(3)'], {}), '(TIME_LENGTH, 3)\n', (7443, 7459), False, 'import torch\n'), ((7495, 7522), 'torch.zeros', 'torch.zeros', (['TIME_LENGTH', '(3)'], {}), '(TIME_LENGTH, 3)\n', (7506, 7522), False, 'import torch\n'), ((7611, 7644), 'torch.tensor', 'torch.tensor', (['position_list[:, 2]'], {}), '(position_list[:, 2])\n', (7623, 7644), False, 'import torch\n'), ((7646, 7686), 'torch.tensor', 'torch.tensor', (['linear_velocity_list[:, 2]'], {}), '(linear_velocity_list[:, 2])\n', (7658, 7686), False, 'import torch\n'), ((5466, 5501), 'torch.abs', 'torch.abs', (['(s[:, :, 1] - s_hat[:, :])'], {}), '(s[:, :, 1] - s_hat[:, :])\n', (5475, 5501), False, 'import torch\n'), ((5799, 5843), 'torch.abs', 'torch.abs', (['(zeta_list - zeta_hat_history_list)'], {}), '(zeta_list - zeta_hat_history_list)\n', (5808, 5843), False, 'import torch\n')]
# _ __ # | |/ /___ ___ _ __ ___ _ _ ® # | ' </ -_) -_) '_ \/ -_) '_| # |_|\_\___\___| .__/\___|_| # |_| # # <NAME> # Copyright 2015 Keeper Security Inc. # Contact: <EMAIL> # import yubico def get_response(challenge): try: YK = yubico.find_yubikey() response = YK.challenge_response(challenge.encode(), slot=2) except yubico.yubico_exception.YubicoError as inst: print("ERROR: %s" % inst.reason) return '' # Workaround for http://bugs.python.org/issue24596 del YK hexresponse = yubico.yubico_util.hexdump(response, length=20).strip('0000') formattedresponse = ''.join(hexresponse.split()) return formattedresponse
[ "yubico.find_yubikey", "yubico.yubico_util.hexdump" ]
[((272, 293), 'yubico.find_yubikey', 'yubico.find_yubikey', ([], {}), '()\n', (291, 293), False, 'import yubico\n'), ((566, 613), 'yubico.yubico_util.hexdump', 'yubico.yubico_util.hexdump', (['response'], {'length': '(20)'}), '(response, length=20)\n', (592, 613), False, 'import yubico\n')]
#!/usr/bin/python3 ''' Abstract: This is a program to show the data with different true and prediction Usage: plot_sed.py [main_name] [true label] [pred label] Example: plot_sed.py MaxLoss15 1 2 Editor: Jacob975 ################################## # Python3 # # This code is made in python3 # ################################## 20180412 #################################### update log 20180412 version alpha 1: 1. The code work ''' import numpy as np import time import load_lib import collections from sys import argv from glob import glob import matplotlib.pyplot as plt def get_sed(detected_occurance, n, data, tracer): # initialize variables normed_by_band = [dict() for i in range(8)] for key in detected_occurance: if detected_occurance[key] >= n: selected_data = data[np.where(tracer == key)] ind_of_peak = np.argmax(selected_data) if ind_of_peak >= 8: continue else: normed_by_band[ind_of_peak][key] = selected_data return normed_by_band #-------------------------------------------- # main code if __name__ == "__main__": VERBOSE = 0 # measure times start_time = time.time() #---------------------------------------- # initialize variables and constants data = None tracer = None cls_pred = None cls_true = None collected_tracer_in_confusion_matrix = np.array([]) collected_sed_in_confusion_matrix = np.array([]) normed_by_band = None n = 5 true_ = pred_ = ["star", "gala", "yso"] #---------------------------------------- # load argv if len(argv) != 4: print ("Error!\nUsage: plot_sed.py [main_name] [true label] [pred label]") exit() main_name = argv[1] true_label = int(argv[2]) pred_label = int(argv[3]) #---------------------------------------- data_list = glob("AI*test_on*") for directory in data_list: print ("#################################") print ("start to loading data saved in {0}".format(directory)) # load tracer failure, data, tracer = load_lib.load_arrangement(main_name, directory) if not failure: print ("load data and tracer success") # load cls_pred failure, cls_pred = load_lib.load_cls_pred(main_name, directory) if not failure: print ("load cls_pred success") # load cls_true failure, cls_true = load_lib.load_cls_true(main_name, directory) if not failure: print ("load cls_true success") # confusion matrix print ("### confusion matrix ###") failure, cm = load_lib.confusion_matrix(cls_true, cls_pred) if not failure: print ("confusion matrix success") print (cm) #----------------------------------- star_length = len(cls_true[cls_true == 0]) print ("number of stars: {0}".format(len(cls_true[cls_true == 0]))) gala_length = len(cls_true[cls_true == 1]) print ("number of galaxies: {0}".format(len(cls_true[cls_true == 1]))) yso_length = len(cls_true[cls_true == 2]) print ("number of YSOs: {0}".format(len(cls_true[cls_true == 2]))) tracer_in_confusion_matrix = tracer.test[(cls_true == true_label) &(cls_pred == pred_label)] collected_tracer_in_confusion_matrix = np.append(collected_tracer_in_confusion_matrix, tracer_in_confusion_matrix) print ("number of gala to yso: {0}".format(len(tracer_in_confusion_matrix))) # save tracer_in_confusion_matrix np.savetxt("{0}/{1}_tracer_true_{2}_pred_{3}.txt".format(directory, main_name, true_[true_label], pred_[pred_label]), tracer_in_confusion_matrix) # save collected_tracer_in_confusion_matrix np.savetxt("all_tracer_true_{0}_pred_{1}.txt".format(true_[true_label], pred_[pred_label]), collected_tracer_in_confusion_matrix) # sort object by band print("detect the occurance") detected_occurance = collections.Counter(collected_tracer_in_confusion_matrix) print("select by band") normed_by_band = get_sed(detected_occurance, n, data.test.images, tracer.test) # plot the sed band by band for ind, peak_at in enumerate(normed_by_band): if len(peak_at) == 0: continue result_plt = plt.figure("sed of true: {0}, pred: {1}, peak at {2} band, {3} data".format(true_[true_label], pred_[pred_label], ind+1, len(peak_at))) plt.title("sed of true: {0}, pred: {1}, peak at {2} band, {3} data".format(true_[true_label], pred_[pred_label], ind+1, len(peak_at))) plt.xlabel("signal/error") plt.ylabel("normalized flux") for key, value in peak_at.items(): plt.plot(range(1, 17), value[0]) result_plt.savefig("sed_true_{0}_pred_{1}_peak_at_{2}_band_{3}_data.png".format(true_[true_label], pred_[pred_label], ind+1, len(peak_at))) #---------------------------------------- # measuring time elapsed_time = time.time() - start_time print ("Exiting Main Program, spending ", elapsed_time, "seconds.")
[ "load_lib.confusion_matrix", "load_lib.load_cls_true", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.where", "numpy.argmax", "collections.Counter", "numpy.array", "numpy.append", "load_lib.load_cls_pred", "load_lib.load_arrangement", "time.time", "glob.glob" ]
[((1239, 1250), 'time.time', 'time.time', ([], {}), '()\n', (1248, 1250), False, 'import time\n'), ((1455, 1467), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1463, 1467), True, 'import numpy as np\n'), ((1508, 1520), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1516, 1520), True, 'import numpy as np\n'), ((1930, 1949), 'glob.glob', 'glob', (['"""AI*test_on*"""'], {}), "('AI*test_on*')\n", (1934, 1949), False, 'from glob import glob\n'), ((4056, 4113), 'collections.Counter', 'collections.Counter', (['collected_tracer_in_confusion_matrix'], {}), '(collected_tracer_in_confusion_matrix)\n', (4075, 4113), False, 'import collections\n'), ((2159, 2206), 'load_lib.load_arrangement', 'load_lib.load_arrangement', (['main_name', 'directory'], {}), '(main_name, directory)\n', (2184, 2206), False, 'import load_lib\n'), ((2334, 2378), 'load_lib.load_cls_pred', 'load_lib.load_cls_pred', (['main_name', 'directory'], {}), '(main_name, directory)\n', (2356, 2378), False, 'import load_lib\n'), ((2499, 2543), 'load_lib.load_cls_true', 'load_lib.load_cls_true', (['main_name', 'directory'], {}), '(main_name, directory)\n', (2521, 2543), False, 'import load_lib\n'), ((2704, 2749), 'load_lib.confusion_matrix', 'load_lib.confusion_matrix', (['cls_true', 'cls_pred'], {}), '(cls_true, cls_pred)\n', (2729, 2749), False, 'import load_lib\n'), ((3415, 3490), 'numpy.append', 'np.append', (['collected_tracer_in_confusion_matrix', 'tracer_in_confusion_matrix'], {}), '(collected_tracer_in_confusion_matrix, tracer_in_confusion_matrix)\n', (3424, 3490), True, 'import numpy as np\n'), ((4667, 4693), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""signal/error"""'], {}), "('signal/error')\n", (4677, 4693), True, 'import matplotlib.pyplot as plt\n'), ((4702, 4731), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""normalized flux"""'], {}), "('normalized flux')\n", (4712, 4731), True, 'import matplotlib.pyplot as plt\n'), ((5054, 5065), 'time.time', 'time.time', ([], {}), '()\n', (5063, 5065), False, 'import time\n'), ((908, 932), 'numpy.argmax', 'np.argmax', (['selected_data'], {}), '(selected_data)\n', (917, 932), True, 'import numpy as np\n'), ((856, 879), 'numpy.where', 'np.where', (['(tracer == key)'], {}), '(tracer == key)\n', (864, 879), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ ========== """ # import standard libraries import os # import third-party libraries import numpy as np import matplotlib.pyplot as plt from colour import write_image, read_image # import my libraries import test_pattern_generator2 as tpg import transfer_functions as tf import plot_utility as pu # information __author__ = '<NAME>' __copyright__ = 'Copyright (C) 2020 - <NAME>' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = '<NAME>' __email__ = 'toru.ver.11 at-sign gmail.com' __all__ = [] def create_ramp(): x = np.linspace(0, 1, 1920).reshape((1, 1920, 1)) img = np.ones((1080, 1920, 3)) img = x * img write_image(img, "test_src.tif", bit_depth='uint16') def create_exr_ramp(min_exposure=-12, max_exposure=12): x = np.linspace(0, 1, 1920).reshape((1, 1920, 1)) y = tpg.shaper_func_log2_to_linear( x, min_exposure=min_exposure, max_exposure=max_exposure) img = np.ones((1080, 1920, 3)) * y fname = f"./img/test_src_exp_{min_exposure}_{max_exposure}.exr" write_image(img, fname, bit_depth='float32') def plot_input_drt(): # file_list = [ # ['./img/old/test_out_sdr100.tif', 'SDR 100'], # ['./img/old/test_out_hdr500.tif', 'HDR 500'], # ['./img/old/test_out_hdr1000.tif', 'HDR 1000'], # ['./img/old/test_out_hdr2000.tif', 'HDR 2000'], # ['./img/old/test_out_hdr4000.tif', 'HDR 4000'], # ['./img/old/test_out_off.tif', 'DRT OFF'] # ] # check_input_drt_test( # file_list=file_list, graph_name="Input_DRT_Characteristics_w_SDR") # file_list = [ # ['./img/old/test_out_hdr500.tif', 'HDR 500'], # ['./img/old/test_out_hdr1000.tif', 'HDR 1000'], # ['./img/old/test_out_hdr2000.tif', 'HDR 2000'], # ['./img/old/test_out_hdr4000.tif', 'HDR 4000'], # ['./img/old/test_out_off.tif', 'DRT OFF'] # ] # check_input_drt_test( # file_list=file_list, graph_name="Input_DRT_Characteristics_wo_SDR") # file_list = [ # ['./img/old/test_out_sdr_er_100-200.tif', 'SDR ER 100/200'], # ['./img/old/test_out_hdr_er_1000-2000.tif', 'HDR ER 1000/2000'], # ['./img/old/test_out_hdr_er_1000-4000.tif', 'HDR ER 1000/4000'], # ['./img/old/test_out_hdr_er_1000-10000.tif', 'HDR ER 1000/10000'], # ['./img/old/test_out_hdr_er_4000-10000.tif', 'HDR ER 4000/10000'], # ['./img/old/test_out_off.tif', 'DRT OFF'] # ] # check_input_drt_test( # file_list=file_list, graph_name="Input_DRT_Characteristics_ER_w_SDR") file_list = [ ['./img/old/test_out_hdr_er_1000-2000.tif', 'HDR ER 1000/2000', '-.'], ['./img/old/test_out_hdr_er_1000-4000.tif', 'HDR ER 1000/4000', '--'], ['./img/old/test_out_hdr_er_1000-10000.tif', 'HDR ER 1000/10000', '-'], ['./img/old/test_out_hdr_er_4000-10000.tif', 'HDR ER 4000/10000', '-'], # ['./img/old/test_out_off.tif', 'DRT OFF'] ] check_input_drt_test( file_list=file_list, graph_name="Input_DRT_Characteristics_ER_wo_SDR") # check_input_drt_test_sdr_only() def check_input_drt_test(file_list, graph_name): create_ramp() x = np.linspace(0, 1, 1920) x_luminance = tf.eotf_to_luminance(x, tf.ST2084) fig, ax1 = pu.plot_1_graph( fontsize=20, figsize=(10, 8), graph_title="DaVinci17 Input DRT Characteristics", graph_title_size=None, xlabel="Input Luminance [cd/m2]", ylabel="Output Luminance [cd/m2]", axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009, 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True) pu.log_scale_settings(ax1, grid_alpha=0.5, bg_color="#E0E0E0") for idx in range(len(file_list))[::-1]: img = read_image(file_list[idx][0])[0, :, 0] label = file_list[idx][1] ls = file_list[idx][2] y_luminance = tf.eotf_to_luminance(img, tf.ST2084) ax1.plot(x_luminance, y_luminance, ls, label=label) plt.legend(loc='upper left') fname_full = f"./img/{graph_name}.png" plt.savefig(fname_full, bbox_inches='tight', pad_inches=0.1) # plt.show() plt.close(fig) def check_input_drt_test_sdr_only(): create_ramp() x = np.linspace(0, 1, 1920) fig, ax1 = pu.plot_1_graph( fontsize=20, figsize=(10, 8), graph_title="DaVinci17 Input DRT Characteristics", graph_title_size=None, xlabel="Input Luminance [cd/m2]", ylabel="Output Luminance [cd/m2]", axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009, 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True) pu.log_scale_settings(ax1, grid_alpha=0.5, bg_color="#E0E0E0") # img = read_image("./img/test_out_sdr100_on_gm24.tif")[0, :, 0] # label = "DRT OFF(ST2084 to Gamma2.4 (.tif))" # x_luminance = tf.eotf_to_luminance(x, tf.ST2084) # y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) # ax1.plot(x_luminance, y_luminance, label=label) # img = read_image("./img/test_out_sdr100_on_gm24_203nits.tif")[0, :, 0] # label = "DRT OFF(ST2084 to Gamma2.4 (.tif) 203nits)" # x_luminance = tf.eotf_to_luminance(x, tf.ST2084) # y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) # ax1.plot(x_luminance, y_luminance, label=label) img = read_image("./img/old/test_out_sdr100_on_gm24.tif")[0, :, 0] label = 'SDR 100 (Output color space is Gamma2.4)' x_luminance = tf.eotf_to_luminance(x, tf.ST2084) y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) ax1.plot(x_luminance, y_luminance, label=label) # img = read_image("./img/test_out_exp_-12_12_sdr_drt-off_gm24.tif")[0, :, 0] # label = "DRT OFF(Gamma2.4 to Gamma2.4 (.tif))" # x_luminance = tf.eotf_to_luminance(x, tf.GAMMA24) # y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) # ax1.plot(x_luminance, y_luminance, label=label) # img = read_image("./img/test_out_exp_-12_12_sdr_drt-off.tif")[0, :, 0] # label = "DRT OFF(Linear to Gamma2.4 (.exr))" # y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) # x = np.linspace(0, 1, 1920) # x_luminance = tpg.shaper_func_log2_to_linear( # x, min_exposure=-12, max_exposure=12) # ax1.plot( # x_luminance * 100, y_luminance, '--', color=pu.SKY, label=label) plt.legend(loc='upper left') fname_full = "./img/input_drt_sdr_only.png" plt.savefig(fname_full, bbox_inches='tight', pad_inches=0.1) # plt.show() plt.close(fig) def check_100nits_code_value_on_st2084(): code_value = tf.oetf_from_luminance(100, tf.ST2084) print(code_value) print(code_value * 1023) def plot_forum_fig1(): x = np.linspace(0, 1, 1920) fig, ax1 = pu.plot_1_graph( fontsize=20, figsize=(10, 8), graph_title="HDR to SDR conversion", graph_title_size=None, xlabel="Input Luminance [cd/m2]", ylabel="Output Luminance [cd/m2]", axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009, 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True) pu.log_scale_settings(ax1, grid_alpha=0.5, bg_color="#E0E0E0") img = read_image("./img/dv17_fig1_sdr_out_st2084.tif")[0, :, 0] label = "(a) src: ST2084(.tif)" x_luminance = tf.eotf_to_luminance(x, tf.ST2084) y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) ax1.plot(x_luminance, y_luminance, color=pu.BLUE, label=label) # img = read_image("./img/dv17_fig1_203_sdr_out_st2084.tif")[0, :, 0] # label = "(b) src: ST2084(.tif), ref-white: 203nits" # x_luminance = tf.eotf_to_luminance(x, tf.ST2084) # y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) # ax1.plot(x_luminance, y_luminance, label=label) img = read_image("./img/dv17_fig1_sdr_out_linear.tif")[0, :, 0] label = "(b) src: Linear(.exr), This is the expected result." y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) x = np.linspace(0, 1, 1920) x_luminance = tpg.shaper_func_log2_to_linear( x, min_exposure=-12, max_exposure=12) ax1.plot( x_luminance * 100, y_luminance, '--', color=pu.RED, label=label) # img = read_image("./img/dv17_fig1_203_sdr_out_linear.tif")[0, :, 0] # label = "src=Linear(.exr), ref-white=203nits" # y_luminance = tf.eotf_to_luminance(img, tf.GAMMA24) # x = np.linspace(0, 1, 1920) # x_luminance = tpg.shaper_func_log2_to_linear( # x, min_exposure=-12, max_exposure=12) # ax1.plot( # x_luminance * 100, y_luminance, label=label) plt.legend(loc='upper left') fname_full = "./img/fig1.png" plt.savefig(fname_full, bbox_inches='tight', pad_inches=0.1) # plt.show() plt.close(fig) def plot_output_drt(): # file_list = [ # # ['./img/Output_DRT_SDR_ER_100-200.tif', 'SDR ER 100/200', '-'], # ['./img/old/Output_DRT_HDR_ER_1000-2000.tif', 'HDR ER 1000/2000', '-'], # ['./img/old/Output_DRT_HDR_ER_1000-4000.tif', 'HDR ER 1000/4000', '-'], # ['./img/old/Output_DRT_HDR_ER_1000-10000.tif', 'HDR ER 1000/10000', '-'], # ['./img/old/Output_DRT_HDR_ER_4000-10000.tif', 'HDR ER 4000/10000', '--'], # ] # check_output_drt_test( # file_list=file_list, # graph_name="DaVinci17 Output DRT ER 無印ST2084") # file_list = [ # # ['./img/Output_DRT_SDR_ER_100-200.tif', 'SDR ER 100/200', '-'], # ['./img/Output_DRT_HDR_ER_1000-2000.tif', 'HDR ER 1000/2000', '-'], # ['./img/Output_DRT_HDR_ER_1000-4000.tif', 'HDR ER 1000/4000', '-'], # ['./img/Output_DRT_HDR_ER_1000-10000.tif', 'HDR ER 1000/10000', '-'], # ['./img/Output_DRT_HDR_ER_4000-10000.tif', 'HDR ER 4000/10000', '--'], # ] # check_output_drt_test( # file_list=file_list, # graph_name="DaVinci17 Output DRT Characteristics ER") # file_list = [ # # ['./img/Output_DRT_SDR_100.tif', 'SDR 100', '-'], # ['./img/old/Output_DRT_HDR_500.tif', 'HDR 500', '-'], # ['./img/old/Output_DRT_HDR_1000.tif', 'HDR 1000', '-'], # ['./img/old/Output_DRT_HDR_2000.tif', 'HDR 2000', '-'], # ['./img/old/Output_DRT_HDR_4000.tif', 'HDR 4000', '-'] # ] # check_output_drt_test( # file_list=file_list, # graph_name="DaVinci17 Output DRT 無印 ST2084") file_list = [ # ['./img/Output_DRT_SDR_100.tif', 'SDR 100', '-'], ['./img/Output_DRT_HDR_500.tif', 'HDR 500', '-'], ['./img/Output_DRT_HDR_1000.tif', 'HDR 1000', '-'], ['./img/Output_DRT_HDR_2000.tif', 'HDR 2000', '-'], ['./img/Output_DRT_HDR_4000.tif', 'HDR 4000', '-'], ['./img/Output_DRT_HDR_10000.tif', 'Custom (10000 nit)', '--'] ] check_output_drt_test( file_list=file_list, graph_name="DaVinci17 Output DRT Characteristics") file_list = [ ['./img/DRT_In_None_HDR1000-500.tif', 'HDR 1000, ST2084 500 nit', '-'], ['./img/DRT_In_None_HDR1000-1000.tif', 'HDR 1000, ST2084 1000 nit', '-'], ['./img/DRT_In_None_HDR1000-2000.tif', 'HDR 1000, ST2084 2000 nit', '-'], ['./img/DRT_In_None_HDR1000-4000.tif', 'HDR 1000, ST2084 4000 nit', '-'], ['./img/DRT_In_None_HDR1000-10000.tif', 'HDR 1000, ST2084 10000 nit', '-'], ] check_output_drt_test( file_list=file_list, graph_name="DaVinci17 Out DRT Characteristics_fix_HDR1000") def check_output_drt_test(file_list, graph_name): x = np.linspace(0, 1, 1920) x_luminance = tf.eotf_to_luminance(x, tf.ST2084) fig, ax1 = pu.plot_1_graph( fontsize=20, figsize=(10, 8), graph_title="DaVinci17 Output DRT Characteristics", graph_title_size=None, xlabel="Input Luminance [cd/m2]", ylabel="Output Luminance [cd/m2]", axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009, 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True) pu.log_scale_settings(ax1, grid_alpha=0.5, bg_color="#E0E0E0") for idx in range(len(file_list)): img = read_image(file_list[idx][0])[0, :, 0] label = file_list[idx][1] ls = file_list[idx][2] y_luminance = tf.eotf_to_luminance(img, tf.ST2084) ax1.plot(x_luminance, y_luminance, ls, label=label) plt.legend(loc='upper left') fname_full = f"./img/{graph_name}.png".replace(' ', "_") plt.savefig(fname_full, bbox_inches='tight', pad_inches=0.1) # plt.show() plt.close(fig) def check_output_drt_test_exr(file_list, graph_name): x = np.linspace(0, 1, 1920) x_luminance = tf.eotf_to_luminance(x, tf.ST2084) fig, ax1 = pu.plot_1_graph( fontsize=20, figsize=(10, 8), graph_title=graph_name, graph_title_size=None, xlabel="Input Luminance [cd/m2]", ylabel="Output Luminance [cd/m2]", axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=None, xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True) pu.log_scale_settings(ax1, grid_alpha=0.5, bg_color="#E0E0E0") for idx in range(len(file_list)): img = read_image(file_list[idx][0])[0, :, 0] label = file_list[idx][1] ls = file_list[idx][2] y_luminance = img * 10000 ax1.plot(x_luminance, y_luminance, ls, label=label) plt.legend(loc='upper left') fname_full = f"./img/{graph_name}.png".replace(' ', "_") plt.savefig(fname_full, bbox_inches='tight', pad_inches=0.1) # plt.show() plt.close(fig) def plot_total_drt(): file_list = [ ['./img/DRT_Total_HDR_500.tif', 'HDR 500', '-'], ['./img/DRT_Total_HDR_1000.tif', 'HDR 1000', '-'], ['./img/DRT_Total_HDR_2000.tif', 'HDR 2000', '-'], ['./img/DRT_Total_HDR_4000.tif', 'HDR 4000', '-'], ['./img/DRT_Total_HDR_10000.tif', 'Custom (10000 nit)', '-'], ] check_total_drt_test( file_list=file_list, graph_name="Input-Output_DRT_Characteristics") file_list = [ ['./img/Output_DRT_HDR1000-500.tif', 'HDR 1000, ST2084 500 nit', '-'], ['./img/Output_DRT_HDR1000-1000.tif', 'HDR 1000, ST2084 1000 nit', '-'], ['./img/Output_DRT_HDR1000-2000.tif', 'HDR 1000, ST2084 2000 nit', '-'], ['./img/Output_DRT_HDR1000-4000.tif', 'HDR 1000, ST2084 4000 nit', '-'], ['./img/Output_DRT_HDR1000-10000.tif','HDR 1000, ST2084 10000 nit', '-'], ] check_total_drt_test( file_list=file_list, graph_name="DaVinci17 In-Out DRT Characteristics_fix_HDR1000") file_list = [ ['./img/DRT_Total_HDR_ER_1000-2000.tif', 'HDR ER 1000/2000', '-'], ['./img/DRT_Total_HDR_ER_1000-4000.tif', 'HDR ER 1000/4000', '-'], ['./img/DRT_Total_HDR_ER_1000-10000.tif', 'HDR ER 1000/10000', '-'], ['./img/DRT_Total_HDR_ER_4000-10000.tif', 'HDR ER 4000/10000', '-'], ] check_total_drt_test( file_list=file_list, graph_name="Input-Output_DRT_Characteristics_ER") def check_total_drt_test(file_list, graph_name): x = np.linspace(0, 1, 1920) x_luminance = tf.eotf_to_luminance(x, tf.ST2084) fig, ax1 = pu.plot_1_graph( fontsize=20, figsize=(10, 8), graph_title="DaVinci17 Input-Output DRT Characteristics", graph_title_size=None, xlabel="Input Luminance [cd/m2]", ylabel="Output Luminance [cd/m2]", axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009, 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True) pu.log_scale_settings(ax1, grid_alpha=0.5, bg_color="#E0E0E0") for idx in range(len(file_list)): img = read_image(file_list[idx][0])[0, :, 0] label = file_list[idx][1] ls = file_list[idx][2] y_luminance = tf.eotf_to_luminance(img, tf.ST2084) ax1.plot(x_luminance, y_luminance, ls, label=label) plt.legend(loc='upper left') fname_full = f"./img/{graph_name}.png".replace(' ', "_") plt.savefig(fname_full, bbox_inches='tight', pad_inches=0.1) # plt.show() plt.close(fig) def plot_inv_drt(): file_list = [ # ['./img/Inverse_DRT_to_HDR500.tif', 'SDR to HDR 500 nit', '-'], ['./img/Inverse_DRT_to_HDR1000.tif', 'SDR to HDR 1000 nit', '-'], # ['./img/Inverse_DRT_to_HDR2000.tif', 'SDR to HDR 2000 nit', '-'], ['./img/Inverse_DRT_to_HDR4000.tif', 'SDR to HDR 4000 nit', '-'], ['./img/Inverse_DRT_to_HDR10000.tif', 'SDR to HDR 10000 nit', '-'], ] check_inv_drt_test( file_list=file_list, graph_name="Inverse_DRT_Characteristics") def check_inv_drt_test(file_list, graph_name): x = np.linspace(0, 1, 1920) x_luminance = tf.eotf_to_luminance(x, tf.GAMMA24) fig, ax1 = pu.plot_1_graph( fontsize=20, figsize=(10, 8), graph_title="DaVinci17 Inverse DRT for SDR to HDR Conversion", graph_title_size=None, xlabel="Input Luminance [cd/m2]", ylabel="Output Luminance [cd/m2]", axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009, 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True) pu.log_scale_settings(ax1, grid_alpha=0.5, bg_color="#E0E0E0") for idx in range(len(file_list))[::-1]: img = read_image(file_list[idx][0])[0, :, 0] label = file_list[idx][1] ls = file_list[idx][2] y_luminance = tf.eotf_to_luminance(img, tf.ST2084) ax1.plot(x_luminance, y_luminance, ls, label=label) plt.legend(loc='upper left') fname_full = f"./img/{graph_name}.png".replace(' ', "_") plt.savefig(fname_full, bbox_inches='tight', pad_inches=0.1) # plt.show() plt.close(fig) def conv_st2084_to_linear(): src_file = "./ST2084_vs_Linear/st2084_clip_checker_st2084.png" dst_file = "./ST2084_vs_Linear/st2084_clip_checker_linear.exr" img_st2084 = read_image(src_file) img_linear = tf.eotf(img_st2084, tf.ST2084) * 100 write_image(img_linear, dst_file) def main_func(): # create_exr_ramp() # plot_input_drt() # plot_output_drt() # check_100nits_code_value_on_st2084() # plot_forum_fig1() # plot_total_drt() # plot_inv_drt() conv_st2084_to_linear() if __name__ == '__main__': os.chdir(os.path.dirname(os.path.abspath(__file__))) main_func()
[ "matplotlib.pyplot.savefig", "numpy.ones", "colour.write_image", "test_pattern_generator2.shaper_func_log2_to_linear", "colour.read_image", "matplotlib.pyplot.legend", "transfer_functions.eotf_to_luminance", "matplotlib.pyplot.close", "plot_utility.log_scale_settings", "numpy.linspace", "os.path...
[((661, 685), 'numpy.ones', 'np.ones', (['(1080, 1920, 3)'], {}), '((1080, 1920, 3))\n', (668, 685), True, 'import numpy as np\n'), ((708, 760), 'colour.write_image', 'write_image', (['img', '"""test_src.tif"""'], {'bit_depth': '"""uint16"""'}), "(img, 'test_src.tif', bit_depth='uint16')\n", (719, 760), False, 'from colour import write_image, read_image\n'), ((881, 973), 'test_pattern_generator2.shaper_func_log2_to_linear', 'tpg.shaper_func_log2_to_linear', (['x'], {'min_exposure': 'min_exposure', 'max_exposure': 'max_exposure'}), '(x, min_exposure=min_exposure, max_exposure=\n max_exposure)\n', (911, 973), True, 'import test_pattern_generator2 as tpg\n'), ((1090, 1134), 'colour.write_image', 'write_image', (['img', 'fname'], {'bit_depth': '"""float32"""'}), "(img, fname, bit_depth='float32')\n", (1101, 1134), False, 'from colour import write_image, read_image\n'), ((3227, 3250), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (3238, 3250), True, 'import numpy as np\n'), ((3269, 3303), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['x', 'tf.ST2084'], {}), '(x, tf.ST2084)\n', (3289, 3303), True, 'import transfer_functions as tf\n'), ((3320, 3750), 'plot_utility.plot_1_graph', 'pu.plot_1_graph', ([], {'fontsize': '(20)', 'figsize': '(10, 8)', 'graph_title': '"""DaVinci17 Input DRT Characteristics"""', 'graph_title_size': 'None', 'xlabel': '"""Input Luminance [cd/m2]"""', 'ylabel': '"""Output Luminance [cd/m2]"""', 'axis_label_size': 'None', 'legend_size': '(17)', 'xlim': '[0.009, 15000]', 'ylim': '[0.009, 15000]', 'xtick': 'None', 'ytick': 'None', 'xtick_size': 'None', 'ytick_size': 'None', 'linewidth': '(3)', 'minor_xtick_num': 'None', 'minor_ytick_num': 'None', 'return_figure': '(True)'}), "(fontsize=20, figsize=(10, 8), graph_title=\n 'DaVinci17 Input DRT Characteristics', graph_title_size=None, xlabel=\n 'Input Luminance [cd/m2]', ylabel='Output Luminance [cd/m2]',\n axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009,\n 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None,\n linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True\n )\n", (3335, 3750), True, 'import plot_utility as pu\n'), ((3873, 3935), 'plot_utility.log_scale_settings', 'pu.log_scale_settings', (['ax1'], {'grid_alpha': '(0.5)', 'bg_color': '"""#E0E0E0"""'}), "(ax1, grid_alpha=0.5, bg_color='#E0E0E0')\n", (3894, 3935), True, 'import plot_utility as pu\n'), ((4223, 4251), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (4233, 4251), True, 'import matplotlib.pyplot as plt\n'), ((4299, 4359), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname_full'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)'}), "(fname_full, bbox_inches='tight', pad_inches=0.1)\n", (4310, 4359), True, 'import matplotlib.pyplot as plt\n'), ((4381, 4395), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4390, 4395), True, 'import matplotlib.pyplot as plt\n'), ((4461, 4484), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (4472, 4484), True, 'import numpy as np\n'), ((4501, 4931), 'plot_utility.plot_1_graph', 'pu.plot_1_graph', ([], {'fontsize': '(20)', 'figsize': '(10, 8)', 'graph_title': '"""DaVinci17 Input DRT Characteristics"""', 'graph_title_size': 'None', 'xlabel': '"""Input Luminance [cd/m2]"""', 'ylabel': '"""Output Luminance [cd/m2]"""', 'axis_label_size': 'None', 'legend_size': '(17)', 'xlim': '[0.009, 15000]', 'ylim': '[0.009, 15000]', 'xtick': 'None', 'ytick': 'None', 'xtick_size': 'None', 'ytick_size': 'None', 'linewidth': '(3)', 'minor_xtick_num': 'None', 'minor_ytick_num': 'None', 'return_figure': '(True)'}), "(fontsize=20, figsize=(10, 8), graph_title=\n 'DaVinci17 Input DRT Characteristics', graph_title_size=None, xlabel=\n 'Input Luminance [cd/m2]', ylabel='Output Luminance [cd/m2]',\n axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009,\n 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None,\n linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True\n )\n", (4516, 4931), True, 'import plot_utility as pu\n'), ((5054, 5116), 'plot_utility.log_scale_settings', 'pu.log_scale_settings', (['ax1'], {'grid_alpha': '(0.5)', 'bg_color': '"""#E0E0E0"""'}), "(ax1, grid_alpha=0.5, bg_color='#E0E0E0')\n", (5075, 5116), True, 'import plot_utility as pu\n'), ((5854, 5888), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['x', 'tf.ST2084'], {}), '(x, tf.ST2084)\n', (5874, 5888), True, 'import transfer_functions as tf\n'), ((5907, 5944), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['img', 'tf.GAMMA24'], {}), '(img, tf.GAMMA24)\n', (5927, 5944), True, 'import transfer_functions as tf\n'), ((6718, 6746), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (6728, 6746), True, 'import matplotlib.pyplot as plt\n'), ((6799, 6859), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname_full'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)'}), "(fname_full, bbox_inches='tight', pad_inches=0.1)\n", (6810, 6859), True, 'import matplotlib.pyplot as plt\n'), ((6881, 6895), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (6890, 6895), True, 'import matplotlib.pyplot as plt\n'), ((6957, 6995), 'transfer_functions.oetf_from_luminance', 'tf.oetf_from_luminance', (['(100)', 'tf.ST2084'], {}), '(100, tf.ST2084)\n', (6979, 6995), True, 'import transfer_functions as tf\n'), ((7080, 7103), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (7091, 7103), True, 'import numpy as np\n'), ((7120, 7536), 'plot_utility.plot_1_graph', 'pu.plot_1_graph', ([], {'fontsize': '(20)', 'figsize': '(10, 8)', 'graph_title': '"""HDR to SDR conversion"""', 'graph_title_size': 'None', 'xlabel': '"""Input Luminance [cd/m2]"""', 'ylabel': '"""Output Luminance [cd/m2]"""', 'axis_label_size': 'None', 'legend_size': '(17)', 'xlim': '[0.009, 15000]', 'ylim': '[0.009, 15000]', 'xtick': 'None', 'ytick': 'None', 'xtick_size': 'None', 'ytick_size': 'None', 'linewidth': '(3)', 'minor_xtick_num': 'None', 'minor_ytick_num': 'None', 'return_figure': '(True)'}), "(fontsize=20, figsize=(10, 8), graph_title=\n 'HDR to SDR conversion', graph_title_size=None, xlabel=\n 'Input Luminance [cd/m2]', ylabel='Output Luminance [cd/m2]',\n axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009,\n 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None,\n linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True\n )\n", (7135, 7536), True, 'import plot_utility as pu\n'), ((7659, 7721), 'plot_utility.log_scale_settings', 'pu.log_scale_settings', (['ax1'], {'grid_alpha': '(0.5)', 'bg_color': '"""#E0E0E0"""'}), "(ax1, grid_alpha=0.5, bg_color='#E0E0E0')\n", (7680, 7721), True, 'import plot_utility as pu\n'), ((7845, 7879), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['x', 'tf.ST2084'], {}), '(x, tf.ST2084)\n', (7865, 7879), True, 'import transfer_functions as tf\n'), ((7898, 7935), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['img', 'tf.GAMMA24'], {}), '(img, tf.GAMMA24)\n', (7918, 7935), True, 'import transfer_functions as tf\n'), ((8456, 8493), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['img', 'tf.GAMMA24'], {}), '(img, tf.GAMMA24)\n', (8476, 8493), True, 'import transfer_functions as tf\n'), ((8502, 8525), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (8513, 8525), True, 'import numpy as np\n'), ((8544, 8612), 'test_pattern_generator2.shaper_func_log2_to_linear', 'tpg.shaper_func_log2_to_linear', (['x'], {'min_exposure': '(-12)', 'max_exposure': '(12)'}), '(x, min_exposure=-12, max_exposure=12)\n', (8574, 8612), True, 'import test_pattern_generator2 as tpg\n'), ((9104, 9132), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (9114, 9132), True, 'import matplotlib.pyplot as plt\n'), ((9171, 9231), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname_full'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)'}), "(fname_full, bbox_inches='tight', pad_inches=0.1)\n", (9182, 9231), True, 'import matplotlib.pyplot as plt\n'), ((9253, 9267), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (9262, 9267), True, 'import matplotlib.pyplot as plt\n'), ((11988, 12011), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (11999, 12011), True, 'import numpy as np\n'), ((12030, 12064), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['x', 'tf.ST2084'], {}), '(x, tf.ST2084)\n', (12050, 12064), True, 'import transfer_functions as tf\n'), ((12081, 12512), 'plot_utility.plot_1_graph', 'pu.plot_1_graph', ([], {'fontsize': '(20)', 'figsize': '(10, 8)', 'graph_title': '"""DaVinci17 Output DRT Characteristics"""', 'graph_title_size': 'None', 'xlabel': '"""Input Luminance [cd/m2]"""', 'ylabel': '"""Output Luminance [cd/m2]"""', 'axis_label_size': 'None', 'legend_size': '(17)', 'xlim': '[0.009, 15000]', 'ylim': '[0.009, 15000]', 'xtick': 'None', 'ytick': 'None', 'xtick_size': 'None', 'ytick_size': 'None', 'linewidth': '(3)', 'minor_xtick_num': 'None', 'minor_ytick_num': 'None', 'return_figure': '(True)'}), "(fontsize=20, figsize=(10, 8), graph_title=\n 'DaVinci17 Output DRT Characteristics', graph_title_size=None, xlabel=\n 'Input Luminance [cd/m2]', ylabel='Output Luminance [cd/m2]',\n axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009,\n 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None,\n linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True\n )\n", (12096, 12512), True, 'import plot_utility as pu\n'), ((12635, 12697), 'plot_utility.log_scale_settings', 'pu.log_scale_settings', (['ax1'], {'grid_alpha': '(0.5)', 'bg_color': '"""#E0E0E0"""'}), "(ax1, grid_alpha=0.5, bg_color='#E0E0E0')\n", (12656, 12697), True, 'import plot_utility as pu\n'), ((12979, 13007), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (12989, 13007), True, 'import matplotlib.pyplot as plt\n'), ((13073, 13133), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname_full'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)'}), "(fname_full, bbox_inches='tight', pad_inches=0.1)\n", (13084, 13133), True, 'import matplotlib.pyplot as plt\n'), ((13155, 13169), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (13164, 13169), True, 'import matplotlib.pyplot as plt\n'), ((13234, 13257), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (13245, 13257), True, 'import numpy as np\n'), ((13276, 13310), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['x', 'tf.ST2084'], {}), '(x, tf.ST2084)\n', (13296, 13310), True, 'import transfer_functions as tf\n'), ((13327, 13716), 'plot_utility.plot_1_graph', 'pu.plot_1_graph', ([], {'fontsize': '(20)', 'figsize': '(10, 8)', 'graph_title': 'graph_name', 'graph_title_size': 'None', 'xlabel': '"""Input Luminance [cd/m2]"""', 'ylabel': '"""Output Luminance [cd/m2]"""', 'axis_label_size': 'None', 'legend_size': '(17)', 'xlim': '[0.009, 15000]', 'ylim': 'None', 'xtick': 'None', 'ytick': 'None', 'xtick_size': 'None', 'ytick_size': 'None', 'linewidth': '(3)', 'minor_xtick_num': 'None', 'minor_ytick_num': 'None', 'return_figure': '(True)'}), "(fontsize=20, figsize=(10, 8), graph_title=graph_name,\n graph_title_size=None, xlabel='Input Luminance [cd/m2]', ylabel=\n 'Output Luminance [cd/m2]', axis_label_size=None, legend_size=17, xlim=\n [0.009, 15000], ylim=None, xtick=None, ytick=None, xtick_size=None,\n ytick_size=None, linewidth=3, minor_xtick_num=None, minor_ytick_num=\n None, return_figure=True)\n", (13342, 13716), True, 'import plot_utility as pu\n'), ((13843, 13905), 'plot_utility.log_scale_settings', 'pu.log_scale_settings', (['ax1'], {'grid_alpha': '(0.5)', 'bg_color': '"""#E0E0E0"""'}), "(ax1, grid_alpha=0.5, bg_color='#E0E0E0')\n", (13864, 13905), True, 'import plot_utility as pu\n'), ((14162, 14190), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (14172, 14190), True, 'import matplotlib.pyplot as plt\n'), ((14256, 14316), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname_full'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)'}), "(fname_full, bbox_inches='tight', pad_inches=0.1)\n", (14267, 14316), True, 'import matplotlib.pyplot as plt\n'), ((14338, 14352), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (14347, 14352), True, 'import matplotlib.pyplot as plt\n'), ((15872, 15895), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (15883, 15895), True, 'import numpy as np\n'), ((15914, 15948), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['x', 'tf.ST2084'], {}), '(x, tf.ST2084)\n', (15934, 15948), True, 'import transfer_functions as tf\n'), ((15965, 16401), 'plot_utility.plot_1_graph', 'pu.plot_1_graph', ([], {'fontsize': '(20)', 'figsize': '(10, 8)', 'graph_title': '"""DaVinci17 Input-Output DRT Characteristics"""', 'graph_title_size': 'None', 'xlabel': '"""Input Luminance [cd/m2]"""', 'ylabel': '"""Output Luminance [cd/m2]"""', 'axis_label_size': 'None', 'legend_size': '(17)', 'xlim': '[0.009, 15000]', 'ylim': '[0.009, 15000]', 'xtick': 'None', 'ytick': 'None', 'xtick_size': 'None', 'ytick_size': 'None', 'linewidth': '(3)', 'minor_xtick_num': 'None', 'minor_ytick_num': 'None', 'return_figure': '(True)'}), "(fontsize=20, figsize=(10, 8), graph_title=\n 'DaVinci17 Input-Output DRT Characteristics', graph_title_size=None,\n xlabel='Input Luminance [cd/m2]', ylabel='Output Luminance [cd/m2]',\n axis_label_size=None, legend_size=17, xlim=[0.009, 15000], ylim=[0.009,\n 15000], xtick=None, ytick=None, xtick_size=None, ytick_size=None,\n linewidth=3, minor_xtick_num=None, minor_ytick_num=None, return_figure=True\n )\n", (15980, 16401), True, 'import plot_utility as pu\n'), ((16525, 16587), 'plot_utility.log_scale_settings', 'pu.log_scale_settings', (['ax1'], {'grid_alpha': '(0.5)', 'bg_color': '"""#E0E0E0"""'}), "(ax1, grid_alpha=0.5, bg_color='#E0E0E0')\n", (16546, 16587), True, 'import plot_utility as pu\n'), ((16869, 16897), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (16879, 16897), True, 'import matplotlib.pyplot as plt\n'), ((16963, 17023), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname_full'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)'}), "(fname_full, bbox_inches='tight', pad_inches=0.1)\n", (16974, 17023), True, 'import matplotlib.pyplot as plt\n'), ((17045, 17059), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (17054, 17059), True, 'import matplotlib.pyplot as plt\n'), ((17640, 17663), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (17651, 17663), True, 'import numpy as np\n'), ((17682, 17717), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['x', 'tf.GAMMA24'], {}), '(x, tf.GAMMA24)\n', (17702, 17717), True, 'import transfer_functions as tf\n'), ((17734, 18178), 'plot_utility.plot_1_graph', 'pu.plot_1_graph', ([], {'fontsize': '(20)', 'figsize': '(10, 8)', 'graph_title': '"""DaVinci17 Inverse DRT for SDR to HDR Conversion"""', 'graph_title_size': 'None', 'xlabel': '"""Input Luminance [cd/m2]"""', 'ylabel': '"""Output Luminance [cd/m2]"""', 'axis_label_size': 'None', 'legend_size': '(17)', 'xlim': '[0.009, 15000]', 'ylim': '[0.009, 15000]', 'xtick': 'None', 'ytick': 'None', 'xtick_size': 'None', 'ytick_size': 'None', 'linewidth': '(3)', 'minor_xtick_num': 'None', 'minor_ytick_num': 'None', 'return_figure': '(True)'}), "(fontsize=20, figsize=(10, 8), graph_title=\n 'DaVinci17 Inverse DRT for SDR to HDR Conversion', graph_title_size=\n None, xlabel='Input Luminance [cd/m2]', ylabel=\n 'Output Luminance [cd/m2]', axis_label_size=None, legend_size=17, xlim=\n [0.009, 15000], ylim=[0.009, 15000], xtick=None, ytick=None, xtick_size\n =None, ytick_size=None, linewidth=3, minor_xtick_num=None,\n minor_ytick_num=None, return_figure=True)\n", (17749, 18178), True, 'import plot_utility as pu\n'), ((18299, 18361), 'plot_utility.log_scale_settings', 'pu.log_scale_settings', (['ax1'], {'grid_alpha': '(0.5)', 'bg_color': '"""#E0E0E0"""'}), "(ax1, grid_alpha=0.5, bg_color='#E0E0E0')\n", (18320, 18361), True, 'import plot_utility as pu\n'), ((18649, 18677), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (18659, 18677), True, 'import matplotlib.pyplot as plt\n'), ((18743, 18803), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname_full'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.1)'}), "(fname_full, bbox_inches='tight', pad_inches=0.1)\n", (18754, 18803), True, 'import matplotlib.pyplot as plt\n'), ((18825, 18839), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (18834, 18839), True, 'import matplotlib.pyplot as plt\n'), ((19022, 19042), 'colour.read_image', 'read_image', (['src_file'], {}), '(src_file)\n', (19032, 19042), False, 'from colour import write_image, read_image\n'), ((19101, 19134), 'colour.write_image', 'write_image', (['img_linear', 'dst_file'], {}), '(img_linear, dst_file)\n', (19112, 19134), False, 'from colour import write_image, read_image\n'), ((989, 1013), 'numpy.ones', 'np.ones', (['(1080, 1920, 3)'], {}), '((1080, 1920, 3))\n', (996, 1013), True, 'import numpy as np\n'), ((4121, 4157), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['img', 'tf.ST2084'], {}), '(img, tf.ST2084)\n', (4141, 4157), True, 'import transfer_functions as tf\n'), ((5720, 5771), 'colour.read_image', 'read_image', (['"""./img/old/test_out_sdr100_on_gm24.tif"""'], {}), "('./img/old/test_out_sdr100_on_gm24.tif')\n", (5730, 5771), False, 'from colour import write_image, read_image\n'), ((7733, 7781), 'colour.read_image', 'read_image', (['"""./img/dv17_fig1_sdr_out_st2084.tif"""'], {}), "('./img/dv17_fig1_sdr_out_st2084.tif')\n", (7743, 7781), False, 'from colour import write_image, read_image\n'), ((8314, 8362), 'colour.read_image', 'read_image', (['"""./img/dv17_fig1_sdr_out_linear.tif"""'], {}), "('./img/dv17_fig1_sdr_out_linear.tif')\n", (8324, 8362), False, 'from colour import write_image, read_image\n'), ((12877, 12913), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['img', 'tf.ST2084'], {}), '(img, tf.ST2084)\n', (12897, 12913), True, 'import transfer_functions as tf\n'), ((16767, 16803), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['img', 'tf.ST2084'], {}), '(img, tf.ST2084)\n', (16787, 16803), True, 'import transfer_functions as tf\n'), ((18547, 18583), 'transfer_functions.eotf_to_luminance', 'tf.eotf_to_luminance', (['img', 'tf.ST2084'], {}), '(img, tf.ST2084)\n', (18567, 18583), True, 'import transfer_functions as tf\n'), ((19060, 19090), 'transfer_functions.eotf', 'tf.eotf', (['img_st2084', 'tf.ST2084'], {}), '(img_st2084, tf.ST2084)\n', (19067, 19090), True, 'import transfer_functions as tf\n'), ((604, 627), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (615, 627), True, 'import numpy as np\n'), ((827, 850), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1920)'], {}), '(0, 1, 1920)\n', (838, 850), True, 'import numpy as np\n'), ((3995, 4024), 'colour.read_image', 'read_image', (['file_list[idx][0]'], {}), '(file_list[idx][0])\n', (4005, 4024), False, 'from colour import write_image, read_image\n'), ((12751, 12780), 'colour.read_image', 'read_image', (['file_list[idx][0]'], {}), '(file_list[idx][0])\n', (12761, 12780), False, 'from colour import write_image, read_image\n'), ((13959, 13988), 'colour.read_image', 'read_image', (['file_list[idx][0]'], {}), '(file_list[idx][0])\n', (13969, 13988), False, 'from colour import write_image, read_image\n'), ((16641, 16670), 'colour.read_image', 'read_image', (['file_list[idx][0]'], {}), '(file_list[idx][0])\n', (16651, 16670), False, 'from colour import write_image, read_image\n'), ((18421, 18450), 'colour.read_image', 'read_image', (['file_list[idx][0]'], {}), '(file_list[idx][0])\n', (18431, 18450), False, 'from colour import write_image, read_image\n'), ((19422, 19447), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (19437, 19447), False, 'import os\n')]
import json from src.lib.application.webApp.action import Action from src.applications.models.json.user import UserModel, UserExpenses, UserExpense from src.lib.application.models.json.model import BaseResponse,ModelErrorResponse class ModelExampleAction(Action): ''' демонстрационный экшен показывает как распарсить модель из запроса обектами провалидировать, изменить запись и выдать объектами ответ пример запроса { "user":{ "id" : 15868, "name" : "Ари", "age": 33, "surname" : "Левитан", "phone" : "+77026202048", "address" : "Куйбышева 42", "expenses" : [ { "expense" : { "id" : 1586, "date" : "2018-02-12 12:22:48", "sum" : 5000.54, "comment" : "оплата баланс на телефон" } },{ "expense" : { "id" : 5698, "date" : "2018-02-12 12:48:12", "sum" : 2000.00, "comment" : "обед" } },{ "expense" : { "id" : 5244, "date" : "2018-02-12 13:34:55", "sum" : 500.00, "comment" : "такси" } } ], "friends" : [ 1245, 6589, 2659 ] } } ''' def get(self): self.write((BaseResponse(BaseResponse.CODE_OK,"use post method for this action")).getJson()) def post(self): try: user = UserModel(json.loads(self.request.body)) if user.validate() == False: error = ModelErrorResponse([user]) self.write(error.getJson()) return expense = UserExpense() expense.setId(12567) expense.setDate("2018-10-09 12:29:53") expense.setSum(12000.00) expense.setComment("тренажерка") user.addExpense(expense) self.write((BaseResponse(BaseResponse.CODE_OK,"record processed successful")).getJson()) except Exception as e: self.write((BaseResponse(BaseResponse.CODE_MODEL_ERROR,str(e))).getJson())
[ "src.applications.models.json.user.UserExpense", "src.lib.application.models.json.model.ModelErrorResponse", "json.loads", "src.lib.application.models.json.model.BaseResponse" ]
[((2161, 2174), 'src.applications.models.json.user.UserExpense', 'UserExpense', ([], {}), '()\n', (2172, 2174), False, 'from src.applications.models.json.user import UserModel, UserExpenses, UserExpense\n'), ((1923, 1952), 'json.loads', 'json.loads', (['self.request.body'], {}), '(self.request.body)\n', (1933, 1952), False, 'import json\n'), ((2032, 2058), 'src.lib.application.models.json.model.ModelErrorResponse', 'ModelErrorResponse', (['[user]'], {}), '([user])\n', (2050, 2058), False, 'from src.lib.application.models.json.model import BaseResponse, ModelErrorResponse\n'), ((1775, 1844), 'src.lib.application.models.json.model.BaseResponse', 'BaseResponse', (['BaseResponse.CODE_OK', '"""use post method for this action"""'], {}), "(BaseResponse.CODE_OK, 'use post method for this action')\n", (1787, 1844), False, 'from src.lib.application.models.json.model import BaseResponse, ModelErrorResponse\n'), ((2441, 2506), 'src.lib.application.models.json.model.BaseResponse', 'BaseResponse', (['BaseResponse.CODE_OK', '"""record processed successful"""'], {}), "(BaseResponse.CODE_OK, 'record processed successful')\n", (2453, 2506), False, 'from src.lib.application.models.json.model import BaseResponse, ModelErrorResponse\n')]
import base64 import distutils.version import random from lbrynet.core.cryptoutils import get_lbry_hash_obj blobhash_length = get_lbry_hash_obj().digest_size * 2 # digest_size is in bytes, and blob hashes are hex encoded def generate_id(num=None): h = get_lbry_hash_obj() if num is not None: h.update(str(num)) else: h.update(str(random.getrandbits(512))) return h.digest() def is_valid_blobhash(blobhash): """ @param blobhash: string, the blobhash to check @return: Whether the blobhash is the correct length and contains only valid characters (0-9, a-f) """ if len(blobhash) != blobhash_length: return False for l in blobhash: if l not in "0123456789abcdef": return False return True def version_is_greater_than(a, b): """Returns True if version a is more recent than version b""" try: return distutils.version.StrictVersion(a) > distutils.version.StrictVersion(b) except ValueError: return distutils.version.LooseVersion(a) > distutils.version.LooseVersion(b) def deobfuscate(obfustacated): return base64.b64decode(obfustacated.decode('rot13')) def obfuscate(plain): return base64.b64encode(plain).encode('rot13')
[ "lbrynet.core.cryptoutils.get_lbry_hash_obj", "base64.b64encode", "random.getrandbits" ]
[((263, 282), 'lbrynet.core.cryptoutils.get_lbry_hash_obj', 'get_lbry_hash_obj', ([], {}), '()\n', (280, 282), False, 'from lbrynet.core.cryptoutils import get_lbry_hash_obj\n'), ((130, 149), 'lbrynet.core.cryptoutils.get_lbry_hash_obj', 'get_lbry_hash_obj', ([], {}), '()\n', (147, 149), False, 'from lbrynet.core.cryptoutils import get_lbry_hash_obj\n'), ((1217, 1240), 'base64.b64encode', 'base64.b64encode', (['plain'], {}), '(plain)\n', (1233, 1240), False, 'import base64\n'), ((365, 388), 'random.getrandbits', 'random.getrandbits', (['(512)'], {}), '(512)\n', (383, 388), False, 'import random\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- from PIL import Image import nfp import argparse import os # default resize width/height when converting image -> nfp DEFAULT_WIDTH, DEFAULT_HEIGHT = 164, 81 desc = ( "Convert standard image files to ComputerCraft nfp files, and vice " "versa. Input file type is identified by extension (.nfp, .jpg, etc.), " "and output files use the input filename with a new extension." ) files_help = "input files, nfp or image (must have correct file extension)" nfp_desc = "optional arguments when converting image -> nfp" skip_help = "skip default behavior of resizing image before conversion" width_help = "if resizing, new width (default: {})".format(DEFAULT_WIDTH) height_help = "if resizing, new height (default: {})".format(DEFAULT_HEIGHT) im_desc = "optional arguments when converting nfp -> image" format_help = ( "output format passed to Image.save() (also output file extension " "unless -e argument specified), see PIL docs for supported formats, " "default: PNG" ) ext_help = ( "if specified, will be used as the output file extension instead of " "FORMAT" ) rm_help = "remove the original image after converting" dither_help = "enables dithering" parser = argparse.ArgumentParser(description=desc) parser.add_argument("files", help=files_help, nargs='+') nfp_group = parser.add_argument_group("nfp arguments", description=nfp_desc) nfp_group.add_argument("--skip-resize", "-s", help=skip_help, action="store_true", default=False) nfp_group.add_argument("--resize-width", "-w", help=width_help, metavar="WIDTH", type=int, default=DEFAULT_WIDTH) nfp_group.add_argument("--resize-height", "-H", help=height_help, metavar="HEIGHT", type=int, default=DEFAULT_HEIGHT) im_group = parser.add_argument_group("image arguments", description=im_desc) im_group.add_argument("--format", "-f", help=format_help, metavar="FORMAT", dest="f_format", default="PNG") im_group.add_argument("--extension", "-e", help=ext_help) im_group.add_argument("--remove", "-r", help=rm_help, action="store_true") im_group.add_argument("--dither", "-d", help=dither_help, action="store_true") args = parser.parse_args() for file in args.files: filename, ext = os.path.splitext(file) if not ext: parser.error("filename must have appropriate extension") if ext.upper() == ".NFP": with open(file, "rt") as f: nfp_file = f.read() im = nfp.nfp_to_img(nfp_file) new_ext = args.f_format.replace(" ", "").lower() if args.extension: new_ext = args.extension im.save("{}.{}".format(filename, new_ext), args.f_format) else: im = Image.open(file) if args.skip_resize: nfp_file = nfp.img_to_nfp(im, dither=1 if args.dither else 0) else: nfp_file = nfp.img_to_nfp( im, (args.resize_width, args.resize_height), dither=1 if args.dither else 0 ) with open("{}.nfp".format(filename), "wt") as f: f.write(nfp_file) if args.remove: os.remove(file)
[ "PIL.Image.open", "argparse.ArgumentParser", "os.path.splitext", "nfp.img_to_nfp", "nfp.nfp_to_img", "os.remove" ]
[((1235, 1276), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc'}), '(description=desc)\n', (1258, 1276), False, 'import argparse\n'), ((2302, 2324), 'os.path.splitext', 'os.path.splitext', (['file'], {}), '(file)\n', (2318, 2324), False, 'import os\n'), ((2517, 2541), 'nfp.nfp_to_img', 'nfp.nfp_to_img', (['nfp_file'], {}), '(nfp_file)\n', (2531, 2541), False, 'import nfp\n'), ((2752, 2768), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (2762, 2768), False, 'from PIL import Image\n'), ((3178, 3193), 'os.remove', 'os.remove', (['file'], {}), '(file)\n', (3187, 3193), False, 'import os\n'), ((2821, 2871), 'nfp.img_to_nfp', 'nfp.img_to_nfp', (['im'], {'dither': '(1 if args.dither else 0)'}), '(im, dither=1 if args.dither else 0)\n', (2835, 2871), False, 'import nfp\n'), ((2909, 3004), 'nfp.img_to_nfp', 'nfp.img_to_nfp', (['im', '(args.resize_width, args.resize_height)'], {'dither': '(1 if args.dither else 0)'}), '(im, (args.resize_width, args.resize_height), dither=1 if\n args.dither else 0)\n', (2923, 3004), False, 'import nfp\n')]
#!/usr/bin/env python # -*- coding:utf-8 -*- """================================================================= @Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3 @File : LC-1679-Max-Number-of-K-Sum-Pairs.py @Author : [YuweiYin](https://github.com/YuweiYin) @Date : 2022-05-04 ==================================================================""" import sys import time from typing import List # import functools """ LeetCode - 1679 - (Medium) - Max Number of K-Sum Pairs https://leetcode.com/problems/max-number-of-k-sum-pairs/ Description & Requirement: You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. Example 1: Input: nums = [1,2,3,4], k = 5 Output: 2 Explanation: Starting with nums = [1,2,3,4]: - Remove numbers 1 and 4, then nums = [2,3] - Remove numbers 2 and 3, then nums = [] There are no more pairs that sum up to 5, hence a total of 2 operations. Example 2: Input: nums = [3,1,3,4,3], k = 6 Output: 1 Explanation: Starting with nums = [3,1,3,4,3]: - Remove the first two 3's, then nums = [1,4,3] There are no more pairs that sum up to 6, hence a total of 1 operation. Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 1 <= k <= 10^9 """ class Solution: def maxOperations(self, nums: List[int], k: int) -> int: # exception case assert isinstance(nums, list) and len(nums) >= 1 assert isinstance(k, int) and k >= 1 # main method: (two sum, greedy match) return self._maxOperations(nums, k) def _maxOperations(self, nums: List[int], k: int) -> int: assert isinstance(nums, list) and len(nums) >= 1 assert isinstance(k, int) and k >= 1 len_nums = len(nums) if len_nums == 1: return 0 if len_nums == 2: return 1 if nums[0] + nums[1] == k else 0 num_dict = dict({}) for idx, num in enumerate(nums): if num not in num_dict: # num_dict[num] = [idx] num_dict[num] = 1 else: # num_dict[num].append(idx) num_dict[num] += 1 # visit_idx = [False for _ in range(len_nums)] res = 0 for idx, num in enumerate(nums): target_num = k - num if target_num in num_dict: if target_num == num: if num_dict[target_num] >= 2: num_dict[target_num] -= 2 res += 1 else: continue else: if num_dict[target_num] >= 1 and num_dict[num] >= 1: num_dict[target_num] -= 1 num_dict[num] -= 1 res += 1 else: continue else: continue return res def main(): # Example 1: Output: 2 nums = [1, 2, 3, 4] k = 5 # Example 2: Output: 1 # nums = [3, 1, 3, 4, 3] # k = 6 # init instance solution = Solution() # run & time start = time.process_time() ans = solution.maxOperations(nums, k) end = time.process_time() # show answer print('\nAnswer:') print(ans) # show time consumption print('Running Time: %.5f ms' % ((end - start) * 1000)) if __name__ == "__main__": sys.exit(main())
[ "time.process_time" ]
[((3330, 3349), 'time.process_time', 'time.process_time', ([], {}), '()\n', (3347, 3349), False, 'import time\n'), ((3402, 3421), 'time.process_time', 'time.process_time', ([], {}), '()\n', (3419, 3421), False, 'import time\n')]
import logging from .utils.plugins import Plugins, Proxy from .utils.decos import GenLimiter from typing import Iterator class ProxyQuery(Plugins): """Handles the querying and operations of plugins""" @GenLimiter def exec_iter_plugin(self, method_name: str, sort_asc_fails: bool = True, *args, **kwargs) -> Iterator[Proxy]: """Executes a given method in all plugins that return an iterable, then returns an iterable that loops through each plugins iterable""" if sort_asc_fails: self.plugins.sort(key=lambda plugin: plugin.fails) for plugin in self.plugins: try: method = getattr(plugin, method_name) return_iter = method(*args, **kwargs) for value in return_iter: yield value except Exception: logging.info(f"FreeProxyScraper plugin \"{plugin.plugin_name}\" has crashed") plugin.report_fail() continue @GenLimiter def find_proxies(self, test: bool = True) -> Iterator[Proxy]: """Uses all plugins to search for proxies""" proxies = self.exec_iter_plugin("find", True) if test: proxies = self.test_proxies(proxies) return proxies @GenLimiter def find_filter(self, country: str = None, ping: int = None, min_anon_level: int = 0, test: bool = True) -> Iterator[Proxy]: """Uses all plugins to finds proxies that meet certain values""" proxies = self.exec_iter_plugin("find_filter", True, country, ping, min_anon_level) if test: proxies = self.test_proxies(proxies) return proxies def test_proxies(self, proxies: Iterator[Proxy]) -> Iterator[Proxy]: """Takes a iterator of Proxy and returns a generator that skips over every plugin that failed the test""" for proxy in proxies: if proxy.test(): yield proxy
[ "logging.info" ]
[((863, 938), 'logging.info', 'logging.info', (['f"""FreeProxyScraper plugin "{plugin.plugin_name}" has crashed"""'], {}), '(f\'FreeProxyScraper plugin "{plugin.plugin_name}" has crashed\')\n', (875, 938), False, 'import logging\n')]
""" Author: <NAME> Date: 6th/July/2020 Copyright: <NAME>, 2020 email: <EMAIL> website: https://johdev.com """ import numpy as np import pandas as pd class FeatureGenerator(object): """A feature engineering generator to create additional feature to DataFrame Group by each label encoded column, compute the: * mean * max * min * Standard Deviation * median of label column Parameter ------------- data: object, a dataset object created by `preprocessing.py` Method ------------- add_group_stats(self): group by each label encoded column, and compute the Grouped Statitics. fill any NaN value with 0 Return: grouped by statitics DataFrame merged with original DataFrame. Example ------------- >>> feature_engineering = True >>> if feature_engineering: FeatureGenerator(data).add_group_stats() """ def __init__(self, data:object): """initializes class and creates groupby object for data""" self.data = data self.cat_cols = data.cat_cols self.groups = data.train_df.groupby(self.cat_cols) def add_group_stats(self): """adds group statistics to data stored in data object""" group_stats_df = self._get_group_stats() group_stats_df.reset_index(inplace=True) # merge derived columns to original df self.data.train_df = self._merge_new_cols(self.data.train_df, group_stats_df, self.cat_cols, fillna=True) self.data.test_df = self._merge_new_cols(self.data.test_df, group_stats_df, self.cat_cols, fillna=True) # update column list group_stats_cols = ['group_mean_salary', 'group_max_salary', 'group_min_salary', 'group_std_salary', 'group_median_salary'] self._extend_col_lists(self.data, cat_cols=group_stats_cols) def _get_group_stats(self): """calculate group statistics""" target_col = self.data.target_col group_stats_df = pd.DataFrame({'group_mean_salary': self.groups[target_col].mean()}) group_stats_df['group_max_salary'] = self.groups[target_col].max() group_stats_df['group_min_salary'] = self.groups[target_col].min() group_stats_df['group_std_salary'] = self.groups[target_col].std() group_stats_df['group_median_salary'] = self.groups[target_col].median() return group_stats_df def _merge_new_cols(self, df, new_cols_df, keys, fillna=False): """Merges engineered features with original df""" DataFrame = pd.merge(df, new_cols_df, on=keys, how='left') if fillna: DataFrame.fillna(0, inplace=True) return DataFrame def _extend_col_lists(self, data, cat_cols=[], num_cols=[]): """addes engineered features cols to data cols lists""" data.num_cols.extend(num_cols) data.cat_cols.extend(cat_cols) data.feature_cols.extend(num_cols + cat_cols)
[ "pandas.merge" ]
[((2594, 2640), 'pandas.merge', 'pd.merge', (['df', 'new_cols_df'], {'on': 'keys', 'how': '"""left"""'}), "(df, new_cols_df, on=keys, how='left')\n", (2602, 2640), True, 'import pandas as pd\n')]
import math import numpy as np import matplotlib.pyplot as plt import csv import os logPath = './online/log/9x16_test/' nameList = ['Alien', 'Conan1', 'Conan2', 'Cooking', 'Rhinos', 'Skiing', 'Surfing', 'War'] num = 48 batch_size = 4 tileList = [] tileListList = [[] for j in range(len(nameList))] for idx, f in enumerate(nameList): for i in range(1, num+1): with open(logPath + f"user_{i}/{f}_{i}.csv", 'r') as csvfile: reader = csv.reader(csvfile) rows = [row for row in reader] tile_list = [float(item[3]) for item in rows[1:-8]] try: tileListList[idx].append(np.mean(tile_list)) except IndexError: print("IndexError:", idx) tileList.append(math.ceil(np.mean(tileListList[idx]))) x = np.arange(len(nameList)) width = 0.4 plt.rcParams['font.size'] = 20 fig, ax = plt.subplots(figsize=(20, 8)) plt.bar(x, tileList, width=width) plt.grid(linestyle='--') plt.xticks(x, nameList, fontsize=20) ax.set_ylabel('AverageTiles') plt.tight_layout() plt.savefig('./online/log/9x16_test/48_users/tiles.png') plt.show() print("finish!") fileName = f'./online/log/9x16_test/48_users/tiles.csv' with open(fileName, 'w', newline='') as f: logWriter = csv.writer(f, dialect='excel') logWriter.writerow(['AverageMetric']+nameList) logWriter.writerows([ ['Tiles'] + tileList, ])
[ "numpy.mean", "matplotlib.pyplot.grid", "matplotlib.pyplot.savefig", "matplotlib.pyplot.xticks", "csv.writer", "matplotlib.pyplot.bar", "matplotlib.pyplot.tight_layout", "csv.reader", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((883, 912), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(20, 8)'}), '(figsize=(20, 8))\n', (895, 912), True, 'import matplotlib.pyplot as plt\n'), ((913, 946), 'matplotlib.pyplot.bar', 'plt.bar', (['x', 'tileList'], {'width': 'width'}), '(x, tileList, width=width)\n', (920, 946), True, 'import matplotlib.pyplot as plt\n'), ((948, 972), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'linestyle': '"""--"""'}), "(linestyle='--')\n", (956, 972), True, 'import matplotlib.pyplot as plt\n'), ((973, 1009), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', 'nameList'], {'fontsize': '(20)'}), '(x, nameList, fontsize=20)\n', (983, 1009), True, 'import matplotlib.pyplot as plt\n'), ((1040, 1058), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1056, 1058), True, 'import matplotlib.pyplot as plt\n'), ((1059, 1115), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./online/log/9x16_test/48_users/tiles.png"""'], {}), "('./online/log/9x16_test/48_users/tiles.png')\n", (1070, 1115), True, 'import matplotlib.pyplot as plt\n'), ((1116, 1126), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1124, 1126), True, 'import matplotlib.pyplot as plt\n'), ((1261, 1291), 'csv.writer', 'csv.writer', (['f'], {'dialect': '"""excel"""'}), "(f, dialect='excel')\n", (1271, 1291), False, 'import csv\n'), ((460, 479), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (470, 479), False, 'import csv\n'), ((771, 797), 'numpy.mean', 'np.mean', (['tileListList[idx]'], {}), '(tileListList[idx])\n', (778, 797), True, 'import numpy as np\n'), ((647, 665), 'numpy.mean', 'np.mean', (['tile_list'], {}), '(tile_list)\n', (654, 665), True, 'import numpy as np\n')]
import logging import math import time import re import os from PIL import Image, ImageDraw, ImageFont from otter_buddy.constants import FONT_PATH logger = logging.getLogger(__name__) # Based on RFC 5322 Official Standard # Ref: https://www.ietf.org/rfc/rfc5322.txt email_regex: str = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" def time_format(seconds): seconds = int(seconds) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) return days, hours, minutes, seconds def pretty_time_format(seconds, *, shorten=False, only_most_significant=False, always_seconds=False): days, hours, minutes, seconds = time_format(seconds) timespec = [ (days, 'day', 'days'), (hours, 'hour', 'hours'), (minutes, 'minute', 'minutes'), ] timeprint = [(cnt, singular, plural) for cnt, singular, plural in timespec if cnt] if not timeprint or always_seconds: timeprint.append((seconds, 'second', 'seconds')) if only_most_significant: timeprint = [timeprint[0]] def format_(triple): cnt, singular, plural = triple return f'{cnt}{singular[0]}' if shorten else f'{cnt} {singular if cnt == 1 else plural}' return ' '.join(map(format_, timeprint)) def is_valid_email(email: str) -> bool: if(re.search(email_regex, email)): return True else: return False def get_size(txt: str, font) -> (int, int): testImg = Image.new('RGB', (1, 1)) testDraw = ImageDraw.Draw(testImg) return testDraw.textsize(txt, font) def create_match_image(week_otter_pairs: list) -> (Image, str): first_list, second_list = zip(*week_otter_pairs) first_column = "\n".join(list(map(lambda user: f"{user.display_name}#{user.discriminator}", first_list))) second_column = "\n".join(list(map(lambda user: f"{user.display_name}#{user.discriminator}", second_list))) colorText = "black" colorOutline = "gray" colorBackground = "white" fontsize = 16 font = ImageFont.truetype(FONT_PATH, fontsize) width, height = get_size(first_column, font) width2, _height2 = get_size(second_column, font) img = Image.new('RGB', ((width + width2)+100, (height)+20), colorBackground) d = ImageDraw.Draw(img) d.text((5,5), first_column, fill=colorText, font=font) d.text((width+55,5), second_column, fill=colorText, font=font) d.rectangle((0, 0, width+50, height+20), outline=colorOutline) d.rectangle((width+50, 0, (width + width2)+100, height+20), outline=colorOutline) path = os.path.dirname(os.path.realpath(__file__)) + "/image.png" img.save(path) return img, path
[ "logging.getLogger", "PIL.Image.new", "PIL.ImageFont.truetype", "os.path.realpath", "PIL.ImageDraw.Draw", "re.search" ]
[((159, 186), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (176, 186), False, 'import logging\n'), ((1362, 1391), 're.search', 're.search', (['email_regex', 'email'], {}), '(email_regex, email)\n', (1371, 1391), False, 'import re\n'), ((1513, 1537), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(1, 1)'], {}), "('RGB', (1, 1))\n", (1522, 1537), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1553, 1576), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['testImg'], {}), '(testImg)\n', (1567, 1576), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2073, 2112), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['FONT_PATH', 'fontsize'], {}), '(FONT_PATH, fontsize)\n', (2091, 2112), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2226, 2296), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(width + width2 + 100, height + 20)', 'colorBackground'], {}), "('RGB', (width + width2 + 100, height + 20), colorBackground)\n", (2235, 2296), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2305, 2324), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (2319, 2324), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2632, 2658), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (2648, 2658), False, 'import os\n')]
"""Module for IQ option websocket.""" import json import logging import websocket import iqoptionapi.constants as OP_code import iqoptionapi.global_value as global_value class WebsocketClient(object): """Class for work with IQ option websocket.""" def __init__(self, api): """ :param api: The instance of :class:`IQOptionAPI <iqoptionapi.api.IQOptionAPI>`. """ self.api = api self.wss = websocket.WebSocketApp( self.api.wss_url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open) def dict_queue_add(self,dict,maxdict,key1,key2,key3,value): if key3 in dict[key1][key2]: dict[key1][key2][key3]=value else: while True: try: dic_size=len(dict[key1][key2]) except: dic_size=0 if dic_size<maxdict: dict[key1][key2][key3]=value break else: #del mini key del dict[key1][key2][sorted(dict[key1][key2].keys(), reverse=False)[0]] def on_message(self, message): # pylint: disable=unused-argument """Method to process websocket messages.""" global_value.ssl_Mutual_exclusion=True logger = logging.getLogger(__name__) logger.debug(message) message = json.loads(str(message)) if message["name"] == "timeSync": self.api.timesync.server_timestamp = message["msg"] ####################################################### #---------------------for_realtime_candle______________ ####################################################### elif message["name"] == "candle-generated": Active_name=list(OP_code.ACTIVES.keys())[list(OP_code.ACTIVES.values()).index(message["msg"]["active_id"])] active=str(Active_name) size=int(message["msg"]["size"]) from_=int(message["msg"]["from"]) msg=message["msg"] maxdict=self.api.real_time_candles_maxdict_table[Active_name][size] self.dict_queue_add(self.api.real_time_candles,maxdict,active,size,from_,msg) self.api.candle_generated_check[active][size]=True elif message["name"]=="options": self.api.get_options_v2_data=message elif message["name"] == "candles-generated": Active_name=list(OP_code.ACTIVES.keys())[list(OP_code.ACTIVES.values()).index(message["msg"]["active_id"])] active=str(Active_name) for k,v in message["msg"]["candles"].items(): v["active_id"]=message["msg"]["active_id"] v["at"]=message["msg"]["at"] v["ask"]=message["msg"]["ask"] v["bid"]=message["msg"]["bid"] v["close"]=message["msg"]["value"] v["size"]=int(k) size=int(v["size"]) from_=int(v["from"]) maxdict=self.api.real_time_candles_maxdict_table[Active_name][size] msg=v self.dict_queue_add(self.api.real_time_candles,maxdict,active,size,from_,msg) self.api.candle_generated_all_size_check[active]=True elif message["name"]=="commission-changed": instrument_type=message["msg"]["instrument_type"] active_id=message["msg"]["active_id"] Active_name=list(OP_code.ACTIVES.keys())[list(OP_code.ACTIVES.values()).index(active_id)] commission=message["msg"]["commission"]["value"] self.api.subscribe_commission_changed_data[instrument_type][Active_name][self.api.timesync.server_timestamp]=int(commission) ####################################################### #______________________________________________________ ####################################################### elif message["name"] =="heartbeat": try: self.api.heartbeat(message["msg"]) except: pass elif message["name"]=="balances": self.api.balances_raw=message elif message["name"] == "profile": #--------------all------------- self.api.profile.msg=message["msg"] if self.api.profile.msg!=False: #--------------------------- try: self.api.profile.balance = message["msg"]["balance"] except: pass #Set Default account if global_value.balance_id==None: for balance in message["msg"]["balances"]: if balance["type"]==4: global_value.balance_id=balance["id"] break try: self.api.profile.balance_id=message["msg"]["balance_id"] except: pass try: self.api.profile.balance_type=message["msg"]["balance_type"] except: pass try: self.api.profile.balances=message["msg"]["balances"] except: pass elif message["name"] == "candles": try: self.api.candles.candles_data = message["msg"]["candles"] except: pass #Make sure ""self.api.buySuccessful"" more stable #check buySuccessful have two fail action #if "user not authorized" we get buyV2_result !!!need to reconnect!!! #elif "we have user authoget_balancerized" we get buyComplete #I Suggest if you get selget_balancef.api.buy_successful==False you need to reconnect iqoption server elif message["name"] == "buyComplete": try: self.api.buy_successful = message["msg"]["isSuccessful"] self.api.buy_id= message["msg"]["result"]["id"] except: pass elif message["name"] == "buyV2_result": self.api.buy_successful = message["msg"]["isSuccessful"] #*********************buyv3 #buy_multi_option elif message["name"] == "option": self.api.buy_multi_option[str(message["request_id"])] = message["msg"] #********************************************************** elif message["name"] == "listInfoData": for get_m in message["msg"]: self.api.listinfodata.set(get_m["win"],get_m["game_state"],get_m["id"]) elif message["name"] == "socket-option-opened": id=message["msg"]["id"] self.api.socket_option_opened[id]=message elif message["name"] == "api_option_init_all_result": self.api.api_option_init_all_result = message["msg"] elif message["name"] == "initialization-data": self.api.api_option_init_all_result_v2 = message["msg"] elif message["name"] == "underlying-list": self.api.underlying_list_data=message["msg"] elif message["name"] == "instruments": self.api.instruments=message["msg"] elif message["name"]=="financial-information": self.api.financial_information=message elif message["name"]=="position-changed": if message["microserviceName"]=="portfolio" and (message["msg"]["source"]=="digital-options") or message["msg"]["source"]=="trading": self.api.order_async[int(message["msg"]["raw_event"]["order_ids"][0])] [message["name"]]=message elif message["microserviceName"]=="portfolio" and message["msg"]["source"]=="binary-options": self.api.order_async[int(message["msg"]["external_id"])] [message["name"]]=message #print(message) elif message["name"]=="option-opened": self.api.order_async[int(message["msg"]["option_id"])][message["name"]]=message elif message["name"]=="option-closed": self.api.order_async[int(message["msg"]["option_id"])][message["name"]]=message elif message["name"]=="top-assets-updated": self.api.top_assets_updated_data[str(message["msg"]["instrument_type"])]=message["msg"]["data"] elif message["name"]=="strike-list": self.api.strike_list=message elif message["name"]=="api_game_betinfo_result": try: self.api.game_betinfo.isSuccessful=message["msg"]["isSuccessful"] self.api.game_betinfo.dict=message["msg"] except: pass elif message["name"]=="traders-mood-changed": self.api.traders_mood[message["msg"]["asset_id"]]=message["msg"]["value"] #------for forex&cfd&crypto.. elif message["name"]=="order-placed-temp": self.api.buy_order_id= message["msg"]["id"] elif message["name"]=="order": self.api.order_data=message elif message["name"]=="positions": self.api.positions=message elif message["name"]=="position": self.api.position=message elif message["name"]=="deferred-orders": self.api.deferred_orders=message elif message["name"]=="position-history": self.api.position_history=message elif message["name"]=="history-positions": self.api.position_history_v2=message elif message["name"]=="available-leverages": self.api.available_leverages=message elif message["name"]=="order-canceled": self.api.order_canceled=message elif message["name"]=="position-closed": self.api.close_position_data=message elif message["name"]=="overnight-fee": self.api.overnight_fee=message elif message["name"]=="api_game_getoptions_result": self.api.api_game_getoptions_result=message elif message["name"]=="sold-options": self.api.sold_options_respond=message elif message["name"]=="tpsl-changed": self.api.tpsl_changed_respond=message elif message["name"]=="position-changed": self.api.position_changed=message elif message["name"]=="auto-margin-call-changed": self.api.auto_margin_call_changed_respond=message elif message["name"]=="digital-option-placed": try: self.api.digital_option_placed_id=message["msg"]["id"] except: self.api.digital_option_placed_id=message["msg"] elif message["name"]=="result": self.api.result=message["msg"]["success"] elif message["name"]=="instrument-quotes-generated": Active_name=list(OP_code.ACTIVES.keys())[list(OP_code.ACTIVES.values()).index(message["msg"]["active"])] period=message["msg"]["expiration"]["period"] ans={} for data in message["msg"]["quotes"]: #FROM IQ OPTION SOURCE CODE #https://github.com/Lu-Yi-Hsun/Decompiler-IQ-Option/blob/master/Source%20Code/5.5.1/sources/com/iqoption/dto/entity/strike/Quote.java#L91 if data["price"]["ask"]==None: ProfitPercent=None else: askPrice=(float)(data["price"]["ask"]) ProfitPercent=((100-askPrice)*100)/askPrice for symble in data["symbols"]: try: """ ID SAMPLE:doUSDJPY-OTC201811111204PT1MC11350481 """ """ dict ID-prodit:{ID:profit} """ ans[symble]=ProfitPercent except: pass self.api.instrument_quites_generated_timestamp[Active_name][period]=message["msg"]["expiration"]["timestamp"] self.api.instrument_quites_generated_data[Active_name][period]=ans self.api.instrument_quotes_generated_raw_data[Active_name][period]=message elif message["name"]=="training-balance-reset": self.api.training_balance_reset_request=message["msg"]["isSuccessful"] elif message["name"]=="live-deal-binary-option-placed": name=message["name"] active_id=message["msg"]["active_id"] active=list(OP_code.ACTIVES.keys())[list(OP_code.ACTIVES.values()).index(active_id)] _type=message["msg"]["option_type"] try: self.api.live_deal_data[name][active][_type].appendleft(message["msg"]) except: pass elif message["name"]=="live-deal-digital-option": name=message["name"] active_id=message["msg"]["instrument_active_id"] active=list(OP_code.ACTIVES.keys())[list(OP_code.ACTIVES.values()).index(active_id)] _type=message["msg"]["expiration_type"] try: self.api.live_deal_data[name][active][_type].appendleft(message["msg"]) except: pass elif message["name"]=="leaderboard-deals-client": self.api.leaderboard_deals_client=message["msg"] elif message["name"]=="live-deal": name=message["name"] active_id=message["msg"]["instrument_active_id"] active=list(OP_code.ACTIVES.keys())[list(OP_code.ACTIVES.values()).index(active_id)] _type=message["msg"]["instrument_type"] try: self.api.live_deal_data[name][active][_type].appendleft(message["msg"]) except: pass elif message["name"]=="user-profile-client": self.api.user_profile_client=message["msg"] elif message["name"]=="leaderboard-userinfo-deals-client": self.api.leaderboard_userinfo_deals_client=message["msg"] elif message["name"]=="users-availability": self.api.users_availability=message["msg"] else: pass global_value.ssl_Mutual_exclusion=False @staticmethod def on_error(wss, error): # pylint: disable=unused-argument """Method to process websocket errors.""" logger = logging.getLogger(__name__) logger.error(error) global_value.websocket_error_reason=str(error) global_value.check_websocket_if_error=True @staticmethod def on_open(wss): # pylint: disable=unused-argument """Method to process websocket open.""" logger = logging.getLogger(__name__) logger.debug("Websocket client connected.") global_value.check_websocket_if_connect=1 @staticmethod def on_close(wss): # pylint: disable=unused-argument """Method to process websocket close.""" logger = logging.getLogger(__name__) logger.debug("Websocket connection closed.") global_value.check_websocket_if_connect=0
[ "logging.getLogger", "iqoptionapi.constants.ACTIVES.keys", "iqoptionapi.constants.ACTIVES.values", "websocket.WebSocketApp" ]
[((468, 610), 'websocket.WebSocketApp', 'websocket.WebSocketApp', (['self.api.wss_url'], {'on_message': 'self.on_message', 'on_error': 'self.on_error', 'on_close': 'self.on_close', 'on_open': 'self.on_open'}), '(self.api.wss_url, on_message=self.on_message,\n on_error=self.on_error, on_close=self.on_close, on_open=self.on_open)\n', (490, 610), False, 'import websocket\n'), ((1407, 1434), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1424, 1434), False, 'import logging\n'), ((14600, 14627), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (14617, 14627), False, 'import logging\n'), ((14901, 14928), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (14918, 14928), False, 'import logging\n'), ((15172, 15199), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (15189, 15199), False, 'import logging\n'), ((1890, 1912), 'iqoptionapi.constants.ACTIVES.keys', 'OP_code.ACTIVES.keys', ([], {}), '()\n', (1910, 1912), True, 'import iqoptionapi.constants as OP_code\n'), ((1919, 1943), 'iqoptionapi.constants.ACTIVES.values', 'OP_code.ACTIVES.values', ([], {}), '()\n', (1941, 1943), True, 'import iqoptionapi.constants as OP_code\n'), ((2583, 2605), 'iqoptionapi.constants.ACTIVES.keys', 'OP_code.ACTIVES.keys', ([], {}), '()\n', (2603, 2605), True, 'import iqoptionapi.constants as OP_code\n'), ((3590, 3612), 'iqoptionapi.constants.ACTIVES.keys', 'OP_code.ACTIVES.keys', ([], {}), '()\n', (3610, 3612), True, 'import iqoptionapi.constants as OP_code\n'), ((2612, 2636), 'iqoptionapi.constants.ACTIVES.values', 'OP_code.ACTIVES.values', ([], {}), '()\n', (2634, 2636), True, 'import iqoptionapi.constants as OP_code\n'), ((3619, 3643), 'iqoptionapi.constants.ACTIVES.values', 'OP_code.ACTIVES.values', ([], {}), '()\n', (3641, 3643), True, 'import iqoptionapi.constants as OP_code\n'), ((11045, 11067), 'iqoptionapi.constants.ACTIVES.keys', 'OP_code.ACTIVES.keys', ([], {}), '()\n', (11065, 11067), True, 'import iqoptionapi.constants as OP_code\n'), ((11074, 11098), 'iqoptionapi.constants.ACTIVES.values', 'OP_code.ACTIVES.values', ([], {}), '()\n', (11096, 11098), True, 'import iqoptionapi.constants as OP_code\n'), ((12726, 12748), 'iqoptionapi.constants.ACTIVES.keys', 'OP_code.ACTIVES.keys', ([], {}), '()\n', (12746, 12748), True, 'import iqoptionapi.constants as OP_code\n'), ((13170, 13192), 'iqoptionapi.constants.ACTIVES.keys', 'OP_code.ACTIVES.keys', ([], {}), '()\n', (13190, 13192), True, 'import iqoptionapi.constants as OP_code\n'), ((12755, 12779), 'iqoptionapi.constants.ACTIVES.values', 'OP_code.ACTIVES.values', ([], {}), '()\n', (12777, 12779), True, 'import iqoptionapi.constants as OP_code\n'), ((13199, 13223), 'iqoptionapi.constants.ACTIVES.values', 'OP_code.ACTIVES.values', ([], {}), '()\n', (13221, 13223), True, 'import iqoptionapi.constants as OP_code\n'), ((13723, 13745), 'iqoptionapi.constants.ACTIVES.keys', 'OP_code.ACTIVES.keys', ([], {}), '()\n', (13743, 13745), True, 'import iqoptionapi.constants as OP_code\n'), ((13752, 13776), 'iqoptionapi.constants.ACTIVES.values', 'OP_code.ACTIVES.values', ([], {}), '()\n', (13774, 13776), True, 'import iqoptionapi.constants as OP_code\n')]
from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. #storing user profile data class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #storing posts in the databse class notes(models.Model): PYTHON = 'PYTHON' DJANGO = 'DJANGO' JAVA = 'JAVA' MYSQL = 'MYSQL' MACHINE_LEARNING = 'MACHINE_LEARNING' JAVASCRIPT = 'JAVASCRIPT' FRONT_END = 'FRONT_END' C = 'C/C++' NOTE_CHOICE = ( (PYTHON,'PYTHON'), (DJANGO,'DJANGO'), (JAVA,'JAVA'), (MYSQL,'MYSQL'), (MACHINE_LEARNING,'MACHINE_LEARNING'), (JAVASCRIPT,'JAVASCRIPT'), (FRONT_END,'FRONT_END'), (C,'C/C++') ) author = models.CharField(max_length=100) tag = models.CharField(blank = True,choices = NOTE_CHOICE, max_length=100) title = models.CharField(max_length=200) content = models.TextField(max_length=10000) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="images", blank=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title #For Commenting on any post it will require login class comments(models.Model): PYTHON = 'PYTHON' DJANGO = 'DJANGO' JAVA = 'JAVA' MYSQL = 'MYSQL' MACHINE_LEARNING = 'MACHINE_LEARNING' JAVASCRIPT = 'JAVASCRIPT' FRONT_END = 'FRONT_END' C = 'C/C++' NOTE_CHOICE = ( (PYTHON,'PYTHON'), (DJANGO,'DJANGO'), (JAVA,'JAVA'), (MYSQL,'MYSQL'), (MACHINE_LEARNING,'MACHINE_LEARNING'), (JAVASCRIPT,'JAVASCRIPT'), (FRONT_END,'FRONT_END'), (C,'C/C++') ) name = models.CharField(blank = True ,max_length = 50) comment_tag = models.CharField(blank = True,choices = NOTE_CHOICE, max_length=100) post_comment= models.CharField(blank = True , max_length = 200) def __str__(self): return self.comment_tag #For storing Feedback from any visitors class Feedback(models.Model): feedback_name = models.CharField(max_length = 50) feedback_comment = models.TextField(max_length = 200)
[ "django.db.models.OneToOneField", "django.db.models.TextField", "django.utils.timezone.now", "django.db.models.ImageField", "django.db.models.DateTimeField", "django.db.models.CharField" ]
[((210, 262), 'django.db.models.OneToOneField', 'models.OneToOneField', (['User'], {'on_delete': 'models.CASCADE'}), '(User, on_delete=models.CASCADE)\n', (230, 262), False, 'from django.db import models\n'), ((798, 830), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (814, 830), False, 'from django.db import models\n'), ((841, 906), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': 'NOTE_CHOICE', 'max_length': '(100)'}), '(blank=True, choices=NOTE_CHOICE, max_length=100)\n', (857, 906), False, 'from django.db import models\n'), ((922, 954), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (938, 954), False, 'from django.db import models\n'), ((969, 1003), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(10000)'}), '(max_length=10000)\n', (985, 1003), False, 'from django.db import models\n'), ((1025, 1068), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1045, 1068), False, 'from django.db import models\n'), ((1081, 1130), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""images"""', 'blank': '(True)'}), "(upload_to='images', blank=True)\n", (1098, 1130), False, 'from django.db import models\n'), ((1830, 1873), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(50)'}), '(blank=True, max_length=50)\n', (1846, 1873), False, 'from django.db import models\n'), ((1896, 1961), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'choices': 'NOTE_CHOICE', 'max_length': '(100)'}), '(blank=True, choices=NOTE_CHOICE, max_length=100)\n', (1912, 1961), False, 'from django.db import models\n'), ((1983, 2027), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(200)'}), '(blank=True, max_length=200)\n', (1999, 2027), False, 'from django.db import models\n'), ((2180, 2211), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (2196, 2211), False, 'from django.db import models\n'), ((2237, 2269), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (2253, 2269), False, 'from django.db import models\n'), ((1185, 1199), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (1197, 1199), False, 'from django.utils import timezone\n')]
from embuilder.builder import EMB prefixes = dict( rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" , rdfs = "http://www.w3.org/2000/01/rdf-schema#" , obo = "http://purl.obolibrary.org/obo/" , sio = "http://semanticscience.org/resource/" , xsd = "http://www.w3.org/2001/XMLSchema#", this = "http://my_example.com/") triplets = [ # sio nodes ["this:$(pid)_$(uniqid)_ID","sio:denotes","this:$(pid)_$(uniqid)_Role","iri"], ["this:$(pid)_$(uniqid)_Entity","sio:has-role","this:$(pid)_$(uniqid)_Role","iri"], ["this:$(pid)_$(uniqid)_Role","sio:is-realized-in","this:$(pid)_$(uniqid)_Process","iri"], ["this:$(pid)_$(uniqid)_Process","sio:has-output","this:$(pid)_$(uniqid)_Output","iri"], ["this:$(pid)_$(uniqid)_Output","sio:refers-to","this:$(pid)_$(uniqid)_Attribute","iri"], ["this:$(pid)_$(uniqid)_Entity","sio:has-attribute","this:$(pid)_$(uniqid)_Attribute","iri"], # sio types ["this:$(pid)_$(uniqid)_ID","rdf:type","sio:identifier","iri"], ["this:$(pid)_$(uniqid)_Entity","rdf:type","sio:person","iri"], ["this:$(pid)_$(uniqid)_Role","rdf:type","sio:role","iri"], ["this:$(pid)_$(uniqid)_Process","rdf:type","sio:process","iri"], ["this:$(pid)_$(uniqid)_Output","rdf:type","sio:information-content-entity","iri"], ["this:$(pid)_$(uniqid)_Attribute","rdf:type","sio:attribute","iri"], # data ["this:$(pid)_$(uniqid)_Output","sio:has-value","$(datetime)","xsd:date"]] config = dict( source_name = "source_cde_test", configuration = "ejp", # Two options for this parameter: # ejp: it defines CDE-in-a-Box references, being compatible with this workflow # csv: No workflow defined, set the source configuration for been used by CSV as data source csv_name = "source_1" # parameter only needed in case you pick "csv" as configuration ) build = EMB(config, prefixes,triplets) test = build.transform_ShEx("this") test2 = build.transform_YARRRML() test3 = build.transform_OBDA() print(test) print(test2) print(test3)
[ "embuilder.builder.EMB" ]
[((1864, 1895), 'embuilder.builder.EMB', 'EMB', (['config', 'prefixes', 'triplets'], {}), '(config, prefixes, triplets)\n', (1867, 1895), False, 'from embuilder.builder import EMB\n')]
from base64 import b64decode with open('good_luck.dat', 'r') as f: data = f.readlines() for i, line in enumerate(data): data[i] = line.split('|')[1] b64answ = ''.join(data) with open('base64_1.txt', 'wb') as f: f.write(b64decode(b64answ)) with open('base64_1.txt', 'r') as f: data = f.read().split() for i, piece in enumerate(data): data[i] = b64decode(piece).decode() answ = ' '.join(data) with open('base64_2.txt', 'w') as f: f.write(answ) another_answ = bytes([int(a) for a in answ.split()]) with open('bytes.txt', 'wb') as f: f.write(another_answ)
[ "base64.b64decode" ]
[((234, 252), 'base64.b64decode', 'b64decode', (['b64answ'], {}), '(b64answ)\n', (243, 252), False, 'from base64 import b64decode\n'), ((370, 386), 'base64.b64decode', 'b64decode', (['piece'], {}), '(piece)\n', (379, 386), False, 'from base64 import b64decode\n')]
# -*- coding: UTF-8 -*- from spider import * class Prepare: def __init__(self,col=None): self.url = BASE_URL self.col = col self.content_type = 'application/json; charset=utf-8' self.collect = mongodb.db[self.col] def update_one(self,matchid,item): """更新数据""" try: if not self.isrollball: inplaydelay = item.get('inplaydelay') del item['inplaydelay'] self.collect.update_one({'matchid': matchid,'inplaydelay':inplaydelay}, {'$set': item}, upsert=True) logger.info('更新数据') else: inplaydelay = item.get('inplaydelay') del item['inplaydelay'] self.collect.update_one({'matchid': matchid,'inplaydelay':inplaydelay}, {'$set': item}, upsert=True) logger.info('更新数据') except Exception as ex: logger.info(traceback.format_exc()) def update_one_by_jsontype(self,jsontype,item): try: self.collect.update_one(jsontype, {'$set': item}, upsert=True) logger.info(f'冠军更新数据,暂停{fresh_by_jsontype}秒') #time.sleep(fresh_by_jsontype) except Exception as ex: logger.info(traceback.format_exc()) def get_matchid(self): try: gids = [] response = self.session.get(self.url,params=self.json_type, timeout=timeout) if response.status_code == 200 and self.content_type == response.headers['Content-Type']: response = response.json() for reslut in response: gids.append(reslut.get('matchID')) return gids else: logger.info('响应不是json,获取cookie') # set cookie get_cookie(self.session,self.url,response.text,self.json_type) return self.get_matchid() except Exception as ex: logger.info(traceback.format_exc()) return self.get_matchid() def handle_matchid(self,matchid): para={'jsontype': 'odds_allodds.aspx','matchid':matchid} try: response = self.session.get(self.url, timeout=timeout,params=para) if response.status_code == 200 and self.content_type == response.headers['Content-Type']: response = response.json() return response else: logger.info('响应不是json,获取cookie') get_cookie(self.session, self.url, response.text,para=para) return self.handle_matchid(matchid) except Exception as ex: return self.handle_matchid(matchid) def get_rollball_matchid(self): para = {'jsontype': 'odds_inplay.aspx'} try: gids = [] response = self.session.get(self.url,params=para, timeout=timeout) if response.status_code == 200 and self.content_type == response.headers['Content-Type']: response = response.json() for reslut in response: #if reslut.get('matchStatus') != 'Defined': gids.append(reslut.get('matchID')) return gids else: logger.info('响应不是json,获取cookie' + traceback.format_exc()) # set cookie get_cookie(self.session,self.url,response.text) return self.get_rollball_matchid() except Exception as ex: logger.info(ex.args) return self.get_rollball_matchid() def handle_rollball_matchid(self,matchid): para={'jsontype': 'odds_inplay_all.aspx','matchid': matchid} try: response = self.session.get(self.url,params=para, timeout=timeout) if response.status_code == 200 and self.content_type == response.headers['Content-Type']: responses = response.json() for response in responses: if response.get('matchID') == matchid: return response return response else: logger.info('响应不是json,获取cookie' + traceback.format_exc()) get_cookie(self.session, self.url, response.text,para=para) return self.handle_rollball_matchid(matchid) except Exception as ex: return self.handle_rollball_matchid(matchid) def fetch(self): gids = self.get_matchid() print(len(gids)) if not gids: logger.info(f'{self.name}暂无赛事暂停{stop}') time.sleep(stop) for gid in gids: response = self.handle_matchid(gid) item = self.parse_response(response) if item: self.update_one(gid, item) def fetch_rollball(self): gids = self.get_rollball_matchid() if not gids: logger.info(f'{self.name}暂无赛事暂停{rollball_stop}') time.sleep(rollball_stop) for gid in gids: response = self.handle_rollball_matchid(gid) item = self.parse_rollball_response(response) if item: self.update_one(gid,item) def parse_response(self, response): for item in response: if item.get('anyInplaySelling') and item.get('matchStatus') == 'Defined': result = self.parse_current_match(item) return result def parse_rollball_response(self,response): result = self.parse_current_match(response) return result def parse_current_match(self,item): item['updateTime'] = datetime.datetime.now() if not getattr(self,'isrollball'): inplaypools_name = 'definedPools' else: inplaypools_name = 'inplayPools' inplayPools = item.get('inplayPools') remove = [] for key in item: if 'odds' in key: if key[:-4].upper() in inplayPools: pass else: remove.append(key) for key in remove: del item[key] inplay_pools = item.get(inplaypools_name) for inplay in inplay_pools: inplay_key = inplay.lower() + 'odds' odds = {} if item.get(inplay_key) and inplay_key == 'hadodds': # 主客和 temp = item.get(inplay_key) odds['homewin'] = temp.get('H')[4:] odds['awaywin'] = temp.get('A')[4:] odds['draw'] = temp.get('D')[4:] odds['status'] = temp.get('POOLSTATUS') odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'fhaodds': # 半场主客和 temp = item.get(inplay_key) odds['homewin'] = temp.get('H')[4:] odds['awaywin'] = temp.get('A')[4:] odds['draw'] = temp.get('D')[4:] odds['status'] = temp.get('POOLSTATUS') odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'hhaodds': # 让球主客和 temp = item.get(inplay_key) odds['homewin'] = temp.get('H')[4:] odds['awaywin'] = temp.get('A')[4:] odds['draw'] = temp.get('D')[4:] odds['status'] = temp.get('POOLSTATUS') odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'hdcodds': # 让球 temp = item.get(inplay_key) point = temp.get('HG') if '/' in point: slice_point = point.split('/') point = point if slice_point[0] != slice_point[1] else slice_point[0] odds['homewin'] = temp.get('H')[4:] odds['awaywin'] = temp.get('A')[4:] odds['point'] = point odds['status'] = temp.get('POOLSTATUS') odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'hilodds': # 入球大细 temp = item.get(inplay_key) odds['info'] = [] linelist = temp.get('LINELIST') for i in linelist: point = i.get('LINE') if '/' in point: slice_point = point.split('/') point = point if slice_point[0] != slice_point[1] else slice_point[0] odds['info'].append({'gt': i.get('H')[4:],'lt': i.get('L')[4:],'point': point}) odds['status'] = temp['POOLSTATUS'] odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'fhlodds': # 半场入球大细 temp = item.get(inplay_key) odds['info'] = [] linelist = temp.get('LINELIST') for i in linelist: point = i.get('LINE') if '/' in point: slice_point = point.split('/') point = point if slice_point[0] != slice_point[1] else slice_point[0] odds['info'].append({'gt': i.get('H')[4:], 'lt': i.get('L')[4:], 'point': point}) odds['sataus'] = temp['POOLSTATUS'] odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'chlodds': # 角球大细 temp = item.get(inplay_key) odds['info'] = [] linelist = temp.get('LINELIST') for i in linelist: point = i.get('LINE') if '/' in point: slice_point = point.split('/') point = point if slice_point[0] != slice_point[1] else slice_point[0] odds['info'].append({'gt': i.get('H')[4:], 'lt': i.get('L')[4:], 'point': point}) odds['sataus'] = temp['POOLSTATUS'] odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'crsodds': # 波胆 temp = item.get(inplay_key) odds['home'] = [] odds['away'] = [] odds['draw'] = [] map_csrodds = { 'S0100':'home','S0200':'home','S0201':'home','S0300':'home','S0301':'home','S0302':'home','S0400':'home','S0401':'home','S0402':'home','S0500':'home','S0501':'home','S0502':'home', 'S0001':'away','S0002':'away', 'S0102':'away','S0003': 'away', 'S0103': 'away','S0203': 'away', 'S0004': 'away', 'S0104': 'away', 'S0204': 'away', 'S0005': 'away','S0105': 'away', 'S0205': 'away', 'S0000': 'draw','S0101': 'draw','S0202': 'draw','S0303': 'draw', 'SM1MA': 'away','SM1MH': 'home','SM1MD':'draw' } map_other = {'1:A': 'other','1:D': 'other','1:H': 'other',} for key, value in temp.items(): if '@' in value: score = key[2] + ':' + key[-1] score = map_other.get(score) or score info = {'name': score,'odds': value[4:]} odds[map_csrodds.get(key)].append(info) odds['title'] = map_item.get(inplay_key) odds['sataus'] = temp['POOLSTATUS'] item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'fcsodds': # 半场波胆 temp = item.get(inplay_key) odds['home'] = [] odds['away'] = [] odds['draw'] = [] map_csrodds = { 'S0100':'home','S0200':'home','S0201':'home','S0300':'home','S0301':'home','S0302':'home','S0400':'home','S0401':'home','S0402':'home','S0500':'home','S0501':'home','S0502':'home', 'S0001':'away','S0002':'away', 'S0102':'away','S0003': 'away', 'S0103': 'away','S0203': 'away', 'S0004': 'away', 'S0104': 'away', 'S0204': 'away', 'S0005': 'away','S0105': 'away', 'S0205': 'away', 'S0000': 'draw','S0101': 'draw','S0202': 'draw','S0303': 'draw', 'SM1MA': 'away','SM1MH': 'home','SM1MD':'draw' } map_other = {'1:A': 'other','1:D': 'other','1:H': 'other',} for key, value in temp.items(): if '@' in value: score = key[2] + ':' + key[-1] score = map_other.get(score) or score info = {'name': score,'odds': value[4:]} odds[map_csrodds.get(key)].append(info) odds['title'] = map_item.get(inplay_key) odds['status'] = temp['POOLSTATUS'] item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'ntsodds': # 下一队进球 if item.get(inplay_key): descriptions = item.get(inplay_key) odds['info'] = [] for description in descriptions: odds['info'].append({'home':description.get('H')[4:],'away':description.get('A')[4:],'N':description.get('N')[4:]}) odds['status'] = description['POOLSTATUS'] odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'ftsodds': # 第一队入球 temp = item.get(inplay_key) odds['home'] = temp.get('H')[4:] odds['away'] = temp.get('A')[4:] odds['N'] = temp.get('N')[4:] odds['title'] = map_item.get(inplay_key) odds['status'] = temp['POOLSTATUS'] item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'ttgodds': # 总入球 temp = item.get(inplay_key) odds['info'] = [] for key, value in temp.items(): if '@' in value: odds['info'].append({'name': key,'odds': value[4:]}) odds['title'] = map_item.get(inplay_key) odds['status'] = temp['POOLSTATUS'] item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'ooeodds': # 入球单双 temp = item.get(inplay_key) odds['info'] = [{'name': '单','odds': temp.get('O')[4:]},{'name': '双','odds': temp.get('E')[4:]}] odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'hftodds': # 半全场 temp = item.get(inplay_key) map_hftodds = { 'HD': '主-和','HA': '主-客','HH': '主-主', 'AD': '客-和','AH': '客-主','AA': '客-客', 'DH': '和-主','DA': '和-客','DD': '和-和'} odds['info'] = [] for key, value in temp.items(): if '@' in value: odds['info'].append({'name': key,'odds': value[4:],'CH':map_hftodds.get(key)}) odds['title'] = map_item.get(inplay_key) item[inplay_key] = odds elif item.get(inplay_key) and inplay_key == 'spcodds': #特别项目 descriptions = item.get(inplay_key) info = [] for description in descriptions: desc = {} desc['title'] = map_item.get(inplay_key) desc['item'] = description.get('ITEM') desc['inplay'] = description.get('INPLAY') desc['itemech'] = description.get('ITEMCH') desc['itemeen'] = description.get('ITEMEN') desc['status'] = description.get('POOLSTATUS') desc['info'] = [] for sellist in description['SELLIST']: sel = {'odds': sellist['ODDS'][4:],'sel': sellist['SEL'],'itemech': sellist.get('CONTENTCH'),'selstatus':sellist.get('SELSTATUS') } desc['info'].append(sel) info.append(desc) item[inplay_key] = info elif item.get(inplay_key) and inplay_key == 'fgsodds': # 首名入球 description = item.get(inplay_key) desc = {} desc['title'] = map_item.get(inplay_key) desc['inplay'] = description.get('INPLAY') desc['status'] = description.get('POOLSTATUS') desc['info'] = [] for sellist in description['SELLIST']: sel = {'odds': sellist['ODDS'][4:], 'sel': sellist['SEL'], 'itemech': sellist.get('CONTENTCH'), 'itemen': sellist.get('CONTENTEN')} desc['info'].append(sel) item[inplay_key] = desc elif item.get(inplay_key) and inplay_key == 'tqlodds': #晋级队伍 description = item.get(inplay_key) desc = {} desc['title'] = map_item.get(inplay_key) desc['inplay'] = description.get('INPLAY') desc['status'] = description.get('POOLSTATUS') desc['homewin'] = description.get('H')[4:] desc['awaywin'] = description.get('A')[4:] item[inplay_key] = desc item['sportid'] = 1 item['updateTime'] = datetime.datetime.now() if item.get('channel'): del item['channel'] del item['matchID'] return item def champion(self,param): try: response = self.session.get(self.url,params=param) if response.status_code == 200 and self.content_type == response.headers['Content-Type']: response = response.json() return response else: logger.info('响应不是json,获取cookie') # set cookie get_cookie(self.session, self.url, response.text, param) return self.champion(param) except Exception as ex: logger.info(traceback.format_exc()) def fetch_champion(self): params = [ {'jsontype': 'odds_chp.aspx'}, {'jsontype': 'tournament.aspx', 'tourn': '1644'}, #{'jsontype': 'tournament.aspx', 'tourn': '1658'} ] for i in params: response = self.champion(i) if isinstance(response,list): key = 'chpodds' for item in response: if item.get(key) : odds = deepcopy(item.get(key)) sellist = item[key]['SELLIST'] del item[key]['SELLIST'] info = [] for sell in sellist: if sell['ODDS'][4:] != 'LSE': info.append({'name': sell.get('CONTENTCH'),'odds': sell.get('ODDS')[4:]}) item[key]['info'] = info odds['title'] = map_item[key] tournamentID = item.get('tournamentID') jsontype = {'tournamentID':tournamentID,'jsontype': key} item['updateTime'] = datetime.datetime.now() self.update_one_by_jsontype(jsontype,item) elif isinstance(response,dict): tps_key = 'tpsodds' chp_key = 'chpodds' if response.get(tps_key): tpsodds = response.get(tps_key) for players in tpsodds: info = [] sellist = players['SELLIST'] del players['SELLIST'] for sell in sellist: if sell['ODDS'][4:] != 'LSE': info.append({'name': sell.get('CONTENTCH'),'odds': sell.get('ODDS')[4:]}) players['info'] = info response[tps_key] = tpsodds if response.get(chp_key): chpodds = response.get(chp_key) sellist = chpodds['SELLIST'] del chpodds['SELLIST'] info = [] for sell in sellist: if sell['ODDS'][4:] != 'LSE': info.append({'name': sell.get('CONTENTCH'), 'odds': sell.get('ODDS')[4:]}) chpodds['info'] = info response[chp_key] = chpodds tournamentID = response.get('tournamentID') jsontype = {'tournamentID': tournamentID, 'jsontype': 'league'} response['updateTime'] = datetime.datetime.now() self.update_one_by_jsontype(jsontype, response) class Soccer(Prepare): def __init__(self,col=None,isrollball=False,name=None): super(Soccer,self).__init__(col) self.name = name self.isrollball = isrollball self.session = requests.Session() self.session.headers.update(headers) self.json_type = { 'jsontype': 'odds_allodds.aspx', 'matchid': 'default'} if __name__ == '__main__': soccer = Soccer(col='rollball',isrollball=True,name='足球走地盘') soccer2 = Soccer(col='sports',isrollball=False,name='足球') soccer3 = Soccer(col='sports', isrollball=False, name='足球') def main1(): while True: soccer.fetch_rollball() time.sleep(5) def main2(): while True: #soccer2.fetch() soccer3.fetch_champion() time.sleep(100) import threading t1 = threading.Thread(target=main1,) t2 = threading.Thread(target=main2, ) t1.start()
[ "threading.Thread" ]
[((22897, 22927), 'threading.Thread', 'threading.Thread', ([], {'target': 'main1'}), '(target=main1)\n', (22913, 22927), False, 'import threading\n'), ((22939, 22969), 'threading.Thread', 'threading.Thread', ([], {'target': 'main2'}), '(target=main2)\n', (22955, 22969), False, 'import threading\n')]
from __future__ import annotations import asyncio import json import logging import os import pathlib import signal import sys import textwrap import traceback from concurrent.futures import ProcessPoolExecutor from dataclasses import dataclass, field from typing import (Any, ClassVar, Dict, Generator, Iterable, List, Optional, Tuple, Union) import apischema from . import common, dbtemplate, graph, settings, util from .access_security import AccessSecurityState from .asyn import AsynState from .autosave import AutosaveState from .common import (AnyPath, FullLoadContext, IocMetadata, IocshCmdArgs, IocshRedirect, IocshResult, IocshScript, LoadContext, MutableLoadContext, PVRelations, RecordDefinitionAndInstance, RecordInstance, ShellStateHandler, WhatRecord, time_context) from .db import Database, DatabaseLoadFailure, LinterResults, RecordType from .format import FormatContext from .iocsh import parse_iocsh_line from .macro import MacroContext from .motor import MotorState from .streamdevice import StreamDeviceState logger = logging.getLogger(__name__) _handler = ShellStateHandler.generic_handler_decorator @dataclass class ShellState(ShellStateHandler): """ IOC shell state container. Contains hooks for commands and state information. This base state handler should only handle epics base-defined IOC shell commands, including: paths, variables, database loading, and IOC initialization. It is the top-level state container, which sub handlers should rely on for things like loading files and other core state information. Attributes ---------- prompt : str The prompt - PS1 - as in "epics>". variables : dict Shell variables (not environment variables). string_encoding : str String encoding for byte strings and files. macro_context : MacroContext Macro context for commands that are evaluated. standin_directories : dict Rewrite hard-coded directory prefixes by setting:: standin_directories = {"/replace_this/": "/with/this"} loaded_files : Dict[str, str] Files loaded, mapped to a hash of their contents. working_directory : pathlib.Path Current working directory. database_definition : Database Loaded database definition (dbd). database : Dict[str, RecordInstance] The IOC database of records. pva_database : Dict[str, RecordInstance] The IOC database of PVAccess groups. aliases : Dict[str, str] Alias name to record name. load_context : List[MutableLoadContext] Current loading context stack (e.g., ``st.cmd`` then ``common_startup.cmd``). Modified in place as scripts are evaluated. """ prompt: str = "epics>" variables: Dict[str, str] = field(default_factory=dict) string_encoding: str = "latin-1" ioc_initialized: bool = False standin_directories: Dict[str, str] = field(default_factory=dict) working_directory: pathlib.Path = field( default_factory=lambda: pathlib.Path.cwd(), ) aliases: Dict[str, str] = field(default_factory=dict) database_definition: Optional[Database] = None database: Dict[str, RecordInstance] = field(default_factory=dict) pva_database: Dict[str, RecordInstance] = field(default_factory=dict) load_context: List[MutableLoadContext] = field(default_factory=list) loaded_files: Dict[str, str] = field(default_factory=dict) macro_context: MacroContext = field( default_factory=MacroContext, metadata=apischema.metadata.skip ) ioc_info: IocMetadata = field(default_factory=IocMetadata) db_add_paths: List[pathlib.Path] = field(default_factory=list) # Sub-state handlers: access_security: AccessSecurityState = field(default_factory=AccessSecurityState) asyn: AsynState = field(default_factory=AsynState) autosave: AutosaveState = field(default_factory=AutosaveState) motor: MotorState = field(default_factory=MotorState) streamdevice: StreamDeviceState = field(default_factory=StreamDeviceState) _jinja_format_: ClassVar[Dict[str, str]] = { "console": textwrap.dedent( """\ {{ obj | classname }}: """.rstrip(), ), "console-verbose": textwrap.dedent( """\ {{ obj | classname }}: """.rstrip(), ) } def __post_init__(self): super().__post_init__() self.macro_context.string_encoding = self.string_encoding @property def sub_handlers(self) -> List[ShellStateHandler]: """Handlers which contain their own state.""" return [ self.access_security, self.asyn, self.autosave, self.motor, self.streamdevice, ] def load_file(self, filename: AnyPath) -> Tuple[pathlib.Path, str]: """Load a file, record its hash, and return its contents.""" filename = self._fix_path(filename) filename = filename.resolve() shasum, contents = util.read_text_file_with_hash( filename, encoding=self.string_encoding ) self.loaded_files[str(filename)] = shasum self.ioc_info.loaded_files[str(filename)] = shasum return filename, contents def _handle_input_redirect( self, redir: IocshRedirect, shresult: IocshResult, recurse: bool = True, raise_on_error: bool = False, ): try: filename, contents = self.load_file(redir.name) except Exception as ex: shresult.error = f"{type(ex).__name__}: {redir.name}" yield shresult return yield shresult yield from self.interpret_shell_script_text( contents.splitlines(), recurse=recurse, name=filename ) def interpret_shell_line(self, line, recurse=True, raise_on_error=False): """Interpret a single shell script line.""" shresult = parse_iocsh_line( line, context=self.get_load_context(), prompt=self.prompt, macro_context=self.macro_context, string_encoding=self.string_encoding, ) input_redirects = [redir for redir in shresult.redirects if redir.mode == "r"] if shresult.error: yield shresult elif input_redirects: if recurse: yield from self._handle_input_redirect( input_redirects[0], shresult, recurse=recurse, raise_on_error=raise_on_error, ) elif shresult.argv: try: result = self._handle_command(*shresult.argv) if result: # Only set if not-None to speed up serialization shresult.result = result except Exception as ex: if raise_on_error: raise ex_details = traceback.format_exc() shresult.error = f"Failed to execute: {ex}:\n{ex_details}" yield shresult if isinstance(shresult.result, IocshCmdArgs): yield from self.interpret_shell_line( shresult.result.command, recurse=recurse ) else: # Otherwise, nothing to do yield shresult def interpret_shell_script( self, filename: Union[pathlib.Path, str], recurse: bool = True, raise_on_error: bool = False, ) -> Generator[IocshResult, None, None]: """Load and interpret a shell script named ``filename``.""" filename, contents = self.load_file(filename) yield from self.interpret_shell_script_text( contents.splitlines(), name=str(filename), recurse=recurse, raise_on_error=raise_on_error, ) def interpret_shell_script_text( self, lines: Iterable[str], name: str = "unknown", recurse: bool = True, raise_on_error: bool = False, ) -> Generator[IocshResult, None, None]: """Interpret a shell script named ``name`` with ``lines`` of text.""" load_ctx = MutableLoadContext(str(name), 0) try: self.load_context.append(load_ctx) for lineno, line in enumerate(lines, 1): load_ctx.line = lineno yield from self.interpret_shell_line( line, recurse=recurse, raise_on_error=raise_on_error, ) finally: self.load_context.remove(load_ctx) # for rec in list(self.database.values()) + list(self.pva_database.values()): # try: # self.annotate_record(rec) # except Exception: # logger.exception("Failed to annotate record: %s", rec.name) def get_load_context(self) -> FullLoadContext: """Get a FullLoadContext tuple representing where we are now.""" if not self.load_context: return tuple() return tuple(ctx.to_load_context() for ctx in self.load_context) def _handle_command(self, command, *args): """Handle IOC shell 'command' with provided arguments.""" handler = self._handlers.get(command, None) if handler is not None: return handler(*args) return self.unhandled(command, args) def _fix_path(self, filename: AnyPath) -> pathlib.Path: """ Makes filename an absolute path with respect to the working directory. Also replaces standin directories, if provided an absolute path. """ filename = str(filename) if os.path.isabs(filename): for from_, to in self.standin_directories.items(): if filename.startswith(from_): _, suffix = filename.split(from_, 1) return pathlib.Path(to + suffix) return self.working_directory / filename @property def db_include_paths(self) -> List[pathlib.Path]: """Database include paths (EPICS_DB_INCLUDE_PATH).""" env_paths = self.paths_from_env_var("EPICS_DB_INCLUDE_PATH") if not env_paths: return [self.working_directory] + self.db_add_paths return env_paths + self.db_add_paths def paths_from_env_var( self, env_var: str, *, default: Optional[str] = None ) -> List[pathlib.Path]: """Paths from an environment variable (or macro).""" env_var = self.macro_context.get(env_var, default) or "" return [ (self.working_directory / pathlib.Path(path)).resolve() # TODO: this is actually OS-dependent (: on linux, ; on Windows) for path in env_var.split(":") ] def _fix_path_with_search_list( self, filename: Union[str, pathlib.Path], include_paths: List[pathlib.Path], ) -> pathlib.Path: """Given a list of paths, find ``filename``.""" filename = str(filename) if not include_paths or "/" in filename or "\\" in filename: # Include path unset or even something resembling a nested path # automatically is used as-is return self.working_directory / filename for path in include_paths: option = path / filename if option.exists() and option.is_file(): return option paths = list(str(path) for path in include_paths) raise FileNotFoundError( f"File {filename!r} not found in search path: {paths}" ) def unhandled(self, command, args): ... # return f"No handler for handle_{command}" @_handler def handle_iocshRegisterVariable(self, variable: str, value: str = ""): self.variables[variable] = value return f"Registered variable: {variable!r}={value!r}" def env_set_EPICS_BASE(self, path): # TODO: slac-specific path = str(pathlib.Path(path).resolve()) version_prefixes = [ "/reg/g/pcds/epics/base/", "/cds/group/pcds/epics/base/", ] for prefix in version_prefixes: if path.startswith(prefix): path = path[len(prefix):] if "/" in path: path = path.split("/")[0] version = path.lstrip("R") if self.ioc_info.base_version == settings.DEFAULT_BASE_VERSION: self.ioc_info.base_version = version return f"Set base version: {version}" return ( f"Found version ({version}) but version already specified:" f" {self.ioc_info.base_version}" ) @_handler def handle_epicsEnvSet(self, variable: str, value: str = ""): self.macro_context.define(**{variable: value}) hook = getattr(self, f"env_set_{variable}", None) if hook and callable(hook): hook_result = hook(value) if hook_result: return { "hook": hook_result, } @_handler def handle_epicsEnvShow(self): return self.macro_context.get_macros() def handle_iocshCmd(self, command: str = "", *_): # TODO: odd return type, used below return IocshCmdArgs(context=self.get_load_context(), command=command) @_handler def handle_cd(self, path: str = ""): if not path: raise RuntimeError("Invalid directory path, ignored") path = self._fix_path(path) if path.is_absolute(): new_dir = path else: new_dir = self.working_directory / path if not new_dir.exists(): raise RuntimeError(f"Path does not exist: {new_dir}") self.working_directory = new_dir.resolve() os.environ["PWD"] = str(self.working_directory) return { "result": f"New working directory: {self.working_directory}" } handle_chdir = handle_cd @_handler def handle_iocInit(self): if self.ioc_initialized: return { "success": False, "error": "Already initialized", } result = { "success": True, } for handler in self.sub_handlers: handler_result = handler.pre_ioc_init() result.update(handler_result or {}) self.ioc_initialized = True for handler in self.sub_handlers: handler_result = handler.post_ioc_init() result.update(handler_result or {}) return result @_handler def handle_dbLoadDatabase(self, dbd: str, path: str = "", substitutions: str = ""): if self.ioc_initialized: raise RuntimeError("Database cannot be loaded after iocInit") if self.database_definition: # TODO: technically this is allowed; we'll need to update # raise RuntimeError("dbd already loaded") return "whatrecord: TODO multiple dbLoadDatabase" dbd_path = self._fix_path_with_search_list(dbd, self.db_include_paths) fn, contents = self.load_file(dbd_path) macro_context = MacroContext(use_environment=False) macro_context.define_from_string(substitutions or "") self.database_definition = Database.from_string( contents, version=self.ioc_info.database_version_spec, filename=fn, macro_context=macro_context, ) for addpath in self.database_definition.addpaths: for path in addpath.path.split(os.pathsep): # TODO: OS-dependent self.db_add_paths.append((dbd_path.parent / path).resolve()) self.aliases.update(self.database_definition.aliases) return {"result": f"Loaded database: {fn}"} @_handler def handle_dbLoadTemplate(self, filename: str, macros: str = ""): filename = self._fix_path_with_search_list(filename, self.db_include_paths) filename, contents = self.load_file(filename) # TODO this should be multiple load calls for the purposes of context result = { "total_records": 0, "total_groups": 0, "loaded_files": [], } template = dbtemplate.TemplateSubstitution.from_string(contents, filename=filename) for sub in template.substitutions: database_contents = sub.expand_file(search_paths=self.db_include_paths) # TODO loading file twice (ensure it gets added to the loaded_files list) self.load_file(sub.filename) lint = self._load_database( filename=str(sub.filename), contents=database_contents, macros=macros, context=self.get_load_context() + sub.context, ) info = { "filename": sub.filename, "macros": sub.macros, "records": len(lint.records), "groups": len(lint.pva_groups), "lint": lint, } result["total_records"] += len(lint.records) result["total_groups"] += len(lint.pva_groups) result["loaded_files"].append(info) return result def _load_database( self, filename: str, contents: str, macros: str, context: FullLoadContext ) -> LinterResults: macro_context = MacroContext(use_environment=False) macros = macro_context.define_from_string(macros or "") try: lint = LinterResults.from_database_string( db=contents, dbd=self.database_definition, db_filename=filename, macro_context=macro_context, version=self.ioc_info.database_version_spec, ) except Exception as ex: # TODO move this around raise DatabaseLoadFailure( f"Failed to load {filename}: {type(ex).__name__} {ex}" ) from ex db: Database = lint.db for name, rec in db.records.items(): if name not in self.database: self.database[name] = rec rec.context = context + rec.context rec.owner = self.ioc_info.name else: entry = self.database[name] entry.context = entry.context + rec.context entry.fields.update(rec.fields) # entry.owner = self.ioc_info.name ? for name, rec in db.pva_groups.items(): if name not in self.pva_database: self.pva_database[name] = rec rec.context = context + rec.context rec.owner = self.ioc_info.name else: entry = self.database[name] entry.context = entry.context + rec.context entry.fields.update(rec.fields) # entry.owner = self.ioc_info.name ? self.aliases.update(db.aliases) for addpath in db.addpaths: for path in addpath.path.split(os.pathsep): # TODO: OS-dependent self.db_add_paths.append((db.parent / path).resolve()) return lint @_handler def handle_dbLoadRecords(self, filename: str, macros: str = ""): if not self.database_definition: raise RuntimeError("dbd not yet loaded") if self.ioc_initialized: raise RuntimeError("Records cannot be loaded after iocInit") filename = self._fix_path_with_search_list(filename, self.db_include_paths) filename, contents = self.load_file(filename) lint = self._load_database( filename=filename, contents=contents, macros=macros or "", context=self.get_load_context() ) return { "loaded_records": len(lint.records), "loaded_groups": len(lint.pva_groups), "lint": lint, } def annotate_record(self, record: RecordInstance) -> Optional[Dict[str, Any]]: """Hook to annotate a record after being loaded.""" for handler in self.sub_handlers: try: annotation = handler.annotate_record(record) except Exception: logger.exception( "Record annotation failed for %s with handler %s", record.name, type(handler).__name__ ) else: if annotation is not None: record.metadata[handler.metadata_key] = annotation @_handler def handle_dbl(self, rtyp: str = "", fields: str = ""): ... @_handler def handle_NDPvaConfigure( self, portName: str, queueSize: int = 0, blockingCallbacks: str = "", NDArrayPort: str = "", NDArrayAddr: str = "", pvName: str = "", maxBuffers: int = 0, maxMemory: int = 0, priority: int = 0, stackSize: int = 0, ): """Implicitly creates a PVA group named ``pvName``.""" metadata = { "portName": portName or "", "queueSize": queueSize or "", "blockingCallbacks": blockingCallbacks or "", "NDArrayPort": NDArrayPort or "", "NDArrayAddr": NDArrayAddr or "", "pvName": pvName or "", "maxBuffers": maxBuffers or "", "maxMemory": maxMemory or "", "priority": priority or "", "stackSize": stackSize or "", } self.pva_database[pvName] = RecordInstance( context=self.get_load_context(), name=pvName, record_type="PVA", fields={}, is_pva=True, metadata={"areaDetector": metadata}, ) return metadata @dataclass class ScriptContainer: """ Aggregate container for any number of LoadedIoc instances. Combines databases, sets of loaded files ease of querying. """ database: Dict[str, RecordInstance] = field(default_factory=dict) aliases: Dict[str, str] = field(default_factory=dict) pva_database: Dict[str, RecordInstance] = field(default_factory=dict) scripts: Dict[str, LoadedIoc] = field(default_factory=dict) startup_script_to_ioc: Dict[str, str] = field(default_factory=dict) #: absolute filename path to sha loaded_files: Dict[str, str] = field(default_factory=dict) record_types: Dict[str, RecordType] = field(default_factory=dict) pv_relations: PVRelations = field(default_factory=dict) def add_loaded_ioc(self, loaded: LoadedIoc): ioc_name = loaded.metadata.name self.scripts[ioc_name] = loaded self.startup_script_to_ioc[str(loaded.metadata.script)] = ioc_name # TODO: IOCs will have conflicting definitions of records self.aliases.update(loaded.shell_state.aliases) if loaded.shell_state.database_definition: self.record_types.update( loaded.shell_state.database_definition.record_types ) graph.combine_relations( self.pv_relations, self.database, loaded.pv_relations, loaded.shell_state.database, record_types=self.record_types, aliases=self.aliases, ) self.database.update(loaded.shell_state.database) self.pva_database.update(loaded.shell_state.pva_database) self.loaded_files.update(loaded.shell_state.loaded_files) def whatrec( self, rec: str, field: Optional[str] = None, include_pva: bool = True, format_option: str = "console", file=sys.stdout, ) -> List[WhatRecord]: fmt = FormatContext() result = [] for name, loaded in self.scripts.items(): info: WhatRecord = loaded.whatrec(rec, field, include_pva=include_pva) if info is not None: info.ioc = loaded.metadata for match in [info.record, info.pva_group]: if file is not None and match is not None: print(fmt.render_object(match, format_option), file=file) result.append(info) return result @dataclass class LoadedIoc: name: str path: pathlib.Path metadata: IocMetadata shell_state: ShellState script: IocshScript load_failure: bool = False pv_relations: PVRelations = field(default_factory=dict) _jinja_format_: ClassVar[Dict[str, str]] = { "console": textwrap.dedent( """\ {{ obj | classname }}: path: {{ path }} metadata: {% set metadata = render_object(metadata, "console") %} {{ metadata | indent(4) }} shell_state: {% set shell_state = render_object(shell_state, "console") %} {{ shell_state | indent(4) }} script: {% set script = render_object(script, "console") %} {{ script | indent(4) }} load_failure: {{ load_failure }} """.rstrip(), ), "console-verbose": textwrap.dedent( """\ {{ obj | classname }}: path: {{ path }} metadata: {% set metadata = render_object(metadata, "console-verbose") %} {{ metadata | indent(4) }} shell_state: {% set shell_state = render_object(shell_state, "console-verbose") %} {{ shell_state | indent(4) }} script: {% set script = render_object(script, "console-verbose") %} {{ script | indent(4) }} load_failure: {{ load_failure }} pv_relations: {{ pv_relations }} """.rstrip(), ) } @classmethod def _json_from_cache(cls, md: IocMetadata) -> Optional[dict]: try: with open(md.ioc_cache_filename, "rb") as fp: return json.load(fp) except FileNotFoundError: ... except json.decoder.JSONDecodeError: # Truncated output file, perhaps ... @classmethod def from_cache(cls, md: IocMetadata) -> Optional[LoadedIoc]: json_dict = cls._json_from_cache(md) if json_dict is not None: return apischema.deserialize(cls, json_dict) def save_to_cache(self) -> bool: if not settings.CACHE_PATH: return False with open(self.metadata.ioc_cache_filename, "wt") as fp: json.dump(apischema.serialize(self), fp=fp) return True @classmethod def from_errored_load( cls, md: IocMetadata, load_failure: IocLoadFailure ) -> LoadedIoc: exception_line = f"{load_failure.ex_class}: {load_failure.ex_message}" error_lines = [exception_line] + load_failure.traceback.splitlines() script = IocshScript( path=str(md.script), lines=tuple( IocshResult(line=line, context=(LoadContext("error", lineno),)) for lineno, line in enumerate(error_lines, 1) ), ) md.metadata["exception_class"] = load_failure.ex_class md.metadata["exception_message"] = load_failure.ex_message md.metadata["traceback"] = load_failure.traceback md.metadata["load_failure"] = True return cls( name=md.name, path=md.script, metadata=md, shell_state=ShellState(), script=script, load_failure=True, ) @classmethod def from_metadata(cls, md: IocMetadata) -> LoadedIoc: sh = ShellState(ioc_info=md) sh.working_directory = md.startup_directory sh.macro_context.define(**md.macros) sh.standin_directories = md.standin_directories or {} # It's not enough to chdir, as we can rely on the environment variable # in shell scripts: os.environ["PWD"] = str(md.startup_directory) script = IocshScript.from_metadata(md, sh=sh) return cls( name=md.name, path=md.script, metadata=md, shell_state=sh, script=script, pv_relations=graph.build_database_relations(sh.database), ) def whatrec( self, rec: str, field: Optional[str] = None, include_pva: bool = True ) -> Optional[WhatRecord]: """Get record information, optionally including PVAccess results.""" state = self.shell_state v3_inst = state.database.get(state.aliases.get(rec, rec), None) pva_inst = state.pva_database.get(rec, None) if include_pva else None if not v3_inst and not pva_inst: return what = WhatRecord( name=rec, ioc=self.metadata, record=None, pva_group=None, ) if v3_inst is not None: if not state.database_definition: defn = None else: defn = state.database_definition.record_types.get( v3_inst.record_type, None ) what.menus = state.database_definition.menus # but what about device types and such? state.annotate_record(v3_inst) what.record = RecordDefinitionAndInstance(defn, v3_inst) if pva_inst is not None: what.pva_group = pva_inst return what def load_cached_ioc( md: IocMetadata, allow_failed_load: bool = False, ) -> Optional[LoadedIoc]: cached_md = md.from_cache() if cached_md is None: logger.debug("Cached metadata unavailable %s", md.name) return None if md._cache_key != cached_md._cache_key: logger.error("Cache key mismatch?! %s %s", md._cache_key, cached_md._cache_key) return None if allow_failed_load and ( cached_md.metadata.get("load_failure") or md.looks_like_sh ): logger.debug( "%s allow_failed_load=True; %s, md.looks_like_sh=%s", md.name, cached_md.metadata.get("load_failure"), md.looks_like_sh, ) elif not cached_md.is_up_to_date(): logger.debug("%s is not up-to-date", md.name) return try: logger.debug("%s is up-to-date; load from cache", md.name) return LoadedIoc._json_from_cache(cached_md) except FileNotFoundError: logger.error("%s is noted as up-to-date; but cache file missing", md.name) @dataclass class IocLoadFailure: ex_class: str ex_message: str traceback: str @dataclass class IocLoadResult: identifier: Union[int, str] load_time: float cache_hit: bool result: Union[IocLoadFailure, str] async def async_load_ioc( identifier: Union[int, str], md: IocMetadata, standin_directories, use_gdb: bool = True, use_cache: bool = True, ) -> IocLoadResult: """ Helper function for loading an IOC in a subprocess and relying on the cache. """ if not settings.CACHE_PATH: use_cache = False with time_context() as ctx: try: md.standin_directories.update(standin_directories) if use_cache: cached_ioc = load_cached_ioc(md) if cached_ioc: return IocLoadResult( identifier=identifier, load_time=ctx(), cache_hit=True, result="use_cache" ) loaded = LoadedIoc.from_metadata(md) if use_gdb: await md.get_binary_information() if use_cache: loaded.metadata.save_to_cache() loaded.save_to_cache() # Avoid pickling massive JSON blob; instruct server to load # from cache with token 'use_cache' serialized = "use_cache" else: serialized = apischema.serialize(loaded) except Exception as ex: return IocLoadResult( identifier=identifier, load_time=ctx(), cache_hit=False, result=IocLoadFailure( ex_class=type(ex).__name__, ex_message=str(ex), traceback=traceback.format_exc(), ), ) return IocLoadResult( identifier=identifier, load_time=ctx(), cache_hit=False, result=serialized, ) def _load_ioc(identifier, md, standin_directories, use_gdb=True, use_cache=True) -> IocLoadResult: return asyncio.run( async_load_ioc( identifier=identifier, md=md, standin_directories=standin_directories, use_gdb=use_gdb, use_cache=use_cache ) ) def _sigint_handler(signum, frame): logger.error("Subprocess killed with SIGINT; exiting.") sys.exit(1) def _process_init(): signal.signal(signal.SIGINT, _sigint_handler) async def load_startup_scripts_with_metadata( *md_items, standin_directories=None, processes: int = 8, use_gdb: bool = True, ) -> ScriptContainer: """ Load all given startup scripts into a shared ScriptContainer. Parameters ---------- *md_items : list of IocMetadata List of IOC metadata. standin_directories : dict Stand-in/substitute directory mapping. processes : int The number of processes to use when loading. """ total_files = len(md_items) total_child_load_time = 0.0 with time_context() as total_time, ProcessPoolExecutor( max_workers=processes, initializer=_process_init ) as executor: coros = [ asyncio.wrap_future( executor.submit( _load_ioc, identifier=idx, md=md, standin_directories=standin_directories, use_gdb=use_gdb ) ) for idx, md in enumerate(md_items) ] for coro in asyncio.as_completed(coros): try: load_result = await coro md = md_items[load_result.identifier] except Exception as ex: logger.exception( "Internal error while loading: %s: %s [server %.1f s]", type(ex).__name__, ex, total_time(), ) continue use_cache = load_result.result == "use_cache" if not use_cache: loaded = load_result.result else: try: loaded = load_cached_ioc(md, allow_failed_load=True) if loaded is None: raise ValueError("Cache entry is empty?") except Exception as ex: logger.exception( "Internal error while loading cached IOC from disk: " "%s: %s [server %.1f s]", type(ex).__name__, ex, total_time(), ) continue total_child_load_time += load_result.load_time if isinstance(loaded, IocLoadFailure): failure_result: IocLoadFailure = loaded logger.error( "Failed to load %s in subprocess: %s " "[%.1f s; server %.1f]: %s\n%s", md.name or md.script, failure_result.ex_class, load_result.load_time, total_time(), failure_result.ex_message, ( failure_result.traceback if failure_result.ex_class != "FileNotFoundError" else "" ), ) if md.base_version == settings.DEFAULT_BASE_VERSION: md.base_version = "unknown" yield md, LoadedIoc.from_errored_load(md, loaded) continue with time_context() as ctx: loaded_ioc = apischema.deserialize(LoadedIoc, loaded) logger.info( "Child loaded %s%s in %.1f s, server deserialized in %.1f s", md.name or md.script, " from cache" if load_result.cache_hit else "", load_result.load_time, ctx(), ) yield md, loaded_ioc logger.info( "Loaded %d startup scripts in %.1f s (wall time) with %d process(es)", total_files, total_time(), processes, ) logger.info( "Child processes reported taking a total of %.1f " "sec, the total time on %d process(es)", total_child_load_time, processes, ) # TODO: apischema skip still requires forwardref to exist? common.ShellState = ShellState
[ "logging.getLogger", "apischema.deserialize", "signal.signal", "traceback.format_exc", "os.path.isabs", "pathlib.Path", "pathlib.Path.cwd", "apischema.serialize", "concurrent.futures.ProcessPoolExecutor", "sys.exit", "json.load", "dataclasses.field", "asyncio.as_completed" ]
[((1147, 1174), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1164, 1174), False, 'import logging\n'), ((2900, 2927), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (2905, 2927), False, 'from dataclasses import dataclass, field\n'), ((3041, 3068), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (3046, 3068), False, 'from dataclasses import dataclass, field\n'), ((3202, 3229), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (3207, 3229), False, 'from dataclasses import dataclass, field\n'), ((3323, 3350), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (3328, 3350), False, 'from dataclasses import dataclass, field\n'), ((3397, 3424), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (3402, 3424), False, 'from dataclasses import dataclass, field\n'), ((3470, 3497), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (3475, 3497), False, 'from dataclasses import dataclass, field\n'), ((3533, 3560), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (3538, 3560), False, 'from dataclasses import dataclass, field\n'), ((3595, 3664), 'dataclasses.field', 'field', ([], {'default_factory': 'MacroContext', 'metadata': 'apischema.metadata.skip'}), '(default_factory=MacroContext, metadata=apischema.metadata.skip)\n', (3600, 3664), False, 'from dataclasses import dataclass, field\n'), ((3707, 3741), 'dataclasses.field', 'field', ([], {'default_factory': 'IocMetadata'}), '(default_factory=IocMetadata)\n', (3712, 3741), False, 'from dataclasses import dataclass, field\n'), ((3781, 3808), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (3786, 3808), False, 'from dataclasses import dataclass, field\n'), ((3879, 3921), 'dataclasses.field', 'field', ([], {'default_factory': 'AccessSecurityState'}), '(default_factory=AccessSecurityState)\n', (3884, 3921), False, 'from dataclasses import dataclass, field\n'), ((3944, 3976), 'dataclasses.field', 'field', ([], {'default_factory': 'AsynState'}), '(default_factory=AsynState)\n', (3949, 3976), False, 'from dataclasses import dataclass, field\n'), ((4007, 4043), 'dataclasses.field', 'field', ([], {'default_factory': 'AutosaveState'}), '(default_factory=AutosaveState)\n', (4012, 4043), False, 'from dataclasses import dataclass, field\n'), ((4068, 4101), 'dataclasses.field', 'field', ([], {'default_factory': 'MotorState'}), '(default_factory=MotorState)\n', (4073, 4101), False, 'from dataclasses import dataclass, field\n'), ((4140, 4180), 'dataclasses.field', 'field', ([], {'default_factory': 'StreamDeviceState'}), '(default_factory=StreamDeviceState)\n', (4145, 4180), False, 'from dataclasses import dataclass, field\n'), ((22348, 22375), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22353, 22375), False, 'from dataclasses import dataclass, field\n'), ((22406, 22433), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22411, 22433), False, 'from dataclasses import dataclass, field\n'), ((22480, 22507), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22485, 22507), False, 'from dataclasses import dataclass, field\n'), ((22544, 22571), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22549, 22571), False, 'from dataclasses import dataclass, field\n'), ((22616, 22643), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22621, 22643), False, 'from dataclasses import dataclass, field\n'), ((22716, 22743), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22721, 22743), False, 'from dataclasses import dataclass, field\n'), ((22786, 22813), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22791, 22813), False, 'from dataclasses import dataclass, field\n'), ((22846, 22873), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (22851, 22873), False, 'from dataclasses import dataclass, field\n'), ((24735, 24762), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (24740, 24762), False, 'from dataclasses import dataclass, field\n'), ((33231, 33242), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (33239, 33242), False, 'import sys\n'), ((33270, 33315), 'signal.signal', 'signal.signal', (['signal.SIGINT', '_sigint_handler'], {}), '(signal.SIGINT, _sigint_handler)\n', (33283, 33315), False, 'import signal\n'), ((9883, 9906), 'os.path.isabs', 'os.path.isabs', (['filename'], {}), '(filename)\n', (9896, 9906), False, 'import os\n'), ((33915, 33984), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': 'processes', 'initializer': '_process_init'}), '(max_workers=processes, initializer=_process_init)\n', (33934, 33984), False, 'from concurrent.futures import ProcessPoolExecutor\n'), ((34337, 34364), 'asyncio.as_completed', 'asyncio.as_completed', (['coros'], {}), '(coros)\n', (34357, 34364), False, 'import asyncio\n'), ((26560, 26597), 'apischema.deserialize', 'apischema.deserialize', (['cls', 'json_dict'], {}), '(cls, json_dict)\n', (26581, 26597), False, 'import apischema\n'), ((3146, 3164), 'pathlib.Path.cwd', 'pathlib.Path.cwd', ([], {}), '()\n', (3162, 3164), False, 'import pathlib\n'), ((26209, 26222), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (26218, 26222), False, 'import json\n'), ((26785, 26810), 'apischema.serialize', 'apischema.serialize', (['self'], {}), '(self)\n', (26804, 26810), False, 'import apischema\n'), ((32242, 32269), 'apischema.serialize', 'apischema.serialize', (['loaded'], {}), '(loaded)\n', (32261, 32269), False, 'import apischema\n'), ((36497, 36537), 'apischema.deserialize', 'apischema.deserialize', (['LoadedIoc', 'loaded'], {}), '(LoadedIoc, loaded)\n', (36518, 36537), False, 'import apischema\n'), ((10102, 10127), 'pathlib.Path', 'pathlib.Path', (['(to + suffix)'], {}), '(to + suffix)\n', (10114, 10127), False, 'import pathlib\n'), ((12201, 12219), 'pathlib.Path', 'pathlib.Path', (['path'], {}), '(path)\n', (12213, 12219), False, 'import pathlib\n'), ((10837, 10855), 'pathlib.Path', 'pathlib.Path', (['path'], {}), '(path)\n', (10849, 10855), False, 'import pathlib\n'), ((7122, 7144), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (7142, 7144), False, 'import traceback\n'), ((32598, 32620), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (32618, 32620), False, 'import traceback\n')]
import os import time import numpy as np import torch import torch.optim as optim from tensorboardX import SummaryWriter from torch.utils.data import DataLoader from tqdm import tqdm from datasets.segDataSet import COVID19_SegDataSet from datasets.segDataSetNormalize import COVID19_SegDataSetNormalize from models.model import U2NET, U2NETP from segConfig import getConfig from utils.Metrics import enhanced_mixing_loss def muti_c_dice_loss_fusion(d0, d1, d2, d3, d4, d5, d6, labels_v, weight, device, num_classes): ''' mixed_loss=alpha*CrossEntropyLoss+(1-alpha)*dice_loss ''' loss0 = enhanced_mixing_loss( d0, labels_v, weight, device, alpha=0.5, n_classes=num_classes) loss1 = enhanced_mixing_loss( d1, labels_v, weight, device, alpha=0.5, n_classes=num_classes) loss2 = enhanced_mixing_loss( d2, labels_v, weight, device, alpha=0.5, n_classes=num_classes) loss3 = enhanced_mixing_loss( d3, labels_v, weight, device, alpha=0.5, n_classes=num_classes) loss4 = enhanced_mixing_loss( d4, labels_v, weight, device, alpha=0.5, n_classes=num_classes) loss5 = enhanced_mixing_loss( d5, labels_v, weight, device, alpha=0.5, n_classes=num_classes) loss6 = enhanced_mixing_loss( d6, labels_v, weight, device, alpha=0.5, n_classes=num_classes) loss = loss0 + loss1 + loss2 + loss3 + loss4 + loss5 + loss6 return loss0, loss def train(model, train_loader, optimizer, device, weight, num_classes): ''' 训练函数 ''' epoch_loss = 0 model.train() for idx, (imgs, masks) in tqdm(enumerate(train_loader), desc='Train', total=len(train_loader)): imgs, masks = imgs.to(device), masks.to(device) optimizer.zero_grad() d0, d1, d2, d3, d4, d5, d6 = model(imgs) # 混合损失 loss2, loss = muti_c_dice_loss_fusion( d0, d1, d2, d3, d4, d5, d6, masks, weight, device, num_classes) # if loss < 0: # print(idx, loss) # print(idx,loss,output.shape,masks.shape) # 反向传播获取梯度 loss.backward() # 优化 optimizer.step() epoch_loss += loss.clone().detach().cpu().numpy() torch.cuda.empty_cache() epoch_loss = epoch_loss / len(train_loader) return epoch_loss def val(model, train_loader, device, weight, num_classes): ''' 测试函数 ''' epoch_loss = 0 model.eval() with torch.no_grad(): for idx, (imgs, masks) in tqdm(enumerate(train_loader), desc='Validation', total=len(train_loader)): imgs, masks = imgs.to(device), masks.to(device) d0, d1, d2, d3, d4, d5, d6 = model(imgs) loss2, loss = muti_c_dice_loss_fusion( d0, d1, d2, d3, d4, d5, d6, masks, weight, device, num_classes) epoch_loss += loss.clone().detach().cpu().numpy() torch.cuda.empty_cache() epoch_loss = epoch_loss / len(train_loader) return epoch_loss def main(args): # 参数的复制 device, lrate, num_classes, num_epochs, log_name, batch_size, weight, model_name =\ args.device, args.lrate, args.num_classes, args.num_epochs, args.log_name, args.batch_size, args.weight, args.model_name pth, save_dir, save_every, start_epoch, train_data_dir, val_data_dir = \ args.pth, args.save_dir, args.save_every, args.start_epoch, args.train_data_dir, args.val_data_dir normalize = args.normalize # pth文件保存,若要使用onnx请自加函数 save_dir = save_dir+'/'+model_name if not os.path.exists(save_dir): os.makedirs(save_dir) # 统计可使用GPU数目并显示 ng = torch.cuda.device_count() print("Available cuda Devices:{}".format(ng)) for i in range(ng): print('device%d:' % i, end='') print(torch.cuda.get_device_properties(i)) # 选择device if device == 'cuda': torch.cuda.set_device(0) if not torch.cuda.is_available(): print('Cuda is not available, use CPU to train.') device = 'cpu' device = torch.device(device) print('===>device:', device) # 确定随机数种子,保证实验可重复 torch.cuda.manual_seed_all(0) # 实例化model print('===>Setup Model') model = U2NET(in_channels=1, out_channels=num_classes).to(device) ''' 需要显示模型请把下一句取消注释 To display the model, please uncomment the next sentence ''' # summary(model,(1, 512, 512)) print('===>Setting optimizer and scheduler') ''' optimizer->Adam优化器 scheduler->余弦退火调整 ''' optimizer = optim.Adam(model.parameters(), lr=lrate, weight_decay=1e-3) scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts( optimizer, T_0=10, eta_min=1e-6, last_epoch=-1, T_mult=2) # 加载预训练模型 if not pth == None: print('===>Loading Pretrained Model') checkpoint = torch.load(pth) model.load_state_dict(checkpoint['model_weights']) optimizer.load_state_dict(checkpoint['optimizer']) scheduler.load_state_dict(checkpoint['scheduler']) start_epoch = checkpoint['epoch']+1 # logger print('===>Making tensorboard log') if not os.path.exists('./log/seg/'): os.makedirs('./log/seg/') if log_name == None: writer = SummaryWriter( './log/seg/'+model_name+time.strftime('%m%d-%H%M', time.localtime(time.time()))) else: writer = SummaryWriter('./log/seg/'+log_name) # Load data if normalize: SegDataSet = COVID19_SegDataSetNormalize else: SegDataSet = COVID19_SegDataSet print('===>Loading dataset') train_data_loader = DataLoader( dataset=SegDataSet(train_data_dir, n_classes=num_classes), batch_size=batch_size, num_workers=8, shuffle=True, drop_last=False) val_data_loader = DataLoader( dataset=SegDataSet(val_data_dir, n_classes=num_classes), batch_size=batch_size, num_workers=8, shuffle=True, drop_last=False) print('train_data_loader:', len(train_data_loader)) print('val_data_loader:', len(val_data_loader)) print('===>Start Training and Validating') print("Start training at epoch = {:d}".format(start_epoch)) best_train_performance = [0, np.Inf] best_val_performance = [0, np.Inf] train_start_time = time.time() # begin training for epoch in range(start_epoch, start_epoch+num_epochs-1): epoch_begin_time = time.time() print("\n"+"="*20+"Epoch[{}:{}]".format(epoch, start_epoch+num_epochs)+"="*20 + '\nlr={}\tweight_decay={}'.format(optimizer.state_dict()['param_groups'][0]['lr'], optimizer.state_dict()['param_groups'][0]['weight_decay'])) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # train train_loss = train( model=model, train_loader=train_data_loader, optimizer=optimizer, device=device, weight=weight, num_classes=num_classes) # val val_loss = val( model=model, train_loader=val_data_loader, device=device, weight=weight, num_classes=num_classes) # change lrate scheduler.step() print('Epoch %d Train Loss:%.4f\t\t\tValidation Loss:%.4f' % (epoch, train_loss, val_loss)) # if satisfied the condition, save model if best_train_performance[1] > train_loss and train_loss > 0 and epoch > 30: state = {'epoch': epoch, 'model_weights': model.state_dict( ), 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict()} torch.save(state, os.path.join( save_dir, 'best_train_model.pth'.format(epoch))) best_train_performance = [epoch, train_loss] if best_val_performance[1] > val_loss and val_loss > 0 and epoch > 30: state = {'epoch': epoch, 'model_weights': model.state_dict( ), 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict()} torch.save(state, os.path.join( save_dir, 'best_val_model.pth'.format(epoch))) best_val_performance = [epoch, val_loss] if epoch % save_every == 0: state = {'epoch': epoch, 'model_weights': model.state_dict( ), 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict()} torch.save(state, os.path.join( save_dir, 'epoch_{}_model.pth'.format(epoch))) print('Best train loss epoch:%d\t\t\tloss:%.4f' % (best_train_performance[0], best_train_performance[1])) print('Best val loss epoch:%d\t\t\tloss:%.4f' % (best_val_performance[0], best_val_performance[1])) ''' tensorboard visualize args -------------------------- train_loss val_loss ''' writer.add_scalar('train/loss', train_loss, epoch) writer.add_scalar('val/loss', val_loss, epoch) epoch_time = time.time()-epoch_begin_time print('This epoch cost %.4fs, predicting it will take another %.4fs' % (epoch_time, epoch_time*(start_epoch+num_epochs-epoch-1))) train_end_time = time.time() print('This train total cost %.4fs' % (train_end_time-train_start_time)) writer.close() if __name__ == '__main__': ''' 本函数用于训练数据,详细参数请观看segConfig.py ''' # 获取参数 args = getConfig('train') main(args)
[ "utils.Metrics.enhanced_mixing_loss", "torch.cuda.manual_seed_all", "os.path.exists", "torch.cuda.get_device_properties", "tensorboardX.SummaryWriter", "os.makedirs", "segConfig.getConfig", "torch.load", "torch.cuda.device_count", "torch.cuda.set_device", "models.model.U2NET", "torch.cuda.is_a...
[((607, 696), 'utils.Metrics.enhanced_mixing_loss', 'enhanced_mixing_loss', (['d0', 'labels_v', 'weight', 'device'], {'alpha': '(0.5)', 'n_classes': 'num_classes'}), '(d0, labels_v, weight, device, alpha=0.5, n_classes=\n num_classes)\n', (627, 696), False, 'from utils.Metrics import enhanced_mixing_loss\n'), ((713, 802), 'utils.Metrics.enhanced_mixing_loss', 'enhanced_mixing_loss', (['d1', 'labels_v', 'weight', 'device'], {'alpha': '(0.5)', 'n_classes': 'num_classes'}), '(d1, labels_v, weight, device, alpha=0.5, n_classes=\n num_classes)\n', (733, 802), False, 'from utils.Metrics import enhanced_mixing_loss\n'), ((819, 908), 'utils.Metrics.enhanced_mixing_loss', 'enhanced_mixing_loss', (['d2', 'labels_v', 'weight', 'device'], {'alpha': '(0.5)', 'n_classes': 'num_classes'}), '(d2, labels_v, weight, device, alpha=0.5, n_classes=\n num_classes)\n', (839, 908), False, 'from utils.Metrics import enhanced_mixing_loss\n'), ((925, 1014), 'utils.Metrics.enhanced_mixing_loss', 'enhanced_mixing_loss', (['d3', 'labels_v', 'weight', 'device'], {'alpha': '(0.5)', 'n_classes': 'num_classes'}), '(d3, labels_v, weight, device, alpha=0.5, n_classes=\n num_classes)\n', (945, 1014), False, 'from utils.Metrics import enhanced_mixing_loss\n'), ((1031, 1120), 'utils.Metrics.enhanced_mixing_loss', 'enhanced_mixing_loss', (['d4', 'labels_v', 'weight', 'device'], {'alpha': '(0.5)', 'n_classes': 'num_classes'}), '(d4, labels_v, weight, device, alpha=0.5, n_classes=\n num_classes)\n', (1051, 1120), False, 'from utils.Metrics import enhanced_mixing_loss\n'), ((1137, 1226), 'utils.Metrics.enhanced_mixing_loss', 'enhanced_mixing_loss', (['d5', 'labels_v', 'weight', 'device'], {'alpha': '(0.5)', 'n_classes': 'num_classes'}), '(d5, labels_v, weight, device, alpha=0.5, n_classes=\n num_classes)\n', (1157, 1226), False, 'from utils.Metrics import enhanced_mixing_loss\n'), ((1243, 1332), 'utils.Metrics.enhanced_mixing_loss', 'enhanced_mixing_loss', (['d6', 'labels_v', 'weight', 'device'], {'alpha': '(0.5)', 'n_classes': 'num_classes'}), '(d6, labels_v, weight, device, alpha=0.5, n_classes=\n num_classes)\n', (1263, 1332), False, 'from utils.Metrics import enhanced_mixing_loss\n'), ((3587, 3612), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (3610, 3612), False, 'import torch\n'), ((3994, 4014), 'torch.device', 'torch.device', (['device'], {}), '(device)\n', (4006, 4014), False, 'import torch\n'), ((4074, 4103), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['(0)'], {}), '(0)\n', (4100, 4103), False, 'import torch\n'), ((4563, 4673), 'torch.optim.lr_scheduler.CosineAnnealingWarmRestarts', 'optim.lr_scheduler.CosineAnnealingWarmRestarts', (['optimizer'], {'T_0': '(10)', 'eta_min': '(1e-06)', 'last_epoch': '(-1)', 'T_mult': '(2)'}), '(optimizer, T_0=10, eta_min=\n 1e-06, last_epoch=-1, T_mult=2)\n', (4609, 4673), True, 'import torch.optim as optim\n'), ((6217, 6228), 'time.time', 'time.time', ([], {}), '()\n', (6226, 6228), False, 'import time\n'), ((9088, 9099), 'time.time', 'time.time', ([], {}), '()\n', (9097, 9099), False, 'import time\n'), ((9297, 9315), 'segConfig.getConfig', 'getConfig', (['"""train"""'], {}), "('train')\n", (9306, 9315), False, 'from segConfig import getConfig\n'), ((2187, 2211), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (2209, 2211), False, 'import torch\n'), ((2413, 2428), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2426, 2428), False, 'import torch\n'), ((3501, 3525), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (3515, 3525), False, 'import os\n'), ((3535, 3556), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n', (3546, 3556), False, 'import os\n'), ((3825, 3849), 'torch.cuda.set_device', 'torch.cuda.set_device', (['(0)'], {}), '(0)\n', (3846, 3849), False, 'import torch\n'), ((4787, 4802), 'torch.load', 'torch.load', (['pth'], {}), '(pth)\n', (4797, 4802), False, 'import torch\n'), ((5093, 5121), 'os.path.exists', 'os.path.exists', (['"""./log/seg/"""'], {}), "('./log/seg/')\n", (5107, 5121), False, 'import os\n'), ((5131, 5156), 'os.makedirs', 'os.makedirs', (['"""./log/seg/"""'], {}), "('./log/seg/')\n", (5142, 5156), False, 'import os\n'), ((5334, 5372), 'tensorboardX.SummaryWriter', 'SummaryWriter', (["('./log/seg/' + log_name)"], {}), "('./log/seg/' + log_name)\n", (5347, 5372), False, 'from tensorboardX import SummaryWriter\n'), ((6341, 6352), 'time.time', 'time.time', ([], {}), '()\n', (6350, 6352), False, 'import time\n'), ((2860, 2884), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (2882, 2884), False, 'import torch\n'), ((3740, 3775), 'torch.cuda.get_device_properties', 'torch.cuda.get_device_properties', (['i'], {}), '(i)\n', (3772, 3775), False, 'import torch\n'), ((3865, 3890), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3888, 3890), False, 'import torch\n'), ((4170, 4216), 'models.model.U2NET', 'U2NET', ([], {'in_channels': '(1)', 'out_channels': 'num_classes'}), '(in_channels=1, out_channels=num_classes)\n', (4175, 4216), False, 'from models.model import U2NET, U2NETP\n'), ((8886, 8897), 'time.time', 'time.time', ([], {}), '()\n', (8895, 8897), False, 'import time\n'), ((6695, 6711), 'time.localtime', 'time.localtime', ([], {}), '()\n', (6709, 6711), False, 'import time\n'), ((5292, 5303), 'time.time', 'time.time', ([], {}), '()\n', (5301, 5303), False, 'import time\n')]
from rest_framework import viewsets from category.models import Category from category.serializers import CategorySerializer class CategoryViewSet(viewsets.ReadOnlyModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer
[ "category.models.Category.objects.all" ]
[((197, 219), 'category.models.Category.objects.all', 'Category.objects.all', ([], {}), '()\n', (217, 219), False, 'from category.models import Category\n')]
import time import datetime import json import pandas as pd from pandas import DataFrame import os import collections import numpy as np import csv import collections import nltk.classify import nltk.metrics """ to save user-user similarity matrix as a whole """ index_list = ["1", "2", "3", "4", "5", "6", "7"] filename1 = "test" + index_list[0] + ".tsv" filename2 = "test" + index_list[1] + ".tsv" filename3 = "test" + index_list[2] + ".tsv" filename4 = "test" + index_list[3] + ".tsv" filename5 = "test" + index_list[4] + ".tsv" filename6 = "test" + index_list[5] + ".tsv" filename7 = "test" + index_list[6] + ".tsv" with open("user_user_matrix_nof.tsv","w",newline='') as csvfile: writer = csv.writer(csvfile) k=0; with open(filename1, 'r') as fp1: with open(filename2, 'r') as fp2: with open(filename3, 'r') as fp3: with open(filename4, 'r') as fp4: with open(filename5, 'r') as fp5: with open(filename6, 'r') as fp6: with open(filename7, 'r') as fp7: for line1 in fp1: line1=(line1.replace('\n', '')).split(',') line2 =(fp2.readline().replace('\n', '')).split(',') line3=((fp3.readline()).replace('\n', '')).split(',') line4=((fp4.readline()).replace('\n', '')).split(',') line5=((fp5.readline()).replace('\n', '')).split(',') line6=((fp6.readline()).replace('\n', '')).split(',') line7=((fp7.readline()).replace('\n', '')).split(',') line=[] if len(line1)>1: print(k) #print(line1[-1]) line.append(line1[0:]+ line2[1:]+ line3[1:] +line4[1:] +line5[1:] +line6[1:] +line7[1:]) #line.append(line2[1:]) #line.append(line3[1:]) #line.append(line4[1:]) #line.append(line5[1:]) #line.append(line6[1:]) #line.append(line7[1:]) k=k+1; #Line=DataFrame(line) #print(Line.T.iloc[0:]) writer.writerow(line) #print([line])
[ "csv.writer" ]
[((725, 744), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (735, 744), False, 'import csv\n')]
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and is distributed in the hope that # it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License for more details. import re from PyQt4.QtCore import (Qt, SIGNAL, pyqtSignature) from PyQt4.QtGui import (QApplication, QDialog) import ui_findandreplacedlg MAC = True try: from PyQt4.QtGui import qt_mac_set_native_menubar except ImportError: MAC = False class FindAndReplaceDlg(QDialog, ui_findandreplacedlg.Ui_FindAndReplaceDlg): def __init__(self, text, parent=None): super(FindAndReplaceDlg, self).__init__(parent) self.__text = str(text) self.__index = 0 self.setupUi(self) if not MAC: self.findButton.setFocusPolicy(Qt.NoFocus) self.replaceButton.setFocusPolicy(Qt.NoFocus) self.replaceAllButton.setFocusPolicy(Qt.NoFocus) self.closeButton.setFocusPolicy(Qt.NoFocus) self.updateUi() @pyqtSignature("QString") def on_findLineEdit_textEdited(self, text): self.__index = 0 self.updateUi() def makeRegex(self): findText = str(self.findLineEdit.text()) if str(self.syntaxComboBox.currentText()) == "Literal": findText = re.escape(findText) flags = re.MULTILINE|re.DOTALL|re.UNICODE if not self.caseCheckBox.isChecked(): flags |= re.IGNORECASE if self.wholeCheckBox.isChecked(): findText = r"\b{0}\b".format(findText) return re.compile(findText, flags) @pyqtSignature("") def on_findButton_clicked(self): regex = self.makeRegex() match = regex.search(self.__text, self.__index) if match is not None: self.__index = match.end() self.emit(SIGNAL("found"), match.start()) else: self.emit(SIGNAL("notfound")) @pyqtSignature("") def on_replaceButton_clicked(self): regex = self.makeRegex() self.__text = regex.sub(str(self.replaceLineEdit.text()), self.__text, 1) @pyqtSignature("") def on_replaceAllButton_clicked(self): regex = self.makeRegex() self.__text = regex.sub(str(self.replaceLineEdit.text()), self.__text) def updateUi(self): enable = not self.findLineEdit.text().isEmpty() self.findButton.setEnabled(enable) self.replaceButton.setEnabled(enable) self.replaceAllButton.setEnabled(enable) def text(self): return self.__text if __name__ == "__main__": import sys text = """US experience shows that, unlike traditional patents, software patents do not encourage innovation and R&D, quite the contrary. In particular they hurt small and medium-sized enterprises and generally newcomers in the market. They will just weaken the market and increase spending on patents and litigation, at the expense of technological innovation and research. Especially dangerous are attempts to abuse the patent system by preventing interoperability as a means of avoiding competition with technological ability. --- Extract quoted from <NAME> and <NAME>'s letter to the President of the European Parliament http://www.effi.org/patentit/patents_torvalds_cox.html""" def found(where): print("Found at {0}".format(where)) def nomore(): print("No more found") app = QApplication(sys.argv) form = FindAndReplaceDlg(text) form.connect(form, SIGNAL("found"), found) form.connect(form, SIGNAL("notfound"), nomore) form.show() app.exec_() print(form.text())
[ "PyQt4.QtGui.QApplication", "re.escape", "re.compile", "PyQt4.QtCore.SIGNAL", "PyQt4.QtCore.pyqtSignature" ]
[((1436, 1460), 'PyQt4.QtCore.pyqtSignature', 'pyqtSignature', (['"""QString"""'], {}), "('QString')\n", (1449, 1460), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n'), ((2016, 2033), 'PyQt4.QtCore.pyqtSignature', 'pyqtSignature', (['""""""'], {}), "('')\n", (2029, 2033), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n'), ((2362, 2379), 'PyQt4.QtCore.pyqtSignature', 'pyqtSignature', (['""""""'], {}), "('')\n", (2375, 2379), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n'), ((2582, 2599), 'PyQt4.QtCore.pyqtSignature', 'pyqtSignature', (['""""""'], {}), "('')\n", (2595, 2599), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n'), ((3924, 3946), 'PyQt4.QtGui.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (3936, 3946), False, 'from PyQt4.QtGui import QApplication, QDialog\n'), ((1981, 2008), 're.compile', 're.compile', (['findText', 'flags'], {}), '(findText, flags)\n', (1991, 2008), False, 'import re\n'), ((4005, 4020), 'PyQt4.QtCore.SIGNAL', 'SIGNAL', (['"""found"""'], {}), "('found')\n", (4011, 4020), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n'), ((4052, 4070), 'PyQt4.QtCore.SIGNAL', 'SIGNAL', (['"""notfound"""'], {}), "('notfound')\n", (4058, 4070), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n'), ((1721, 1740), 're.escape', 're.escape', (['findText'], {}), '(findText)\n', (1730, 1740), False, 'import re\n'), ((2251, 2266), 'PyQt4.QtCore.SIGNAL', 'SIGNAL', (['"""found"""'], {}), "('found')\n", (2257, 2266), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n'), ((2319, 2337), 'PyQt4.QtCore.SIGNAL', 'SIGNAL', (['"""notfound"""'], {}), "('notfound')\n", (2325, 2337), False, 'from PyQt4.QtCore import Qt, SIGNAL, pyqtSignature\n')]
# -*- coding: utf-8 -*- import numpy as np import scipy.io as sio import glob import os import torch import torch.utils.data import torchvision.transforms.functional import cv2 def read_dataset(path): """ Read training dataset or validation dataset. :param path: The path of dataset. :return: The list of filenames. """ image_list = glob.glob(os.path.join(path, 'images/*.jpg')) return image_list def read_mat(mode, path, image_list): """ Read joints.mat file. joints.mat in lspet is (14, 3, 10000); joints.mat in lsp is (3, 14, 2000) :param mode: 'lspet' or 'lsp' :param path: The path of joints.mat. :param image_list: The array of image filenames. :return: """ mat_arr = sio.loadmat(os.path.join(path, 'joints.mat'))['joints'] # (x,y,z) # LSPET: z = 1 means the key points is not blocked. # LSP: z = 0 means the key points is not blocked. key_point_list = [] limits = [] if mode == 'lspet': key_point_list = np.transpose(mat_arr, (2, 0, 1)).tolist() # Calculate the limits to find center points limits = np.transpose(mat_arr, (2, 1, 0)) if mode == 'lsp': # Guarantee z = 1 means the key points is not blocked mat_arr[2] = np.logical_not(mat_arr[2]) key_point_list = np.transpose(mat_arr, (2, 1, 0)).tolist() # Calculate the limits to find center points limits = np.transpose(mat_arr, (2, 0, 1)) center_point_list = [] scale_list = [] for i in range(limits.shape[0]): image = cv2.imread(image_list[i]) h = image.shape[0] w = image.shape[1] # Calculate the center points of each image center_x = (limits[i][0][limits[i][0] > 0].min() + limits[i][0][limits[i][0] < w].max()) / 2 center_y = (limits[i][1][limits[i][1] > 0].min() + limits[i][1][limits[i][1] < h].max()) / 2 center_point_list.append([center_x, center_y]) # Calculate the scale of each image scale = (limits[i][1][limits[i][1] < h].max() - limits[i][1][limits[i][1] > 0].min() + 4) / 368 scale_list.append(scale) return key_point_list, center_point_list, scale_list def gaussian_kernel(size_w, size_h, center_x, center_y, sigma): grid_y, grid_x = np.mgrid[0:size_h, 0:size_w] D2 = (grid_x - center_x) ** 2 + (grid_y - center_y) ** 2 return np.exp(-D2 / 2.0 / sigma / sigma) class LSP_DATA(torch.utils.data.Dataset): def __init__(self, mode, path, stride, transformer=None): self.image_list = read_dataset(path) self.key_point_list, self.center_point_list, self.scale_list = read_mat(mode, path, self.image_list) self.stride = stride self.transformer = transformer self.sigma = 3.0 def __getitem__(self, item): image_path = self.image_list[item] image = np.array(cv2.imread(image_path), dtype=np.float32) key_points = self.key_point_list[item] center_points = self.center_point_list[item] scale = self.scale_list[item] # Expand dataset image, key_points, center_points = self.transformer(image, key_points, center_points, scale) h, w, _ = image.shape # Generate heatmap size_h = int(h / self.stride) size_w = int(w / self.stride) heatmap = np.zeros((size_h, size_w, len(key_points) + 1), dtype=np.float32) # Generate the heatmap of all key points for i in range(len(key_points)): # Resize image from 368 to 46 x = int(key_points[i][0]) * 1.0 / self.stride y = int(key_points[i][1]) * 1.0 / self.stride kernel = gaussian_kernel(size_h=size_h, size_w=size_w, center_x=x, center_y=y, sigma=self.sigma) kernel[kernel > 1] = 1 kernel[kernel < 0.01] = 0 heatmap[:, :, i + 1] = kernel # Generate the heatmap of background heatmap[:, :, 0] = 1.0 - np.max(heatmap[:, :, 1:], axis=2) # Generate centermap centermap = np.zeros((h, w, 1), dtype=np.float32) kernel = gaussian_kernel(size_h=h, size_w=w, center_x=center_points[0], center_y=center_points[1], sigma=self.sigma) kernel[kernel > 1] = 1 kernel[kernel < 0.01] = 0 centermap[:, :, 0] = kernel image -= image.mean() image = torchvision.transforms.functional.to_tensor(image) heatmap = torch.from_numpy(np.transpose(heatmap, (2, 0, 1))) centermap = torch.from_numpy(np.transpose(centermap, (2, 0, 1))) return image.float(), heatmap.float(), centermap.float() def __len__(self): return len(self.image_list)
[ "numpy.logical_not", "os.path.join", "numpy.max", "numpy.exp", "numpy.zeros", "numpy.transpose", "cv2.imread" ]
[((2187, 2220), 'numpy.exp', 'np.exp', (['(-D2 / 2.0 / sigma / sigma)'], {}), '(-D2 / 2.0 / sigma / sigma)\n', (2193, 2220), True, 'import numpy as np\n'), ((351, 385), 'os.path.join', 'os.path.join', (['path', '"""images/*.jpg"""'], {}), "(path, 'images/*.jpg')\n", (363, 385), False, 'import os\n'), ((1042, 1074), 'numpy.transpose', 'np.transpose', (['mat_arr', '(2, 1, 0)'], {}), '(mat_arr, (2, 1, 0))\n', (1054, 1074), True, 'import numpy as np\n'), ((1166, 1192), 'numpy.logical_not', 'np.logical_not', (['mat_arr[2]'], {}), '(mat_arr[2])\n', (1180, 1192), True, 'import numpy as np\n'), ((1312, 1344), 'numpy.transpose', 'np.transpose', (['mat_arr', '(2, 0, 1)'], {}), '(mat_arr, (2, 0, 1))\n', (1324, 1344), True, 'import numpy as np\n'), ((1432, 1457), 'cv2.imread', 'cv2.imread', (['image_list[i]'], {}), '(image_list[i])\n', (1442, 1457), False, 'import cv2\n'), ((3632, 3669), 'numpy.zeros', 'np.zeros', (['(h, w, 1)'], {'dtype': 'np.float32'}), '((h, w, 1), dtype=np.float32)\n', (3640, 3669), True, 'import numpy as np\n'), ((707, 739), 'os.path.join', 'os.path.join', (['path', '"""joints.mat"""'], {}), "(path, 'joints.mat')\n", (719, 739), False, 'import os\n'), ((2628, 2650), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (2638, 2650), False, 'import cv2\n'), ((3560, 3593), 'numpy.max', 'np.max', (['heatmap[:, :, 1:]'], {'axis': '(2)'}), '(heatmap[:, :, 1:], axis=2)\n', (3566, 3593), True, 'import numpy as np\n'), ((4013, 4045), 'numpy.transpose', 'np.transpose', (['heatmap', '(2, 0, 1)'], {}), '(heatmap, (2, 0, 1))\n', (4025, 4045), True, 'import numpy as np\n'), ((4078, 4112), 'numpy.transpose', 'np.transpose', (['centermap', '(2, 0, 1)'], {}), '(centermap, (2, 0, 1))\n', (4090, 4112), True, 'import numpy as np\n'), ((941, 973), 'numpy.transpose', 'np.transpose', (['mat_arr', '(2, 0, 1)'], {}), '(mat_arr, (2, 0, 1))\n', (953, 973), True, 'import numpy as np\n'), ((1212, 1244), 'numpy.transpose', 'np.transpose', (['mat_arr', '(2, 1, 0)'], {}), '(mat_arr, (2, 1, 0))\n', (1224, 1244), True, 'import numpy as np\n')]
#!/usr/bin/env python3 from collections import Counter from decimal import Decimal import csv import os import sys def process_trips(trip_ids): route_ids = set() shape_ids = set() service_ids = set() with open('trips.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if row[2] in trip_ids: filtered_rows.append(row) route_ids.add(row[0]) shape_ids.add(row[9]) service_ids.add(row[1]) with open('cleaned/trips.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) return route_ids, shape_ids, service_ids def clean_shapes(shape_ids): with open('shapes.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if row[0] in shape_ids: filtered_rows.append(row) with open('cleaned/shapes.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) def process_stop_times(stop_ids): trip_ids = set() trip_id_count = Counter() with open('stop_times.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if row[2] in stop_ids: filtered_rows.append(row) trip_id_count[row[0]] += 1 for trip_id, count in trip_id_count.items(): if count >= 2: trip_ids.add(trip_id) cleaned_rows = [filtered_rows[0]] for row in filtered_rows[1:]: if row[0] in trip_ids: cleaned_rows.append(row) with open('cleaned/stop_times.txt', 'w') as f: writer = csv.writer(f) writer.writerows(cleaned_rows) return trip_ids def process_stops(min_lat, max_lat, min_lon, max_lon): stop_ids = set() with open('stops.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: stop_lat = Decimal(row[3]) stop_lon = Decimal(row[4]) if (stop_lat >= min_lat and stop_lat <= max_lat and stop_lon >= min_lon and stop_lon <= max_lon): filtered_rows.append(row) stop_ids.add(row[0]) with open('cleaned/stops.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) return stop_ids def process_routes(route_ids): agency_ids = set() with open('routes.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if row[0] in route_ids: filtered_rows.append(row) agency_ids.add(row[1]) with open('cleaned/routes.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) return agency_ids def clean_transfers(stop_ids, trip_ids): with open('transfers.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if (row[0] in stop_ids and row[1] in stop_ids and row[4] in trip_ids and row[5] in trip_ids): filtered_rows.append(row) with open('cleaned/transfers.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) def clean_calendar(service_ids): with open('calendar_dates.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if row[0] in service_ids: filtered_rows.append(row) with open('cleaned/calendar_dates.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) def clean_agencies(agency_ids): with open('agency.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if row[0] in agency_ids: filtered_rows.append(row) with open('cleaned/agency.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) def create_output_directory(): os.makedirs('cleaned', exist_ok=True) def main(): create_output_directory() min_lat_str, max_lat_str, min_lon_str, max_lon_str = sys.argv[1:5] min_lat = Decimal(min_lat_str) max_lat = Decimal(max_lat_str) min_lon = Decimal(min_lon_str) max_lon = Decimal(max_lon_str) # TODO: Deduplicate code. stop_ids = process_stops(min_lat, max_lat, min_lon, max_lon) trip_ids = process_stop_times(stop_ids) route_ids, shape_ids, service_ids = process_trips(trip_ids) agency_ids = process_routes(route_ids) clean_transfers(stop_ids, trip_ids) clean_shapes(shape_ids) clean_calendar(service_ids) clean_agencies(agency_ids) if __name__ == '__main__': main()
[ "os.makedirs", "csv.writer", "collections.Counter", "csv.reader", "decimal.Decimal" ]
[((1213, 1222), 'collections.Counter', 'Counter', ([], {}), '()\n', (1220, 1222), False, 'from collections import Counter\n'), ((4447, 4484), 'os.makedirs', 'os.makedirs', (['"""cleaned"""'], {'exist_ok': '(True)'}), "('cleaned', exist_ok=True)\n", (4458, 4484), False, 'import os\n'), ((4615, 4635), 'decimal.Decimal', 'Decimal', (['min_lat_str'], {}), '(min_lat_str)\n', (4622, 4635), False, 'from decimal import Decimal\n'), ((4650, 4670), 'decimal.Decimal', 'Decimal', (['max_lat_str'], {}), '(max_lat_str)\n', (4657, 4670), False, 'from decimal import Decimal\n'), ((4685, 4705), 'decimal.Decimal', 'Decimal', (['min_lon_str'], {}), '(min_lon_str)\n', (4692, 4705), False, 'from decimal import Decimal\n'), ((4720, 4740), 'decimal.Decimal', 'Decimal', (['max_lon_str'], {}), '(max_lon_str)\n', (4727, 4740), False, 'from decimal import Decimal\n'), ((270, 283), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (280, 283), False, 'import csv\n'), ((639, 652), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (649, 652), False, 'import csv\n'), ((826, 839), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (836, 839), False, 'import csv\n'), ((1081, 1094), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (1091, 1094), False, 'import csv\n'), ((1284, 1297), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1294, 1297), False, 'import csv\n'), ((1862, 1875), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (1872, 1875), False, 'import csv\n'), ((2070, 2083), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (2080, 2083), False, 'import csv\n'), ((2533, 2546), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2543, 2546), False, 'import csv\n'), ((2721, 2734), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (2731, 2734), False, 'import csv\n'), ((3015, 3028), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (3025, 3028), False, 'import csv\n'), ((3194, 3207), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (3204, 3207), False, 'import csv\n'), ((3538, 3551), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (3548, 3551), False, 'import csv\n'), ((3691, 3704), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (3701, 3704), False, 'import csv\n'), ((3956, 3969), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (3966, 3969), False, 'import csv\n'), ((4100, 4113), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (4110, 4113), False, 'import csv\n'), ((4356, 4369), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (4366, 4369), False, 'import csv\n'), ((2205, 2220), 'decimal.Decimal', 'Decimal', (['row[3]'], {}), '(row[3])\n', (2212, 2220), False, 'from decimal import Decimal\n'), ((2244, 2259), 'decimal.Decimal', 'Decimal', (['row[4]'], {}), '(row[4])\n', (2251, 2259), False, 'from decimal import Decimal\n')]
from concurrent import futures import base64 import time import os import model_pb2 import model_pb2_grpc import predict as predict_fn import grpc class PredictService(model_pb2_grpc.PredictServiceServicer): # def GetEncode(self, request, context): # return test_pb2.encodetext(enctransactionID = encoding(request.pttransactionID), # encproperties = encoding(request.ptproperties), # encsenderID = request.ptsenderID) def __init__(self, model_name, model_port, proxy_name, proxy_port): self.model_name = model_name self.model_port = model_port self.proxy_name = proxy_name self.proxy_port = proxy_port def SetProxy(self, request, context): print("[SetProxy]{request}\n".format(request=request)) self.proxy_name = request.proxyName self.proxy_port = request.proxyPort return model_pb2.response(status = "SetProxy Sucessful") def Predict(self, request, context): print("[Input]{request}\n".format(request=request)) input_type = request.inputType input_stream = request.inputStream #if (self.proxy_name == None or self.proxy_port == None): # return model_pb2.response(status = "ProxyNotSet") output = predict_fn.predict(input_stream) # print("goes here") print("[Output]" + output) ''' Connect to proxy, return the prediction result ''' # channel = grpc.insecure_channel('{proxy_name}:{proxy_port}'.format( # proxy_name = self.proxy_name, # proxy_port = self.proxy_port # )) # stub = proxy_pb2_grpc.ProxyServiceStub(channel) # response = stub.Return(proxy_pb2.input( # inputType = "string", # inputStream = output # )) # print('Predicted output [{output}] sent to {proxy}:{response}'.format( # output = output, # proxy = self.proxy_name, # response = response.status # )) return model_pb2.output(outputType = "string", outputStream = output) def Ping(self, request, context): #print("received request:{request}\n".format(request=request)) hi_msg = request.msg if (self.proxy_name == None or self.proxy_port == None): return model_pb2.response(status = "ProxyNotSet") r = "This is %s \n"%(self.model_name) return model_pb2.response(status = r) def serve(): model_name = os.environ["MODEL_NAME"] model_port = os.environ["MODEL_PORT"] proxy_name = os.environ["PROXY_NAME"] proxy_port = os.environ["PROXY_PORT"] server = grpc.server(futures.ThreadPoolExecutor(max_workers=2)) service = PredictService(model_name, model_port, proxy_name, proxy_port) model_pb2_grpc.add_PredictServiceServicer_to_server(service,server) # server.add_insecure_port('[::]:22222') server.add_insecure_port('[::]:{port}'.format(port=model_port)) server.start() print("Model Server Started -- %s"%(model_name)) try: while True: time.sleep(60*60*24) except KeyboardInterrupt: server.stop(0) if __name__ == '__main__': serve()
[ "model_pb2.response", "predict.predict", "concurrent.futures.ThreadPoolExecutor", "time.sleep", "model_pb2_grpc.add_PredictServiceServicer_to_server", "model_pb2.output" ]
[((2907, 2975), 'model_pb2_grpc.add_PredictServiceServicer_to_server', 'model_pb2_grpc.add_PredictServiceServicer_to_server', (['service', 'server'], {}), '(service, server)\n', (2958, 2975), False, 'import model_pb2_grpc\n'), ((971, 1018), 'model_pb2.response', 'model_pb2.response', ([], {'status': '"""SetProxy Sucessful"""'}), "(status='SetProxy Sucessful')\n", (989, 1018), False, 'import model_pb2\n'), ((1365, 1397), 'predict.predict', 'predict_fn.predict', (['input_stream'], {}), '(input_stream)\n', (1383, 1397), True, 'import predict as predict_fn\n'), ((2134, 2192), 'model_pb2.output', 'model_pb2.output', ([], {'outputType': '"""string"""', 'outputStream': 'output'}), "(outputType='string', outputStream=output)\n", (2150, 2192), False, 'import model_pb2\n'), ((2532, 2560), 'model_pb2.response', 'model_pb2.response', ([], {'status': 'r'}), '(status=r)\n', (2550, 2560), False, 'import model_pb2\n'), ((2783, 2824), 'concurrent.futures.ThreadPoolExecutor', 'futures.ThreadPoolExecutor', ([], {'max_workers': '(2)'}), '(max_workers=2)\n', (2809, 2824), False, 'from concurrent import futures\n'), ((2423, 2463), 'model_pb2.response', 'model_pb2.response', ([], {'status': '"""ProxyNotSet"""'}), "(status='ProxyNotSet')\n", (2441, 2463), False, 'import model_pb2\n'), ((3201, 3225), 'time.sleep', 'time.sleep', (['(60 * 60 * 24)'], {}), '(60 * 60 * 24)\n', (3211, 3225), False, 'import time\n')]
"""Events API views""" #DRF from rest_framework.views import APIView from rest_framework import status, mixins, viewsets from rest_framework.response import Response from rest_framework.request import Request from rest_framework.decorators import api_view from rest_framework import generics from operator import itemgetter, attrgetter #Django from django.db.models import Q #Serializer from cride.users.serializers import PrizeModelSerializer, ExchangeModelSerializer #Utilities from heapq import nlargest #Models from cride.users.models import Prize, User, Exchange @api_view(["POST"]) def shipment_exchange(request): exchange = Exchange.objects.get(id = request.data["exchange"]) exchange.phone = request.data["phone"] exchange.email = request.data["email"] exchange.adress = request.data["adress"] exchange.country = request.data["country"] exchange.state = request.data["state"] exchange.city = request.data["city"] exchange.cp = request.data["cp"] exchange.full_name = request.data["full_name"] exchange.save() data = {"Exchange": ExchangeModelSerializer(exchange).data} return Response(data)
[ "cride.users.serializers.ExchangeModelSerializer", "rest_framework.response.Response", "rest_framework.decorators.api_view", "cride.users.models.Exchange.objects.get" ]
[((571, 589), 'rest_framework.decorators.api_view', 'api_view', (["['POST']"], {}), "(['POST'])\n", (579, 589), False, 'from rest_framework.decorators import api_view\n'), ((637, 686), 'cride.users.models.Exchange.objects.get', 'Exchange.objects.get', ([], {'id': "request.data['exchange']"}), "(id=request.data['exchange'])\n", (657, 686), False, 'from cride.users.models import Prize, User, Exchange\n'), ((1138, 1152), 'rest_framework.response.Response', 'Response', (['data'], {}), '(data)\n', (1146, 1152), False, 'from rest_framework.response import Response\n'), ((1086, 1119), 'cride.users.serializers.ExchangeModelSerializer', 'ExchangeModelSerializer', (['exchange'], {}), '(exchange)\n', (1109, 1119), False, 'from cride.users.serializers import PrizeModelSerializer, ExchangeModelSerializer\n')]
# Copyright (c) 2008-2009 <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # 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. """ Random graph generators. @sort: generate """ # Imports import graph as classes from random import randint # Generator def generate(graph, num_nodes, num_edges, weight_range=(1, 1)): """ Add nodes and random edges to the graph. @type graph: graph @param graph: Graph. @type num_nodes: number @param num_nodes: Number of nodes. @type num_edges: number @param num_edges: Number of edges. @type weight_range: tuple @param weight_range: tuple of two integers as lower and upper limits on randomly generated weights (uniform distribution). """ # Discover if graph is directed or not directed = (type(graph) == classes.digraph) # Nodes first nodes = xrange(num_nodes) graph.add_nodes(nodes) # Build a list of all possible edges edges = [] edges_append = edges.append for x in nodes: for y in nodes: if ((directed and x != y) or (x > y)): edges_append((x, y)) # Randomize the list for i in xrange(len(edges)): r = randint(0, len(edges)-1) edges[i], edges[r] = edges[r], edges[i] # Add edges to the graph min_wt = min(weight_range) max_wt = max(weight_range) for i in xrange(num_edges): each = edges[i] graph.add_edge(each[0], each[1], wt = randint(min_wt, max_wt))
[ "random.randint" ]
[((2515, 2538), 'random.randint', 'randint', (['min_wt', 'max_wt'], {}), '(min_wt, max_wt)\n', (2522, 2538), False, 'from random import randint\n')]
# Generated by Django 4.0 on 2021-12-16 19:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("episodes", "0021_auto_20210922_1012"), ] operations = [ migrations.AddField( model_name="episode", name="link", field=models.URLField(blank=True, max_length=2083, null=True), ), ]
[ "django.db.models.URLField" ]
[((332, 387), 'django.db.models.URLField', 'models.URLField', ([], {'blank': '(True)', 'max_length': '(2083)', 'null': '(True)'}), '(blank=True, max_length=2083, null=True)\n', (347, 387), False, 'from django.db import migrations, models\n')]
import datetime as dt from celery_store.mixins import PeriodicTaskMixin, TaskScheduleMixin from celery import current_app as app from celery.schedules import crontab @app.task(name='sum-of-two-numbers') def add(x, y): return x + y class PeriodicTask(PeriodicTaskMixin): @property def name(self): return 'My Task' def get_schedules(self): schedule = TaskSchedule() schedule.task = self return [schedule] def get_task(self): return add @classmethod def get_all_with_active_schedules(cls): return [TaskSchedule(), TaskSchedule()] @classmethod def get_latest_change_to_schedule(cls): return dt.datetime.now() - dt.timedelta(minutes=5) @property def last_run_at(self): return dt.datetime.now() - dt.timedelta(seconds=(60*4) + 50) class TaskSchedule(TaskScheduleMixin): @property def schedule(self): return crontab('*') @property def task(self): task = PeriodicTask() task.schedule = self return task
[ "datetime.datetime.now", "datetime.timedelta", "celery.current_app.task", "celery.schedules.crontab" ]
[((171, 206), 'celery.current_app.task', 'app.task', ([], {'name': '"""sum-of-two-numbers"""'}), "(name='sum-of-two-numbers')\n", (179, 206), True, 'from celery import current_app as app\n'), ((944, 956), 'celery.schedules.crontab', 'crontab', (['"""*"""'], {}), "('*')\n", (951, 956), False, 'from celery.schedules import crontab\n'), ((694, 711), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (709, 711), True, 'import datetime as dt\n'), ((714, 737), 'datetime.timedelta', 'dt.timedelta', ([], {'minutes': '(5)'}), '(minutes=5)\n', (726, 737), True, 'import datetime as dt\n'), ((795, 812), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (810, 812), True, 'import datetime as dt\n'), ((815, 848), 'datetime.timedelta', 'dt.timedelta', ([], {'seconds': '(60 * 4 + 50)'}), '(seconds=60 * 4 + 50)\n', (827, 848), True, 'import datetime as dt\n')]
from flask import render_template,redirect,request,url_for,abort,flash from . import main #from PIL import Image from flask_login import login_required,current_user from ..models import User,Post,Comment from .forms import UpdateProfile,PostForm,AddCommentForm#,UpdateAccountForm from .. import db from .. import db,photos from app.request import getQuotes @main.route('/') def index(): quotes= getQuotes() ''' View root page function that returns the index page and its data ''' post # popular_quotes = get_quotes('popular') #print(popular_quotes) # popular_quotes = get_quotes('popular') #print(popular_quotes) title = 'Home - Welcome to The Blogwebsite Review Online' return render_template('index.html', title = title, quotes=quotes) @main.route('/views') def view_page(): all_posts = Post.query.all() return render_template('views.html',all_posts=all_posts) @main.route("/account", methods=['GET', 'POST']) @login_required def account(): form = UpdateProfile() if form.validate_on_submit(): if form.picture.data: picture_file = save_picture(form.picture.data) current_user.image_file = picture_file current_user.username = form.username.data current_user.email = form.email.data db.session.commit() flash('Your account has been updated!', 'success') return redirect(url_for('account')) elif request.method == 'GET': form.username.data = current_user.username form.email.data = current_user.email image_file = url_for('static', filename='profile_pics/' + current_user.image_file) return render_template('account.html', title='Account', image_file=image_file, form=form) @main.route("/post/<int:post_id>") def post(post_id): post = Post.query.get_or_404(post_id) return render_template('post.html', title=post.title, post=post) @main.route('/user/<uname>/update',methods = ['GET','POST']) @login_required def update_profile(uname): user = User.query.filter_by(username = uname).first() if user is None: abort(404) form = UpdateProfile() if form.validate_on_submit(): # user.bio = form.bio.data db.session.add(user) db.session.commit() #return redirect(url_for('.profile',uname=user.username)) return render_template('post_blog.html',form =form) @main.route('/user/<uname>/update/pic',methods= ['POST']) @login_required def update_pic(uname): user = User.query.filter_by(username = uname).first() if 'photo' in request.files: filename = photos.save(request.files['photo']) path = f'photos/{filename}' user.profile_pic_path = path db.session.commit() return redirect(url_for('main.profile',uname=uname)) @main.route('/user/post',methods = ['GET','POST']) # @login_required def post_blog(): uname = current_user.username form = PostForm() user = User.query.filter_by(username = uname).first() if user is None: abort(404) if form.validate_on_submit: title = form.title.data blog = form.blog.data #users=form.users.data post = Post.query.filter_by(title = title ).first() if post == None: new_post = Post(title = title , blog = blog ) db.session.add(new_post) db.session.commit() return render_template('post_blog.html',form =form) @main.route("/post/<int:post_id>/update", methods=['GET', 'POST']) @login_required def update_post(post_id): post = Post.query.get_or_404(post_id) form = PostForm() if form.validate_on_submit(): post.title = form.title.data post.blog = form.blog.data db.session.add(post) db.session.commit() flash('Your post has been updated!', 'success') return redirect(url_for('post', post_id=post.id)) elif request.method == 'GET': form.title.data = post.title form.blog.data = post.blog return render_template('create_post.html', title='Update Post',form=form, legend='Update Post') @main.route("/post/<int:post_id>/delete", methods=['POST']) @login_required def delete_post(post_id): post = Post.query.get_or_404(post_id) db.session.delete(post) db.session.commit() flash('Your post has been deleted!', 'success') return redirect(url_for('main.view_page')) @main.route("/post/<int:post_id>/comment", methods=["GET", "POST"]) @login_required def comment_post(post_id): comments = Comment.query.filter_by(post_id=post_id).all() post = Post.query.get_or_404(post_id) form = AddCommentForm() if request.method == 'POST': # this only gets executed when the form is submitted and not when the page loads if form.validate_on_submit(): #all_comments = Comment.query.all() comment = Comment(body=form.body.data, article=post) db.session.add(comment) db.session.commit() flash("Your comment has been added to the post", "success") return render_template('views.html',comment=comment) #return redirect(url_for("main.post", post_id=post.id)) return render_template("comment_post.html", title="Comment Post",form=form, post_id=post_id,comment='comment')
[ "flask.render_template", "flask.flash", "app.request.getQuotes", "flask.url_for", "flask.abort" ]
[((404, 415), 'app.request.getQuotes', 'getQuotes', ([], {}), '()\n', (413, 415), False, 'from app.request import getQuotes\n'), ((729, 786), 'flask.render_template', 'render_template', (['"""index.html"""'], {'title': 'title', 'quotes': 'quotes'}), "('index.html', title=title, quotes=quotes)\n", (744, 786), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((873, 923), 'flask.render_template', 'render_template', (['"""views.html"""'], {'all_posts': 'all_posts'}), "('views.html', all_posts=all_posts)\n", (888, 923), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((1583, 1652), 'flask.url_for', 'url_for', (['"""static"""'], {'filename': "('profile_pics/' + current_user.image_file)"}), "('static', filename='profile_pics/' + current_user.image_file)\n", (1590, 1652), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((1664, 1750), 'flask.render_template', 'render_template', (['"""account.html"""'], {'title': '"""Account"""', 'image_file': 'image_file', 'form': 'form'}), "('account.html', title='Account', image_file=image_file,\n form=form)\n", (1679, 1750), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((1883, 1940), 'flask.render_template', 'render_template', (['"""post.html"""'], {'title': 'post.title', 'post': 'post'}), "('post.html', title=post.title, post=post)\n", (1898, 1940), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((2410, 2454), 'flask.render_template', 'render_template', (['"""post_blog.html"""'], {'form': 'form'}), "('post_blog.html', form=form)\n", (2425, 2454), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((3459, 3503), 'flask.render_template', 'render_template', (['"""post_blog.html"""'], {'form': 'form'}), "('post_blog.html', form=form)\n", (3474, 3503), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((4073, 4167), 'flask.render_template', 'render_template', (['"""create_post.html"""'], {'title': '"""Update Post"""', 'form': 'form', 'legend': '"""Update Post"""'}), "('create_post.html', title='Update Post', form=form, legend=\n 'Update Post')\n", (4088, 4167), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((4368, 4415), 'flask.flash', 'flash', (['"""Your post has been deleted!"""', '"""success"""'], {}), "('Your post has been deleted!', 'success')\n", (4373, 4415), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((5290, 5399), 'flask.render_template', 'render_template', (['"""comment_post.html"""'], {'title': '"""Comment Post"""', 'form': 'form', 'post_id': 'post_id', 'comment': '"""comment"""'}), "('comment_post.html', title='Comment Post', form=form,\n post_id=post_id, comment='comment')\n", (5305, 5399), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((1341, 1391), 'flask.flash', 'flash', (['"""Your account has been updated!"""', '"""success"""'], {}), "('Your account has been updated!', 'success')\n", (1346, 1391), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((2165, 2175), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (2170, 2175), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((2824, 2860), 'flask.url_for', 'url_for', (['"""main.profile"""'], {'uname': 'uname'}), "('main.profile', uname=uname)\n", (2831, 2860), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((3096, 3106), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (3101, 3106), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((3850, 3897), 'flask.flash', 'flash', (['"""Your post has been updated!"""', '"""success"""'], {}), "('Your post has been updated!', 'success')\n", (3855, 3897), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((4436, 4461), 'flask.url_for', 'url_for', (['"""main.view_page"""'], {}), "('main.view_page')\n", (4443, 4461), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((1416, 1434), 'flask.url_for', 'url_for', (['"""account"""'], {}), "('account')\n", (1423, 1434), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((3922, 3954), 'flask.url_for', 'url_for', (['"""post"""'], {'post_id': 'post.id'}), "('post', post_id=post.id)\n", (3929, 3954), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((5086, 5145), 'flask.flash', 'flash', (['"""Your comment has been added to the post"""', '"""success"""'], {}), "('Your comment has been added to the post', 'success')\n", (5091, 5145), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n'), ((5165, 5211), 'flask.render_template', 'render_template', (['"""views.html"""'], {'comment': 'comment'}), "('views.html', comment=comment)\n", (5180, 5211), False, 'from flask import render_template, redirect, request, url_for, abort, flash\n')]
"""create user table Revision ID: <PASSWORD> Revises: Create Date: 2021-03-16 21:26:48.338701 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<PASSWORD>' down_revision = None branch_labels = None depends_on = None def upgrade(): op.create_table( 'users', sa.Column('id', sa.Integer, primary_key=True, index=True), sa.Column('email', sa.String, unique=True, index=True, nullable=False), sa.Column('username', sa.String, index=True), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.func.now()), sa.Column('bio', sa.String, index=True), sa.Column('birthdate', sa.Date, index=True), sa.Column('hashed_password', sa.String, nullable=False), sa.Column('confirmation_key', sa.String, nullable=True), sa.Column('account_verified', sa.Boolean, nullable=True, default=False) ) def downgrade(): op.drop_table('users')
[ "alembic.op.drop_table", "sqlalchemy.func.now", "sqlalchemy.Column", "sqlalchemy.DateTime" ]
[((1091, 1113), 'alembic.op.drop_table', 'op.drop_table', (['"""users"""'], {}), "('users')\n", (1104, 1113), False, 'from alembic import op\n'), ((338, 395), 'sqlalchemy.Column', 'sa.Column', (['"""id"""', 'sa.Integer'], {'primary_key': '(True)', 'index': '(True)'}), "('id', sa.Integer, primary_key=True, index=True)\n", (347, 395), True, 'import sqlalchemy as sa\n'), ((405, 475), 'sqlalchemy.Column', 'sa.Column', (['"""email"""', 'sa.String'], {'unique': '(True)', 'index': '(True)', 'nullable': '(False)'}), "('email', sa.String, unique=True, index=True, nullable=False)\n", (414, 475), True, 'import sqlalchemy as sa\n'), ((485, 529), 'sqlalchemy.Column', 'sa.Column', (['"""username"""', 'sa.String'], {'index': '(True)'}), "('username', sa.String, index=True)\n", (494, 529), True, 'import sqlalchemy as sa\n'), ((757, 796), 'sqlalchemy.Column', 'sa.Column', (['"""bio"""', 'sa.String'], {'index': '(True)'}), "('bio', sa.String, index=True)\n", (766, 796), True, 'import sqlalchemy as sa\n'), ((806, 849), 'sqlalchemy.Column', 'sa.Column', (['"""birthdate"""', 'sa.Date'], {'index': '(True)'}), "('birthdate', sa.Date, index=True)\n", (815, 849), True, 'import sqlalchemy as sa\n'), ((859, 914), 'sqlalchemy.Column', 'sa.Column', (['"""hashed_password"""', 'sa.String'], {'nullable': '(False)'}), "('hashed_password', sa.String, nullable=False)\n", (868, 914), True, 'import sqlalchemy as sa\n'), ((924, 979), 'sqlalchemy.Column', 'sa.Column', (['"""confirmation_key"""', 'sa.String'], {'nullable': '(True)'}), "('confirmation_key', sa.String, nullable=True)\n", (933, 979), True, 'import sqlalchemy as sa\n'), ((989, 1060), 'sqlalchemy.Column', 'sa.Column', (['"""account_verified"""', 'sa.Boolean'], {'nullable': '(True)', 'default': '(False)'}), "('account_verified', sa.Boolean, nullable=True, default=False)\n", (998, 1060), True, 'import sqlalchemy as sa\n'), ((563, 589), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {'timezone': '(True)'}), '(timezone=True)\n', (574, 589), True, 'import sqlalchemy as sa\n'), ((672, 698), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {'timezone': '(True)'}), '(timezone=True)\n', (683, 698), True, 'import sqlalchemy as sa\n'), ((624, 637), 'sqlalchemy.func.now', 'sa.func.now', ([], {}), '()\n', (635, 637), True, 'import sqlalchemy as sa\n'), ((733, 746), 'sqlalchemy.func.now', 'sa.func.now', ([], {}), '()\n', (744, 746), True, 'import sqlalchemy as sa\n')]
from twilio.rest import Client def sendotp(otpreci): account_sid = 'ACe8caad8112e2135294377d739ce3e9b9' auth_token = '<PASSWORD>' client = Client(account_sid, auth_token) msg='OTP for Login : ' + str(otpreci) message = client.messages.create( from_='whatsapp:+14155238886', body= msg , to='whatsapp:+918421296860' )
[ "twilio.rest.Client" ]
[((153, 184), 'twilio.rest.Client', 'Client', (['account_sid', 'auth_token'], {}), '(account_sid, auth_token)\n', (159, 184), False, 'from twilio.rest import Client\n')]
# Generated by Django 3.0.7 on 2020-07-30 04:32 from django.db import migrations, models import django.db.models.deletion import tinymce.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Goods', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateField(auto_now_add=True)), ('update_time', models.DateField(auto_now=True)), ('is_delete', models.BooleanField(default=False)), ('name', models.CharField(max_length=50)), ('detail', tinymce.models.HTMLField()), ], options={ 'verbose_name': 'Goods', 'verbose_name_plural': 'Goodses', 'db_table': 'df_goods', 'managed': True, }, ), migrations.CreateModel( name='GoodsSKU', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateField(auto_now_add=True)), ('update_time', models.DateField(auto_now=True)), ('is_delete', models.BooleanField(default=False)), ('name', models.CharField(max_length=50)), ('desc', models.CharField(max_length=256)), ('price', models.DecimalField(decimal_places=2, max_digits=10)), ('unit', models.CharField(max_length=50)), ('sales', models.IntegerField(default=0)), ('stock', models.IntegerField(default=0)), ('image', models.ImageField(upload_to='')), ('status', models.SmallIntegerField(choices=[(0, '下线'), (1, '上线')], default=1)), ('goods', models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='goods.Goods')), ], options={ 'verbose_name': 'GoodsSKU', 'verbose_name_plural': 'GoodsSKUs', 'db_table': 'df_goods_sku', 'managed': True, }, ), migrations.CreateModel( name='GoodsType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateField(auto_now_add=True)), ('update_time', models.DateField(auto_now=True)), ('is_delete', models.BooleanField(default=False)), ('name', models.CharField(max_length=50)), ('logo', models.CharField(max_length=50)), ('image', models.ImageField(upload_to='')), ], options={ 'verbose_name': 'GoodsType', 'verbose_name_plural': 'GoodsTypes', 'db_table': 'df_goods_type', 'managed': True, }, ), migrations.CreateModel( name='IndexPromotionBanner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateField(auto_now_add=True)), ('update_time', models.DateField(auto_now=True)), ('is_delete', models.BooleanField(default=False)), ('name', models.CharField(max_length=50)), ('image', models.ImageField(upload_to='')), ('url', models.URLField()), ('index', models.SmallIntegerField(default=0)), ], options={ 'verbose_name': 'IndexPromotionBanner', 'verbose_name_plural': 'IndexPromotionBanners', 'db_table': 'df_index_promotion_banner', 'managed': True, }, ), migrations.CreateModel( name='IndexTypeGoodsBanner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateField(auto_now_add=True)), ('update_time', models.DateField(auto_now=True)), ('is_delete', models.BooleanField(default=False)), ('index', models.SmallIntegerField(default=0)), ('display_type', models.SmallIntegerField(choices=[(0, '标题'), (1, '图片')], default=1)), ('goods_sku', models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='goods.GoodsSKU')), ('goods_type', models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='goods.GoodsType')), ], options={ 'verbose_name': 'IndexTypeGoodsBanner', 'verbose_name_plural': 'IndexTypeGoodsBanners', 'db_table': 'df_index_type_goods_banner', 'managed': True, }, ), migrations.CreateModel( name='IndexGoodsBanner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateField(auto_now_add=True)), ('update_time', models.DateField(auto_now=True)), ('is_delete', models.BooleanField(default=False)), ('image', models.ImageField(upload_to='')), ('index', models.SmallIntegerField(default=0)), ('goods_sku', models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='goods.GoodsSKU')), ], options={ 'verbose_name': 'IndexGoodsBanner', 'verbose_name_plural': 'IndexGoodsBanners', 'db_table': 'df_index_goods_banner', 'managed': True, }, ), migrations.AddField( model_name='goodssku', name='goods_type', field=models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='goods.GoodsType'), ), migrations.CreateModel( name='GoodsImage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create_time', models.DateField(auto_now_add=True)), ('update_time', models.DateField(auto_now=True)), ('is_delete', models.BooleanField(default=False)), ('image', models.ImageField(upload_to='')), ('goods_sku', models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='goods.GoodsSKU')), ], options={ 'verbose_name': 'GoodsImage', 'verbose_name_plural': 'GoodsImages', 'db_table': '', 'managed': True, }, ), ]
[ "django.db.models.DateField", "django.db.models.ForeignKey", "django.db.models.IntegerField", "django.db.models.BooleanField", "django.db.models.AutoField", "django.db.models.SmallIntegerField", "django.db.models.ImageField", "django.db.models.DecimalField", "django.db.models.URLField", "django.db...
[((6195, 6305), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'db_constraint': '(False)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""goods.GoodsType"""'}), "(db_constraint=False, on_delete=django.db.models.deletion.\n CASCADE, to='goods.GoodsType')\n", (6212, 6305), False, 'from django.db import migrations, models\n'), ((356, 449), '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", (372, 449), False, 'from django.db import migrations, models\n'), ((480, 515), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (496, 515), False, 'from django.db import migrations, models\n'), ((550, 581), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (566, 581), False, 'from django.db import migrations, models\n'), ((614, 648), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (633, 648), False, 'from django.db import migrations, models\n'), ((676, 707), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (692, 707), False, 'from django.db import migrations, models\n'), ((1098, 1191), '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", (1114, 1191), False, 'from django.db import migrations, models\n'), ((1222, 1257), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (1238, 1257), False, 'from django.db import migrations, models\n'), ((1292, 1323), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (1308, 1323), False, 'from django.db import migrations, models\n'), ((1356, 1390), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1375, 1390), False, 'from django.db import migrations, models\n'), ((1418, 1449), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (1434, 1449), False, 'from django.db import migrations, models\n'), ((1477, 1509), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)'}), '(max_length=256)\n', (1493, 1509), False, 'from django.db import migrations, models\n'), ((1538, 1590), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'decimal_places': '(2)', 'max_digits': '(10)'}), '(decimal_places=2, max_digits=10)\n', (1557, 1590), False, 'from django.db import migrations, models\n'), ((1618, 1649), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (1634, 1649), False, 'from django.db import migrations, models\n'), ((1678, 1708), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1697, 1708), False, 'from django.db import migrations, models\n'), ((1737, 1767), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (1756, 1767), False, 'from django.db import migrations, models\n'), ((1796, 1827), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '""""""'}), "(upload_to='')\n", (1813, 1827), False, 'from django.db import migrations, models\n'), ((1857, 1924), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'choices': "[(0, '下线'), (1, '上线')]", 'default': '(1)'}), "(choices=[(0, '下线'), (1, '上线')], default=1)\n", (1881, 1924), False, 'from django.db import migrations, models\n'), ((1953, 2059), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'db_constraint': '(False)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""goods.Goods"""'}), "(db_constraint=False, on_delete=django.db.models.deletion.\n CASCADE, to='goods.Goods')\n", (1970, 2059), False, 'from django.db import migrations, models\n'), ((2399, 2492), '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", (2415, 2492), False, 'from django.db import migrations, models\n'), ((2523, 2558), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (2539, 2558), False, 'from django.db import migrations, models\n'), ((2593, 2624), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (2609, 2624), False, 'from django.db import migrations, models\n'), ((2657, 2691), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (2676, 2691), False, 'from django.db import migrations, models\n'), ((2719, 2750), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (2735, 2750), False, 'from django.db import migrations, models\n'), ((2778, 2809), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (2794, 2809), False, 'from django.db import migrations, models\n'), ((2838, 2869), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '""""""'}), "(upload_to='')\n", (2855, 2869), False, 'from django.db import migrations, models\n'), ((3228, 3321), '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", (3244, 3321), False, 'from django.db import migrations, models\n'), ((3352, 3387), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (3368, 3387), False, 'from django.db import migrations, models\n'), ((3422, 3453), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (3438, 3453), False, 'from django.db import migrations, models\n'), ((3486, 3520), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (3505, 3520), False, 'from django.db import migrations, models\n'), ((3548, 3579), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (3564, 3579), False, 'from django.db import migrations, models\n'), ((3608, 3639), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '""""""'}), "(upload_to='')\n", (3625, 3639), False, 'from django.db import migrations, models\n'), ((3666, 3683), 'django.db.models.URLField', 'models.URLField', ([], {}), '()\n', (3681, 3683), False, 'from django.db import migrations, models\n'), ((3712, 3747), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (3736, 3747), False, 'from django.db import migrations, models\n'), ((4140, 4233), '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", (4156, 4233), False, 'from django.db import migrations, models\n'), ((4264, 4299), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (4280, 4299), False, 'from django.db import migrations, models\n'), ((4334, 4365), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (4350, 4365), False, 'from django.db import migrations, models\n'), ((4398, 4432), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (4417, 4432), False, 'from django.db import migrations, models\n'), ((4461, 4496), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (4485, 4496), False, 'from django.db import migrations, models\n'), ((4532, 4599), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'choices': "[(0, '标题'), (1, '图片')]", 'default': '(1)'}), "(choices=[(0, '标题'), (1, '图片')], default=1)\n", (4556, 4599), False, 'from django.db import migrations, models\n'), ((4632, 4741), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'db_constraint': '(False)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""goods.GoodsSKU"""'}), "(db_constraint=False, on_delete=django.db.models.deletion.\n CASCADE, to='goods.GoodsSKU')\n", (4649, 4741), False, 'from django.db import migrations, models\n'), ((4770, 4880), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'db_constraint': '(False)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""goods.GoodsType"""'}), "(db_constraint=False, on_delete=django.db.models.deletion.\n CASCADE, to='goods.GoodsType')\n", (4787, 4880), False, 'from django.db import migrations, models\n'), ((5265, 5358), '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", (5281, 5358), False, 'from django.db import migrations, models\n'), ((5389, 5424), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (5405, 5424), False, 'from django.db import migrations, models\n'), ((5459, 5490), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (5475, 5490), False, 'from django.db import migrations, models\n'), ((5523, 5557), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (5542, 5557), False, 'from django.db import migrations, models\n'), ((5586, 5617), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '""""""'}), "(upload_to='')\n", (5603, 5617), False, 'from django.db import migrations, models\n'), ((5646, 5681), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (5670, 5681), False, 'from django.db import migrations, models\n'), ((5714, 5823), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'db_constraint': '(False)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""goods.GoodsSKU"""'}), "(db_constraint=False, on_delete=django.db.models.deletion.\n CASCADE, to='goods.GoodsSKU')\n", (5731, 5823), False, 'from django.db import migrations, models\n'), ((6420, 6513), '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", (6436, 6513), False, 'from django.db import migrations, models\n'), ((6544, 6579), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (6560, 6579), False, 'from django.db import migrations, models\n'), ((6614, 6645), 'django.db.models.DateField', 'models.DateField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (6630, 6645), False, 'from django.db import migrations, models\n'), ((6678, 6712), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (6697, 6712), False, 'from django.db import migrations, models\n'), ((6741, 6772), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '""""""'}), "(upload_to='')\n", (6758, 6772), False, 'from django.db import migrations, models\n'), ((6805, 6914), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'db_constraint': '(False)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""goods.GoodsSKU"""'}), "(db_constraint=False, on_delete=django.db.models.deletion.\n CASCADE, to='goods.GoodsSKU')\n", (6822, 6914), False, 'from django.db import migrations, models\n')]
import urllib.request as ur from bs4 import BeautifulSoup as soup def find_productF(search): header = { 'User-Agent' : 'Mozilla/5.0' } link=["_3wU53n","_2cLu-l","_2B_pmu"] search=search.replace(" ","%20") urlF= "https://www.flipkart.com/search?q={}&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off".format(search) req=ur.Request(urlF,None,header) uClient = ur.urlopen(req) page = uClient.read() uClient.close() psoup = soup(page, "html.parser") contain=[] for k in link: for a in psoup.findAll("a",{"class":k}): contain.append(a) for a in psoup.findAll("div",{"class":k}): contain.append(a) contain=contain[0:5] price = psoup.findAll("div",{"class":"_1vC4OE"}) p={} for i in contain: for j in price: p[i.text] = j.text price.remove(j) break return p #search=input("enter product to be search : ") #find_product(search)
[ "bs4.BeautifulSoup", "urllib.request.Request", "urllib.request.urlopen" ]
[((372, 402), 'urllib.request.Request', 'ur.Request', (['urlF', 'None', 'header'], {}), '(urlF, None, header)\n', (382, 402), True, 'import urllib.request as ur\n'), ((416, 431), 'urllib.request.urlopen', 'ur.urlopen', (['req'], {}), '(req)\n', (426, 431), True, 'import urllib.request as ur\n'), ((494, 519), 'bs4.BeautifulSoup', 'soup', (['page', '"""html.parser"""'], {}), "(page, 'html.parser')\n", (498, 519), True, 'from bs4 import BeautifulSoup as soup\n')]
# https://practice.geeksforgeeks.org/problems/save-ironman/0 import re a = 'Ab?/Ba' pattern = r'\w+' matches = re.findall(pattern, a) the_string = ''.join(matches) print(the_string) half_len = len(the_string) // 2 part_1 = list(the_string[:half_len+1]) part_2 = list(the_string[-half_len:]) part_2.reverse() for char1, char2 in zip(part_1, part_2): #print(char1.upper(), char2.upper()) if char1.upper() != char2.upper(): print('False') print('True')
[ "re.findall" ]
[((112, 134), 're.findall', 're.findall', (['pattern', 'a'], {}), '(pattern, a)\n', (122, 134), False, 'import re\n')]
import json import requests import time import webbrowser import sys from logger import Logger class DiscordApi: def __init__(self): self.api_endpoint = 'https://discord.com/api/v9' with open("secrets.json") as f: self.secrets = json.load(f) self.headers = {"Authorization": f"Bot {self.secrets['bot_token']}"} self.bot_id = None def launch_bot_auth(self): webbrowser.open(f"{self.api_endpoint}/oauth2/authorize?client_id={self.secrets['client_id']}&scope=bot&permissions=134217728&guild_id={self.secrets['guild_id']}&disable_guild_select=true") def get_bot_id(self): if self.bot_id is None: r = requests.get(f"{self.api_endpoint}/users/@me", headers=self.headers) r.raise_for_status() self.bot_id = r.json()['id'] return self.bot_id def get_guild_member(self, discord_id): r = requests.get(f"{self.api_endpoint}/guilds/{self.secrets['guild_id']}/members/{discord_id}", headers=self.headers) r.raise_for_status() return r.json() def get_guild_members(self): params = {"limit": 1000} r = requests.get(f"{self.api_endpoint}/guilds/{self.secrets['guild_id']}/members", params=params, headers=self.headers) r.raise_for_status() return r.json() def get_guild_member_ids(self): ids = [] for guild_member in self.get_guild_members(): ids.append(guild_member['user']['id']) return ids def set_nickname(self, discord_id, nickname): Logger.log(f"Setting {discord_id} to \"{nickname}\"") body = {"nick": nickname} r = requests.patch(f"{self.api_endpoint}/guilds/{self.secrets['guild_id']}/members/{discord_id}", json=body, headers=self.headers) response = r.json() try: r.raise_for_status() except Exception as e: Logger.log(response) Logger.log(e) if "retry_after" in response: delay = response["retry_after"] Logger.log(f"Waiting {delay} seconds.") time.sleep(delay) response = self.set_nickname(discord_id, nickname) return response def use_test_guild(self): self.secrets["guild_id"] = self.secrets["test_guild_id"] if __name__ == "__main__": api = DiscordApi() api.use_test_guild() if len(sys.argv) > 1 and sys.argv[1] == "auth": api.launch_bot_auth() else: Logger.log(api.get_guild_members()) Logger.log(api.get_bot_id())
[ "requests.patch", "webbrowser.open", "requests.get", "time.sleep", "logger.Logger.log", "json.load" ]
[((421, 619), 'webbrowser.open', 'webbrowser.open', (['f"""{self.api_endpoint}/oauth2/authorize?client_id={self.secrets[\'client_id\']}&scope=bot&permissions=134217728&guild_id={self.secrets[\'guild_id\']}&disable_guild_select=true"""'], {}), '(\n f"{self.api_endpoint}/oauth2/authorize?client_id={self.secrets[\'client_id\']}&scope=bot&permissions=134217728&guild_id={self.secrets[\'guild_id\']}&disable_guild_select=true"\n )\n', (436, 619), False, 'import webbrowser\n'), ((912, 1035), 'requests.get', 'requests.get', (['f"""{self.api_endpoint}/guilds/{self.secrets[\'guild_id\']}/members/{discord_id}"""'], {'headers': 'self.headers'}), '(\n f"{self.api_endpoint}/guilds/{self.secrets[\'guild_id\']}/members/{discord_id}"\n , headers=self.headers)\n', (924, 1035), False, 'import requests\n'), ((1158, 1277), 'requests.get', 'requests.get', (['f"""{self.api_endpoint}/guilds/{self.secrets[\'guild_id\']}/members"""'], {'params': 'params', 'headers': 'self.headers'}), '(f"{self.api_endpoint}/guilds/{self.secrets[\'guild_id\']}/members",\n params=params, headers=self.headers)\n', (1170, 1277), False, 'import requests\n'), ((1564, 1615), 'logger.Logger.log', 'Logger.log', (['f"""Setting {discord_id} to "{nickname}\\""""'], {}), '(f\'Setting {discord_id} to "{nickname}"\')\n', (1574, 1615), False, 'from logger import Logger\n'), ((1664, 1800), 'requests.patch', 'requests.patch', (['f"""{self.api_endpoint}/guilds/{self.secrets[\'guild_id\']}/members/{discord_id}"""'], {'json': 'body', 'headers': 'self.headers'}), '(\n f"{self.api_endpoint}/guilds/{self.secrets[\'guild_id\']}/members/{discord_id}"\n , json=body, headers=self.headers)\n', (1678, 1800), False, 'import requests\n'), ((264, 276), 'json.load', 'json.load', (['f'], {}), '(f)\n', (273, 276), False, 'import json\n'), ((685, 753), 'requests.get', 'requests.get', (['f"""{self.api_endpoint}/users/@me"""'], {'headers': 'self.headers'}), "(f'{self.api_endpoint}/users/@me', headers=self.headers)\n", (697, 753), False, 'import requests\n'), ((1908, 1928), 'logger.Logger.log', 'Logger.log', (['response'], {}), '(response)\n', (1918, 1928), False, 'from logger import Logger\n'), ((1941, 1954), 'logger.Logger.log', 'Logger.log', (['e'], {}), '(e)\n', (1951, 1954), False, 'from logger import Logger\n'), ((2061, 2100), 'logger.Logger.log', 'Logger.log', (['f"""Waiting {delay} seconds."""'], {}), "(f'Waiting {delay} seconds.')\n", (2071, 2100), False, 'from logger import Logger\n'), ((2117, 2134), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (2127, 2134), False, 'import time\n')]
#!/usr/bin/env python """ Setup file created """ from setuptools import setup setup(name='pyqm', version='0.1', description='', url='https://github.com/suracefm/pyqm', author='<NAME>', license='BSD 3 New', packages = ['pyqm'] )
[ "setuptools.setup" ]
[((79, 235), 'setuptools.setup', 'setup', ([], {'name': '"""pyqm"""', 'version': '"""0.1"""', 'description': '""""""', 'url': '"""https://github.com/suracefm/pyqm"""', 'author': '"""<NAME>"""', 'license': '"""BSD 3 New"""', 'packages': "['pyqm']"}), "(name='pyqm', version='0.1', description='', url=\n 'https://github.com/suracefm/pyqm', author='<NAME>', license=\n 'BSD 3 New', packages=['pyqm'])\n", (84, 235), False, 'from setuptools import setup\n')]
#!/usr/bin/env python3 import sys import rospy import cv2 from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class ImageGrabber: def __init__(self): self.bridge = CvBridge() self.image_sub = rospy.Subscriber("main_camera/image_raw", Image, self.callback) def callback(self, data): try: cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) cv2.imshow("Image window", cv_image) cv2.waitKey(3) if __name__ == '__main__': ig = ImageGrabber() rospy.init_node('image_grabber', anonymous=True) try: rospy.spin() except KeyboardInterrupt: print("Shutting down") cv2.destroyAllWindows()
[ "rospy.init_node", "cv2.imshow", "cv_bridge.CvBridge", "cv2.destroyAllWindows", "rospy.spin", "rospy.Subscriber", "cv2.waitKey" ]
[((599, 647), 'rospy.init_node', 'rospy.init_node', (['"""image_grabber"""'], {'anonymous': '(True)'}), "('image_grabber', anonymous=True)\n", (614, 647), False, 'import rospy\n'), ((743, 766), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (764, 766), False, 'import cv2\n'), ((208, 218), 'cv_bridge.CvBridge', 'CvBridge', ([], {}), '()\n', (216, 218), False, 'from cv_bridge import CvBridge, CvBridgeError\n'), ((244, 307), 'rospy.Subscriber', 'rospy.Subscriber', (['"""main_camera/image_raw"""', 'Image', 'self.callback'], {}), "('main_camera/image_raw', Image, self.callback)\n", (260, 307), False, 'import rospy\n'), ((482, 518), 'cv2.imshow', 'cv2.imshow', (['"""Image window"""', 'cv_image'], {}), "('Image window', cv_image)\n", (492, 518), False, 'import cv2\n'), ((527, 541), 'cv2.waitKey', 'cv2.waitKey', (['(3)'], {}), '(3)\n', (538, 541), False, 'import cv2\n'), ((665, 677), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (675, 677), False, 'import rospy\n')]
import csv from site_crawler.cleaner.cleaner import Cleaner class Dataset_Builder: def __init__(self): self.cleaner = Cleaner() self.create_csv_headers() def create_csv_headers(self): csv_files = [ 'negative_sentiment', 'positive_sentiment', 'dataset_sentiment' ] for csv_file in csv_files: with open('../data/dataset/csv/' + csv_file + '.csv', 'a') as f: writer = csv.writer(f) writer.writerow(["text", "label"]) def write_tweet_txt(self, sentiment, name): file = open('../data/dataset/txt/'+name+ '.txt', 'a') line = sentiment.strip() cleaned_line = self.cleaner.clean_tweets(line) file.write(cleaned_line) file.write('\n') def write_tweet_csv(self, sentiment, name, polarity): with open('../data/dataset/csv/' + name + '.csv', 'a') as f: writer = csv.writer(f) line = sentiment.strip() cleaned_line = self.cleaner.clean_tweets(line) writer.writerow([cleaned_line,polarity, ]) pass def extract_sentiment_csv(self,csv_name): with open('../data/twitter_data/labeled_data/unlabeled_'+csv_name+'.csv', newline='', encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile) for row in reader: # negative if row['label'] == '-1': self.write_tweet_txt(row['text'].strip(), 'negative_sentiment.txt') self.write_tweet_csv(row['text'].strip(), 'negative_sentiment','-1') self.write_tweet_csv(row['text'].strip(), 'dataset_sentiment','-1') # positive elif row['label'] == '1': self.write_tweet_txt(row['text'].strip(), 'positive_sentiment') self.write_tweet_csv(row['text'].strip(), 'positive_sentiment', '1') self.write_tweet_csv(row['text'].strip(), 'dataset_sentiment', '1') # neutral / irrelevant elif row['label'] == '0': self.write_tweet_txt(row['text'].strip(), 'neutral') if __name__ == "__main__": D_builder = Dataset_Builder() tweets_csvs = [ 'Business_KE', 'MadeItInAfrica', 'IFCAfrica', 'africareview', 'AfDB_Group', '_AfricanUnion', 'Taifa_Leo', 'BD_Africa', 'RadioCitizenFM', 'citizentvkenya', 'KTNKenya', 'K24Tv', 'StandardKenya', 'TheStarKenya', 'radiomaisha', 'KBCChannel1', 'CapitalFMKenya', 'African_Markets', 'Africafinancial', 'InvestInAfrica', 'AfricanInvestor', 'forbesafrica', 'cnbcafrica', 'BBCAfrica', 'CNNAfrica', 'allafrica', 'ReutersAfrica', 'VenturesAfrica', 'BBGAfrica', 'GhettoRadio895', 'kenyanwalstreet', 'SokoAnalyst', 'NSEKenya', 'wazua' ] for tweets_csv in tweets_csvs: D_builder.extract_sentiment_csv(tweets_csv)
[ "site_crawler.cleaner.cleaner.Cleaner", "csv.writer", "csv.DictReader" ]
[((131, 140), 'site_crawler.cleaner.cleaner.Cleaner', 'Cleaner', ([], {}), '()\n', (138, 140), False, 'from site_crawler.cleaner.cleaner import Cleaner\n'), ((950, 963), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (960, 963), False, 'import csv\n'), ((1320, 1343), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {}), '(csvfile)\n', (1334, 1343), False, 'import csv\n'), ((479, 492), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (489, 492), False, 'import csv\n')]
import filecmp import os def are_files_equal(file1, file2): """ :param file1: :param file2: :return: bool - if files content is equal """ file1_input = open(os.getcwd() + file1, "r") file2_input = open(os.getcwd() + file2, "r") line1 = file1_input.readlines() line2 = file2_input.readlines() for i in range(len(line1)): if line1[i] != line2[i]: file1_input.close() file2_input.close() return False file1_input.close() file2_input.close() return True # return filecmp.cmp(os.getcwd() + r"\file1", os.getcwd() + r"\file2") # ANOTHER EASY WAY OF COMPARING def main(): print(are_files_equal(r"\file1", r"\file2")) if __name__ == '__main__': main()
[ "os.getcwd" ]
[((183, 194), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (192, 194), False, 'import os\n'), ((232, 243), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (241, 243), False, 'import os\n')]
_this_pdbrc_unic_459f279ea52642e4bd9f38b32ad284e9 = 1 # enable simple tab completion (do it on top to avoid side effects) import pdb import rlcompleter pdb.Pdb.complete = rlcompleter.Completer(locals()).complete # save indent! respect youself import bdb import linecache if (not hasattr(bdb.Bdb , "_format_stack_entry_bak")): setattr(bdb.Bdb, "_format_stack_entry_bak", bdb.Bdb.format_stack_entry) def ___new_format_stack_entry(self, frame_lineno, lprefix=': '): import linecache frame, lineno = frame_lineno # prefix "\n%3d: " used to be comparable by indent with output of "l" command ret = bdb.Bdb._format_stack_entry_bak(self, frame_lineno, "\n%3d: " % lineno) filename = self.canonic(frame.f_code.co_filename) line = linecache.getline(filename, lineno, frame.f_globals) if line: # hope that naked "strip" was used unintentionally # bold print \033[1m .. \033[0m ret = ret.replace(line.strip(), "\033[1m"+line.rstrip()+"\033[0m") return ret setattr(bdb.Bdb, "format_stack_entry", ___new_format_stack_entry) # I awaited this too long. A simple thing but so useful def ___exec_whithout_success_code(some): ret = os.system(some) return ret if ret else None
[ "linecache.getline", "bdb.Bdb._format_stack_entry_bak" ]
[((638, 712), 'bdb.Bdb._format_stack_entry_bak', 'bdb.Bdb._format_stack_entry_bak', (['self', 'frame_lineno', "('\\n%3d: ' % lineno)"], {}), "(self, frame_lineno, '\\n%3d: ' % lineno)\n", (669, 712), False, 'import bdb\n'), ((786, 838), 'linecache.getline', 'linecache.getline', (['filename', 'lineno', 'frame.f_globals'], {}), '(filename, lineno, frame.f_globals)\n', (803, 838), False, 'import linecache\n')]
import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf import numpy as np from tensorflow import keras from pandas.plotting import autocorrelation_plot from keras import Sequential from tensorflow.python.keras.layers.recurrent import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import OneHotEncoder from random import randint import sys df = pd.read_csv(r'C:\Users\Michael\Desktop\pwrball_rand\pwr_ball - Copy.csv') trim = df.drop(['prize', 'daysin','daycos','year'], axis=1) #print(trim) sequence = trim.values.reshape(-1,1).tolist() #print(sequence) ohe = OneHotEncoder().fit(sequence) encoded_trim = ohe.transform(sequence).toarray() #np.set_printoptions(threshold=sys.maxsize) row, col = encoded_trim.shape def gen_sample(num_start): #start_of_sample = randint(0,17436) #print(start_of_sample) sample_X = encoded_trim[num_start:num_start + 6, :] sample_Y = encoded_trim[num_start+6:num_start+7, :] sample_X = sample_X.reshape(1,6,69) #sample_Y = sample_Y.reshape(1,1,69) #print(sample_X.shape) #print(sample_Y.shape) return sample_X, sample_Y #this_x, this_y = gen_sample(0) model = Sequential() model.add(LSTM(138, input_shape = (6,69), return_sequences = True)) model.add(LSTM(69, input_shape = (6,69))) model.add(tf.keras.layers.Dense(69, activation='softmax')) model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.05), loss="categorical_crossentropy") model.summary() test_num = [9,36,49,56,62,9] #june 27 test_num = np.asarray(test_num) test_num = test_num.reshape(-1,1) test_num_encode = ohe.transform(test_num).toarray() #print(test_num_encode) test_sample = test_num_encode.reshape(1,6,69) for i in range(17429): X, y = gen_sample(i) model.fit(X,y,epochs=1, verbose=2) #model.reset_states() test_out = model.predict(test_sample) test_out = ohe.inverse_transform(test_out) print(test_out) #expect 15 #test nums: #9,36,49,56,62,8 #lstm_input_dataframe = pd.DataFrame(np.concatenate(lstm_input_unsplit)) #decoded_trim = ohe.inverse_transform(encoded_trim) #print(type(decoded_trim))
[ "keras.Sequential", "pandas.read_csv", "sklearn.preprocessing.OneHotEncoder", "numpy.asarray", "tensorflow.python.keras.layers.recurrent.LSTM", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.Dense" ]
[((412, 489), 'pandas.read_csv', 'pd.read_csv', (['"""C:\\\\Users\\\\Michael\\\\Desktop\\\\pwrball_rand\\\\pwr_ball - Copy.csv"""'], {}), "('C:\\\\Users\\\\Michael\\\\Desktop\\\\pwrball_rand\\\\pwr_ball - Copy.csv')\n", (423, 489), True, 'import pandas as pd\n'), ((1243, 1255), 'keras.Sequential', 'Sequential', ([], {}), '()\n', (1253, 1255), False, 'from keras import Sequential\n'), ((1606, 1626), 'numpy.asarray', 'np.asarray', (['test_num'], {}), '(test_num)\n', (1616, 1626), True, 'import numpy as np\n'), ((1267, 1320), 'tensorflow.python.keras.layers.recurrent.LSTM', 'LSTM', (['(138)'], {'input_shape': '(6, 69)', 'return_sequences': '(True)'}), '(138, input_shape=(6, 69), return_sequences=True)\n', (1271, 1320), False, 'from tensorflow.python.keras.layers.recurrent import LSTM\n'), ((1336, 1365), 'tensorflow.python.keras.layers.recurrent.LSTM', 'LSTM', (['(69)'], {'input_shape': '(6, 69)'}), '(69, input_shape=(6, 69))\n', (1340, 1365), False, 'from tensorflow.python.keras.layers.recurrent import LSTM\n'), ((1379, 1426), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(69)'], {'activation': '"""softmax"""'}), "(69, activation='softmax')\n", (1400, 1426), True, 'import tensorflow as tf\n'), ((641, 656), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {}), '()\n', (654, 656), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((1457, 1498), 'tensorflow.keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'learning_rate': '(0.05)'}), '(learning_rate=0.05)\n', (1478, 1498), False, 'from tensorflow import keras\n')]
import boto3 def get_lambda_client(access_key, secret_key, region): return boto3.client( "lambda", region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) def check_function_exists(function_name, access_key, secret_key, region): client = get_lambda_client(access_key, secret_key, region) try: response = client.get_function(FunctionName=function_name) return True if response['Configuration'] else False except: return False
[ "boto3.client" ]
[((81, 191), 'boto3.client', 'boto3.client', (['"""lambda"""'], {'region_name': 'region', 'aws_access_key_id': 'access_key', 'aws_secret_access_key': 'secret_key'}), "('lambda', region_name=region, aws_access_key_id=access_key,\n aws_secret_access_key=secret_key)\n", (93, 191), False, 'import boto3\n')]
# Generated by Django 3.1 on 2020-09-20 22:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0007_auto_20200920_1813'), ] operations = [ migrations.AddField( model_name='student', name='group', field=models.ManyToManyField(null=True, to='api.Group'), ), migrations.DeleteModel( name='PartOf', ), ]
[ "django.db.migrations.DeleteModel", "django.db.models.ManyToManyField" ]
[((398, 435), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', ([], {'name': '"""PartOf"""'}), "(name='PartOf')\n", (420, 435), False, 'from django.db import migrations, models\n'), ((328, 377), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'null': '(True)', 'to': '"""api.Group"""'}), "(null=True, to='api.Group')\n", (350, 377), False, 'from django.db import migrations, models\n')]
from setuptools import setup setup(name='geomle', version='1.0', description='Intrinsic dimension', url='https://github.com/premolab/GeoMLE', author='<NAME>, <NAME>', author_email='<EMAIL> ', license='MIT', packages=['geomle'], install_requires=[ 'numpy>=1.13.1', 'scikit-learn>=0.18', 'pandas>=0.19', ], zip_safe=False)
[ "setuptools.setup" ]
[((30, 336), 'setuptools.setup', 'setup', ([], {'name': '"""geomle"""', 'version': '"""1.0"""', 'description': '"""Intrinsic dimension"""', 'url': '"""https://github.com/premolab/GeoMLE"""', 'author': '"""<NAME>, <NAME>"""', 'author_email': '"""<EMAIL> """', 'license': '"""MIT"""', 'packages': "['geomle']", 'install_requires': "['numpy>=1.13.1', 'scikit-learn>=0.18', 'pandas>=0.19']", 'zip_safe': '(False)'}), "(name='geomle', version='1.0', description='Intrinsic dimension', url=\n 'https://github.com/premolab/GeoMLE', author='<NAME>, <NAME>',\n author_email='<EMAIL> ', license='MIT', packages=['geomle'],\n install_requires=['numpy>=1.13.1', 'scikit-learn>=0.18', 'pandas>=0.19'\n ], zip_safe=False)\n", (35, 336), False, 'from setuptools import setup\n')]
""" Created on 19/06/2020 @author: <NAME> """ from Data_manager.Dataset import Dataset from Data_manager.IncrementalSparseMatrix import IncrementalSparseMatrix_FilterIDs from pandas.api.types import is_string_dtype import pandas as pd def _add_keys_to_mapper(key_to_value_mapper, new_key_list): for new_key in new_key_list: if new_key not in key_to_value_mapper: new_value = len(key_to_value_mapper) key_to_value_mapper[new_key] = new_value return key_to_value_mapper class DatasetMapperManager(object): """ This class is used to build a Dataset object The DatasetMapperManager object takes as input the original data in dataframes. The required columns are: - URM: "UserID", "ItemID", "Data" - ICM: "ItemID", "FeatureID", "Data" - UCM: "UserID", "FeatureID", "Data" The data type of the "Data" columns can be any, the "ItemID", "UserID", "FeatureID" data types MUST be strings. How to use it: - First add all the necessary data calling the add_URM, add_ICM, add_UCM functions - Then call the generate_Dataset function(dataset_name, is_implicit) to obtain the Dataset object. The generate_Dataset function will first transform all "ItemID", "UserID", "FeatureID" into unique numerical indices and represent all of them as sparse matrices: URM, ICM, UCM. """ URM_DICT = None URM_mapper_DICT = None ICM_DICT = None ICM_mapper_DICT = None UCM_DICT = None UCM_mapper_DICT = None user_original_ID_to_index = None item_original_ID_to_index = None __Dataset_finalized = False def __init__(self): super(DatasetMapperManager, self).__init__() self.URM_DICT = {} self.URM_mapper_DICT = {} self.ICM_DICT = {} self.ICM_mapper_DICT = {} self.UCM_DICT = {} self.UCM_mapper_DICT = {} self.__Dataset_finalized = False def generate_Dataset(self, dataset_name, is_implicit): assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" self.__Dataset_finalized = True # Generate ID to index mappers self._generate_global_mappers() self._generate_ICM_UCM_mappers() URM_DICT_sparse = {} ICM_DICT_sparse = {} UCM_DICT_sparse = {} on_new_ID = "ignore" for URM_name, URM_dataframe in self.URM_DICT.items(): URM_sparse_builder = IncrementalSparseMatrix_FilterIDs(preinitialized_col_mapper = self.item_original_ID_to_index, preinitialized_row_mapper = self.user_original_ID_to_index, on_new_col = on_new_ID, on_new_row = on_new_ID) URM_sparse_builder.add_data_lists(URM_dataframe["UserID"].values, URM_dataframe["ItemID"].values, URM_dataframe["Data"].values) URM_DICT_sparse[URM_name] = URM_sparse_builder.get_SparseMatrix() for ICM_name, ICM_dataframe in self.ICM_DICT.items(): feature_ID_to_index = self.ICM_mapper_DICT[ICM_name] ICM_sparse_builder = IncrementalSparseMatrix_FilterIDs(preinitialized_col_mapper = feature_ID_to_index, preinitialized_row_mapper = self.item_original_ID_to_index, on_new_col = on_new_ID, on_new_row = on_new_ID) ICM_sparse_builder.add_data_lists(ICM_dataframe["ItemID"].values, ICM_dataframe["FeatureID"].values, ICM_dataframe["Data"].values) ICM_DICT_sparse[ICM_name] = ICM_sparse_builder.get_SparseMatrix() for UCM_name, UCM_dataframe in self.UCM_DICT.items(): feature_ID_to_index = self.UCM_mapper_DICT[UCM_name] UCM_sparse_builder = IncrementalSparseMatrix_FilterIDs(preinitialized_col_mapper = feature_ID_to_index, preinitialized_row_mapper = self.user_original_ID_to_index, on_new_col = on_new_ID, on_new_row = on_new_ID) UCM_sparse_builder.add_data_lists(UCM_dataframe["UserID"].values, UCM_dataframe["FeatureID"].values, UCM_dataframe["Data"].values) UCM_DICT_sparse[UCM_name] = UCM_sparse_builder.get_SparseMatrix() loaded_dataset = Dataset(dataset_name=dataset_name, URM_dictionary=URM_DICT_sparse, ICM_dictionary=ICM_DICT_sparse, ICM_feature_mapper_dictionary=self.ICM_mapper_DICT, UCM_dictionary=UCM_DICT_sparse, UCM_feature_mapper_dictionary=self.UCM_mapper_DICT, user_original_ID_to_index=self.user_original_ID_to_index, item_original_ID_to_index=self.item_original_ID_to_index, is_implicit=is_implicit, ) return loaded_dataset def _generate_global_mappers(self): """ Generates the UserID and ItemID mapper including all data available: URM, ICM, UCM :return: """ self.user_original_ID_to_index = {} self.item_original_ID_to_index = {} for _, URM_dataframe in self.URM_DICT.items(): self.user_original_ID_to_index = _add_keys_to_mapper(self.user_original_ID_to_index, URM_dataframe["UserID"].values) self.item_original_ID_to_index = _add_keys_to_mapper(self.item_original_ID_to_index, URM_dataframe["ItemID"].values) for _, ICM_dataframe in self.ICM_DICT.items(): self.item_original_ID_to_index = _add_keys_to_mapper(self.item_original_ID_to_index, ICM_dataframe["ItemID"].values) for _, UCM_dataframe in self.UCM_DICT.items(): self.user_original_ID_to_index = _add_keys_to_mapper(self.user_original_ID_to_index, UCM_dataframe["UserID"].values) def _generate_ICM_UCM_mappers(self): """ Generates the FeatureID mapper of each ICM and UCM :return: """ for ICM_name, ICM_dataframe in self.ICM_DICT.items(): feature_ID_to_index = _add_keys_to_mapper({}, ICM_dataframe["FeatureID"].values) self.ICM_mapper_DICT[ICM_name] = feature_ID_to_index for UCM_name, UCM_dataframe in self.UCM_DICT.items(): feature_ID_to_index = _add_keys_to_mapper({}, UCM_dataframe["FeatureID"].values) self.UCM_mapper_DICT[UCM_name] = feature_ID_to_index def add_URM(self, URM_dataframe:pd.DataFrame, URM_name): """ Adds the URM_dataframe to the current dataset object :param URM_dataframe: Expected columns: UserID, ItemID, Data :param URM_name: String with the name of the URM :return: """ assert set(["UserID", "ItemID", "Data"]).issubset(set(URM_dataframe.columns)), "Dataframe columns not correct" assert all(is_string_dtype(URM_dataframe[ID_column]) for ID_column in ["UserID", "ItemID"]), "ID columns must be strings" assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" assert URM_name not in self.URM_DICT, "URM_name alredy exists" self.URM_DICT[URM_name] = URM_dataframe def add_ICM(self, ICM_dataframe:pd.DataFrame, ICM_name): """ Adds the ICM_dataframe to the current dataset object :param ICM_dataframe: Expected columns: ItemID, FeatureID, Data :param ICM_name: String with the name of the ICM :return: """ assert set(["ItemID", "FeatureID", "Data"]).issubset(set(ICM_dataframe.columns)), "Dataframe columns not correct" assert all(is_string_dtype(ICM_dataframe[ID_column]) for ID_column in ["ItemID", "FeatureID"]), "ID columns must be strings" assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" assert ICM_name not in self.ICM_DICT, "ICM_name alredy exists" self.ICM_DICT[ICM_name] = ICM_dataframe def add_UCM(self, UCM_dataframe:pd.DataFrame, UCM_name): """ Adds the UCM_dataframe to the current dataset object :param UCM_dataframe: Expected columns: UserID, FeatureID, Data :param UCM_name: String with the name of the UCM :return: """ assert set(["UserID", "FeatureID", "Data"]).issubset(set(UCM_dataframe.columns)), "Dataframe columns not correct" assert all(is_string_dtype(UCM_dataframe[ID_column]) for ID_column in ["UserID", "FeatureID"]), "ID columns must be strings" assert not self.__Dataset_finalized, "Dataset mappers have already been generated, adding new data is forbidden" assert UCM_name not in self.UCM_DICT, "UCM_name alredy exists" self.UCM_DICT[UCM_name] = UCM_dataframe
[ "pandas.api.types.is_string_dtype", "Data_manager.IncrementalSparseMatrix.IncrementalSparseMatrix_FilterIDs", "Data_manager.Dataset.Dataset" ]
[((4767, 5168), 'Data_manager.Dataset.Dataset', 'Dataset', ([], {'dataset_name': 'dataset_name', 'URM_dictionary': 'URM_DICT_sparse', 'ICM_dictionary': 'ICM_DICT_sparse', 'ICM_feature_mapper_dictionary': 'self.ICM_mapper_DICT', 'UCM_dictionary': 'UCM_DICT_sparse', 'UCM_feature_mapper_dictionary': 'self.UCM_mapper_DICT', 'user_original_ID_to_index': 'self.user_original_ID_to_index', 'item_original_ID_to_index': 'self.item_original_ID_to_index', 'is_implicit': 'is_implicit'}), '(dataset_name=dataset_name, URM_dictionary=URM_DICT_sparse,\n ICM_dictionary=ICM_DICT_sparse, ICM_feature_mapper_dictionary=self.\n ICM_mapper_DICT, UCM_dictionary=UCM_DICT_sparse,\n UCM_feature_mapper_dictionary=self.UCM_mapper_DICT,\n user_original_ID_to_index=self.user_original_ID_to_index,\n item_original_ID_to_index=self.item_original_ID_to_index, is_implicit=\n is_implicit)\n', (4774, 5168), False, 'from Data_manager.Dataset import Dataset\n'), ((2485, 2688), 'Data_manager.IncrementalSparseMatrix.IncrementalSparseMatrix_FilterIDs', 'IncrementalSparseMatrix_FilterIDs', ([], {'preinitialized_col_mapper': 'self.item_original_ID_to_index', 'preinitialized_row_mapper': 'self.user_original_ID_to_index', 'on_new_col': 'on_new_ID', 'on_new_row': 'on_new_ID'}), '(preinitialized_col_mapper=self.\n item_original_ID_to_index, preinitialized_row_mapper=self.\n user_original_ID_to_index, on_new_col=on_new_ID, on_new_row=on_new_ID)\n', (2518, 2688), False, 'from Data_manager.IncrementalSparseMatrix import IncrementalSparseMatrix_FilterIDs\n'), ((3296, 3488), 'Data_manager.IncrementalSparseMatrix.IncrementalSparseMatrix_FilterIDs', 'IncrementalSparseMatrix_FilterIDs', ([], {'preinitialized_col_mapper': 'feature_ID_to_index', 'preinitialized_row_mapper': 'self.item_original_ID_to_index', 'on_new_col': 'on_new_ID', 'on_new_row': 'on_new_ID'}), '(preinitialized_col_mapper=\n feature_ID_to_index, preinitialized_row_mapper=self.\n item_original_ID_to_index, on_new_col=on_new_ID, on_new_row=on_new_ID)\n', (3329, 3488), False, 'from Data_manager.IncrementalSparseMatrix import IncrementalSparseMatrix_FilterIDs\n'), ((4099, 4291), 'Data_manager.IncrementalSparseMatrix.IncrementalSparseMatrix_FilterIDs', 'IncrementalSparseMatrix_FilterIDs', ([], {'preinitialized_col_mapper': 'feature_ID_to_index', 'preinitialized_row_mapper': 'self.user_original_ID_to_index', 'on_new_col': 'on_new_ID', 'on_new_row': 'on_new_ID'}), '(preinitialized_col_mapper=\n feature_ID_to_index, preinitialized_row_mapper=self.\n user_original_ID_to_index, on_new_col=on_new_ID, on_new_row=on_new_ID)\n', (4132, 4291), False, 'from Data_manager.IncrementalSparseMatrix import IncrementalSparseMatrix_FilterIDs\n'), ((7445, 7486), 'pandas.api.types.is_string_dtype', 'is_string_dtype', (['URM_dataframe[ID_column]'], {}), '(URM_dataframe[ID_column])\n', (7460, 7486), False, 'from pandas.api.types import is_string_dtype\n'), ((8240, 8281), 'pandas.api.types.is_string_dtype', 'is_string_dtype', (['ICM_dataframe[ID_column]'], {}), '(ICM_dataframe[ID_column])\n', (8255, 8281), False, 'from pandas.api.types import is_string_dtype\n'), ((9039, 9080), 'pandas.api.types.is_string_dtype', 'is_string_dtype', (['UCM_dataframe[ID_column]'], {}), '(UCM_dataframe[ID_column])\n', (9054, 9080), False, 'from pandas.api.types import is_string_dtype\n')]
import os import pytest import yaml from gcasc.utils.yaml_include import YamlIncluderConstructor from .helpers import read_file, read_yaml YamlIncluderConstructor.add_to_loader_class( loader_class=yaml.FullLoader, base_dir=os.path.dirname(os.path.realpath(__file__)) + "/data", ) @pytest.fixture() def file1(): return read_yaml("yaml_include_f1.yml") @pytest.fixture() def file2(): return read_yaml("yaml_include_f2.yml") @pytest.fixture() def file_txt(): return read_file("yaml_include_txt.md") def test_files_included_into_yaml(file1, file2, file_txt): # given file = "yaml_include.yml" # when data = read_yaml(file) # then assert data["inc1"] == file1 assert data["inc2"] == [file2, file_txt]
[ "pytest.fixture", "os.path.realpath" ]
[((295, 311), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (309, 311), False, 'import pytest\n'), ((372, 388), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (386, 388), False, 'import pytest\n'), ((449, 465), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (463, 465), False, 'import pytest\n'), ((251, 277), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (267, 277), False, 'import os\n')]
def memoiziraj(f): rezultati = {} def mem_f(x): if x not in rezultati: rezultati[x] = f(x) return rezultati[x] return mem_f #naredi pametno funkcijo import sys sys.setrecursionlimit(10000000) def vsota(n): if n == 0: return 0 else: return n + vsota(n-1) print(vsota(1000))
[ "sys.setrecursionlimit" ]
[((202, 233), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10000000)'], {}), '(10000000)\n', (223, 233), False, 'import sys\n')]
import cocotb from cocotb.triggers import Timer from utils import pytest_cocotb_run_test def test_onehot_mux(pytestconfig): """Pytest fixture for One-hot Mux test""" pytest_cocotb_run_test(pytestconfig, __name__) @cocotb.test() async def cocotb_test_onehot_mux(dut): """One-hot mux test""" dw = int(dut.DW) n = int(dut.N) # Generate counting pattern on input vectors dut_i = 0 for i in range(n): dut_i |= (i % dw) << (i * dw) dut.i <= dut_i for i in range(n): dut.sel <= 1 << i await Timer(1) assert i % dw == int(dut.o)
[ "cocotb.triggers.Timer", "cocotb.test", "utils.pytest_cocotb_run_test" ]
[((226, 239), 'cocotb.test', 'cocotb.test', ([], {}), '()\n', (237, 239), False, 'import cocotb\n'), ((176, 222), 'utils.pytest_cocotb_run_test', 'pytest_cocotb_run_test', (['pytestconfig', '__name__'], {}), '(pytestconfig, __name__)\n', (198, 222), False, 'from utils import pytest_cocotb_run_test\n'), ((555, 563), 'cocotb.triggers.Timer', 'Timer', (['(1)'], {}), '(1)\n', (560, 563), False, 'from cocotb.triggers import Timer\n')]
""" Defines a number of diverse, system-wide helper functions. Contents: 1. Pickling 2. Graph saving and loading 3. Reporting 4. Corpus processing 5. Math functions """ import os import sys import time import pickle import codecs import random import logging import numpy as np import pandas as pd import tensorflow as tf # =========================================== Pickling =========================================== def make_pickle(opt, data_processor, corpus_name, source_path, data_path, vocab_path=None, is_train=False, is_valid=False, is_test=False): """ Pickles corpus information for fast re-use; tracks the duration of the performed operations for rudimentary estimation of processing efficiency. """ # Vocabulary objects are created for training sets only if not is_train: # Display the appropriate feedback to user if is_valid: print('Processing the validation data ...') elif is_test: print('Processing the test data ...') else: print('Processing full corpus data ...') g_st = time.time() sentences = data_processor(opt, source_path, corpus_name) g_diff = time.time() - g_st print('Data generation took {:d} minutes and {:.4f} seconds!'.format(int(g_diff // 60), g_diff % 60)) p_st = time.time() with open(data_path, 'wb') as in_file: pickle.dump(sentences, in_file) p_diff = time.time() - p_st print('Pickling took {:d} minutes and {:.4f} seconds!'.format(int(p_diff // 60), p_diff % 60)) else: print('Processing training vocab and data ...') g_st = time.time() vocab, sentences = data_processor(opt, source_path, corpus_name, zipf_sort=True, generate_vocab=True) g_diff = time.time() - g_st print('Data generation took {:d} minutes and {:.4f} seconds!'.format(int(g_diff // 60), g_diff % 60)) if vocab_path is not None: pv_st = time.time() with open(vocab_path, 'wb') as in_file: pickle.dump(vocab, in_file) pv_diff = time.time() - pv_st print('Vocab pickling took {:d} minutes and {:.4f} seconds!'.format(int(pv_diff // 60), pv_diff % 60)) pd_st = time.time() with open(data_path, 'wb') as in_file: pickle.dump(sentences, in_file) pd_diff = time.time() - pd_st print('Data pickling took {:d} minutes and {:.4f} seconds!'.format(int(pd_diff // 60), pd_diff % 60)) def load_pickle(pickle_path): """ Un-pickles corpus information (or any pickle, in general). """ with open(pickle_path, 'rb') as out_file: return pickle.load(out_file) # =========================================== Graph saving and loading =========================================== def save_model(session, model, model_saver, save_dir, source_epoch): """ Saves the model to the specified save directory. """ # Epoch designations are limited to 'best', 'final', and time-stamps unique = ['best', 'final'] # Generate the appropriate checkpoint name if source_epoch in unique: file_name = '{:s}_{:s}.ckpt'.format(str(source_epoch), model.name) else: time_tuple = time.localtime(time.time()) time_stamp = '{:d}.{:d}.{:d}_{:d}:{:d}:{:d}' \ .format(time_tuple[2], time_tuple[1], time_tuple[0], time_tuple[3], time_tuple[4], time_tuple[5]) file_name = '{:s}_{:s}_{:s}.ckpt'.format(str(source_epoch), time_stamp, model.name) # Save save_path = model_saver.save(session, os.path.join(save_dir, file_name)) # Report logging.info('{:s} model {:s} has been saved in file {:s}'.format(model.name, file_name, save_path)) def load_model(session, model_saver, save_dir, target_epoch): """ Loads the specified checkpoint from the designated save directory. """ # Retrieve the correct checkpoint file checkpoints = [ ckpt for ckpt in os.listdir(save_dir) if os.path.isfile(os.path.join(save_dir, ckpt)) and 'meta' in ckpt] if target_epoch is None: load_from = [ckpt for ckpt in checkpoints if ckpt.startswith('best')] else: load_from = [ckpt for ckpt in checkpoints if ckpt.startswith(str(target_epoch))] file_name = '.'.join(load_from[0].split('.')[:-1]) file_path = os.path.join(save_dir, file_name) # Load model_saver.restore(session, file_path) # Report logging.info('Model restored from {:s}'.format(file_name)) # =========================================== Reporting =========================================== def print_off(): """ Suppresses print output; see: stackoverflow.com/questions/8391411/suppress-calls-to-print-python""" sys.stdout = open(os.devnull, 'w') def print_on(): """ Re-enables print output; same source as above.""" sys.stdout = sys.__stdout__ # =========================================== Corpus processing =========================================== def clean_europarl(source_path, clean_path, keep_above=2): """ Removes lines of length <= 2 from the corpus so as to make the training more stable. """ line_count = 0 word_count = 0 with codecs.open(source_path, 'r', encoding='utf8') as out_file: with open(clean_path, 'w') as in_file: for line in out_file: line_length = len(line.split()) if line_length > keep_above: in_file.write(line) line_count += 1 word_count += line_length # Report the outcome of the cleaning process print('Corpus cleaned. Cleaned corpus contains {:d} lines, totaling up to {:d} words.'. format(line_count, word_count)) def truncate_europarl(source_path, truncated_path, truncated_length=100000): """ Truncates the Europarl v7 monolingual English (or any) corpus to the specified length. """ with codecs.open(source_path, 'r', encoding='utf8') as out_file: word_count = 0 with open(truncated_path, 'w') as in_file: for i, line in enumerate(out_file): if i < truncated_length: in_file.write(line) word_count += len(line.split()) # Report the scope of the truncated corpus print('Corpus truncated to {:d} lines, totaling up to {:d} words.'.format(truncated_length, word_count)) def train_valid_test_split(source_path, train_path, valid_path, test_path, split_fractions): """ Splits the specified source corpus in training, validation, and testing sub-corpora according to the proportions specified in split_factions. """ with open(source_path, 'r') as out_file: # Read in the full corpus all_lines = out_file.readlines() # Shuffle to increase the diversity of sentences contained in each of the split sets random.shuffle(all_lines) source_len = len(all_lines) # Determine cut-off points for each split train_bound = int(source_len * split_fractions[0]) valid_bound = int(source_len * (split_fractions[0] + split_fractions[1])) # Split source corpus in train/ valid/ test sets with open(train_path, 'w') as train_file: for line in all_lines[: train_bound]: train_file.write(line.strip() + '\n') with open(valid_path, 'w') as valid_file: for line in all_lines[train_bound: valid_bound]: valid_file.write(line.strip() + '\n') with open(test_path, 'w') as test_file: for line in all_lines[valid_bound:]: test_file.write(line.strip() + '\n') print('Train-valid-test-split successfully completed.') def shrink_domain(scored_path, reduced_path, keep_fraction=0.9): """ Prunes 1.0 - keep_faction of the total source corpus size in outliers, as determined by model perplexity scores assigned to each of the corpus sentences by a trained language model. """ # Read in the source corpus df_full = pd.read_table(scored_path, header=None, names=['Sentence', 'Sentence_Perplexity'], skip_blank_lines=True) # Sort dataframe by sentence-wise model perplexity scores, ascending df_full = df_full.sort_values('Sentence_Perplexity', ascending=True) # Prune the lowest 1.0 - keep_fraction of the dataframe df_shrunk = df_full.iloc[0: int(len(df_full) * keep_fraction), 0] # Shuffle the retained dataframe and write the result to file df_shrunk = df_shrunk.iloc[np.random.permutation(len(df_shrunk))] with open(reduced_path, 'w') as in_file: for entry_id in range(len(df_shrunk)): line = df_shrunk.iloc[entry_id].strip() + '\n' in_file.write(line) print('Corpus domain successfully restricted.') def id_split(annotated_path, low_path, high_path): """ Splits the annotated corpus into low-ID and a high-ID sub-corpora, each containing an identical number of samples; the so obtained corpora are used in both stages of IDGAN training. """ # Read in the source corpus df_annotated = pd.read_table(annotated_path, header=None, names=['Sentence', 'Total_surprisal', 'Per_word_surprisal', 'Normalized_surprisal', 'Total_UID_divergence', 'Per_word_UID_divergence', 'Normalized_UID_divergence'], skip_blank_lines=True) # Sort dataframe along sentence-wise normalized surprisal scores df_annotated = df_annotated.loc[:, ['Sentence', 'Normalized_surprisal']] df_annotated = df_annotated.sort_values('Normalized_surprisal', ascending=True) # Split dataframe along the median surprisal value median_row = len(df_annotated) // 2 df_low = df_annotated.iloc[: median_row, :] df_high = df_annotated.iloc[median_row:, :] id_variant_corpora = [(df_low, low_path), (df_high, high_path)] # Shuffle the derived corpora and write the result to file for tpl in id_variant_corpora: # Calculate ID-related corpus statistics corpus_name = tpl[1].split('/')[-1] ns_mean = tpl[0]['Normalized_surprisal'].mean() ns_median = tpl[0]['Normalized_surprisal'].median() ns_min = tpl[0]['Normalized_surprisal'].min() ns_max = tpl[0]['Normalized_surprisal'].max() sent_lens = 0 corpus = tpl[0].iloc[np.random.permutation(len(tpl[0]))] with open(tpl[1], 'w') as in_file: for entry_id in range(len(corpus)): line = corpus.iloc[entry_id][0].strip() in_file.write(line + '\n') sent_lens += len(line.split()) mean_sent_len = sent_lens / len(corpus) # Report ID-relevant statistics print('{:s} corpus: Mean NS: {:.4f} | Median NS: {:.4f} | Min NS: {:.4f} | Max NS: {:.4f} | ' 'Mean sentence length: {:.4f}' .format(corpus_name, ns_mean, ns_median, ns_min, ns_max, mean_sent_len)) print('Corpus successfully subdivided according to the chosen ID criterion.') # =========================================== Math functions =========================================== def padded_log(input_tensor): """ Prevents NaNs during log computations, see github.com/AYLIEN/IDGAN-intro/blob/master/IDGAN.py. """ return tf.log(tf.maximum(input_tensor, 1e-5))
[ "os.listdir", "pickle.dump", "random.shuffle", "pickle.load", "os.path.join", "pandas.read_table", "tensorflow.maximum", "codecs.open", "time.time" ]
[((4339, 4372), 'os.path.join', 'os.path.join', (['save_dir', 'file_name'], {}), '(save_dir, file_name)\n', (4351, 4372), False, 'import os\n'), ((8015, 8124), 'pandas.read_table', 'pd.read_table', (['scored_path'], {'header': 'None', 'names': "['Sentence', 'Sentence_Perplexity']", 'skip_blank_lines': '(True)'}), "(scored_path, header=None, names=['Sentence',\n 'Sentence_Perplexity'], skip_blank_lines=True)\n", (8028, 8124), True, 'import pandas as pd\n'), ((9070, 9312), 'pandas.read_table', 'pd.read_table', (['annotated_path'], {'header': 'None', 'names': "['Sentence', 'Total_surprisal', 'Per_word_surprisal',\n 'Normalized_surprisal', 'Total_UID_divergence',\n 'Per_word_UID_divergence', 'Normalized_UID_divergence']", 'skip_blank_lines': '(True)'}), "(annotated_path, header=None, names=['Sentence',\n 'Total_surprisal', 'Per_word_surprisal', 'Normalized_surprisal',\n 'Total_UID_divergence', 'Per_word_UID_divergence',\n 'Normalized_UID_divergence'], skip_blank_lines=True)\n", (9083, 9312), True, 'import pandas as pd\n'), ((1107, 1118), 'time.time', 'time.time', ([], {}), '()\n', (1116, 1118), False, 'import time\n'), ((1347, 1358), 'time.time', 'time.time', ([], {}), '()\n', (1356, 1358), False, 'import time\n'), ((1671, 1682), 'time.time', 'time.time', ([], {}), '()\n', (1680, 1682), False, 'import time\n'), ((2277, 2288), 'time.time', 'time.time', ([], {}), '()\n', (2286, 2288), False, 'import time\n'), ((2692, 2713), 'pickle.load', 'pickle.load', (['out_file'], {}), '(out_file)\n', (2703, 2713), False, 'import pickle\n'), ((3589, 3622), 'os.path.join', 'os.path.join', (['save_dir', 'file_name'], {}), '(save_dir, file_name)\n', (3601, 3622), False, 'import os\n'), ((5194, 5240), 'codecs.open', 'codecs.open', (['source_path', '"""r"""'], {'encoding': '"""utf8"""'}), "(source_path, 'r', encoding='utf8')\n", (5205, 5240), False, 'import codecs\n'), ((5920, 5966), 'codecs.open', 'codecs.open', (['source_path', '"""r"""'], {'encoding': '"""utf8"""'}), "(source_path, 'r', encoding='utf8')\n", (5931, 5966), False, 'import codecs\n'), ((6865, 6890), 'random.shuffle', 'random.shuffle', (['all_lines'], {}), '(all_lines)\n', (6879, 6890), False, 'import random\n'), ((11303, 11334), 'tensorflow.maximum', 'tf.maximum', (['input_tensor', '(1e-05)'], {}), '(input_tensor, 1e-05)\n', (11313, 11334), True, 'import tensorflow as tf\n'), ((1202, 1213), 'time.time', 'time.time', ([], {}), '()\n', (1211, 1213), False, 'import time\n'), ((1418, 1449), 'pickle.dump', 'pickle.dump', (['sentences', 'in_file'], {}), '(sentences, in_file)\n', (1429, 1449), False, 'import pickle\n'), ((1467, 1478), 'time.time', 'time.time', ([], {}), '()\n', (1476, 1478), False, 'import time\n'), ((1810, 1821), 'time.time', 'time.time', ([], {}), '()\n', (1819, 1821), False, 'import time\n'), ((1995, 2006), 'time.time', 'time.time', ([], {}), '()\n', (2004, 2006), False, 'import time\n'), ((2348, 2379), 'pickle.dump', 'pickle.dump', (['sentences', 'in_file'], {}), '(sentences, in_file)\n', (2359, 2379), False, 'import pickle\n'), ((2398, 2409), 'time.time', 'time.time', ([], {}), '()\n', (2407, 2409), False, 'import time\n'), ((3266, 3277), 'time.time', 'time.time', ([], {}), '()\n', (3275, 3277), False, 'import time\n'), ((3973, 3993), 'os.listdir', 'os.listdir', (['save_dir'], {}), '(save_dir)\n', (3983, 3993), False, 'import os\n'), ((2075, 2102), 'pickle.dump', 'pickle.dump', (['vocab', 'in_file'], {}), '(vocab, in_file)\n', (2086, 2102), False, 'import pickle\n'), ((2125, 2136), 'time.time', 'time.time', ([], {}), '()\n', (2134, 2136), False, 'import time\n'), ((4012, 4040), 'os.path.join', 'os.path.join', (['save_dir', 'ckpt'], {}), '(save_dir, ckpt)\n', (4024, 4040), False, 'import os\n')]
# Exhibiter, copyright (c) 2021 <NAME>. # This software may not be used to evict people, see LICENSE.md. # python standard imports from re import search, sub, fullmatch from pathlib import Path from copy import copy # third-party imports from pdfrw import PdfReader, PdfWriter, buildxobj, toreportlab from reportlab.lib import pagesizes, colors from reportlab.pdfgen.canvas import Canvas from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.style import WD_STYLE_TYPE from docx import Document from PIL import Image # global variables FILE_TYPES = ["png", "PNG", "jpg", "JPG", "jpeg", "JPEG", "pdf", "PDF"] EXCLUDE_PATTERN = r"\((UNUSED|[Uu]nused)\)" DISPUTE_FILE = "evidentiary disputes.txt" class Exhibit: """ The the heart of Exhibiter. This object contains a ReportLab canvas and a list of documents, corresponding to the contents of one exhibit. """ @classmethod def from_path( cls, exhibit_path: Path, respect_exclusions: bool = True, number_pages: bool = True, page_label_coords: tuple = (50, 3), rotate_landscape_pics: bool = True, strip_leading_digits: bool = True, ): """ This constructor makes an exhibit from a given folder or file. The folder name should be formatted like this: "101" or "101. Residential Lease". This will set the exhibit's index and, optionally, its title. The exhibit folder should contain one or more documents. A document means a file in the FILE_TYPES list, or a folder full of such files. Documents whose names contain "(UNUSED)" will normally be omitted.""" # throw error if filename is wrong if not fullmatch("^(\d+|[A-Y])(\.?( .+)?)?", exhibit_path.stem): raise SyntaxError( f"'{exhibit_path.stem}' isnt a valid name for an exhibit. It" + " must be a number or capital letter from A-Y, optionally" + " followed by a title to display in the exhibit list. Valid" + " examples include names like these:" + '\n"101"' + '\n"102. Party Communications"' + '\n"A"' ) # for single-document exhibits, throw errors if they're the # wrong type, or if they don't have titles. if not exhibit_path.is_dir(): if exhibit_path.suffix[1:] not in FILE_TYPES: raise SyntaxError( f"{exhibit_path.name} is not a supported file type." + " Exhibits can be PDFs, JPGs, PNGs, or folders" + " full of those things." ) elif not fullmatch("^(\d+|[A-Y])\. .+", exhibit_path.stem): raise SyntaxError( f'"{exhibit_path.name}" is not a valid name for an' + ' exhibit that is only one file. It must have a' + ' title, like "101. Rental Agreement.pdf".' ) # get index and title (if any) from filename. folder_name = _process_filename(exhibit_path.name, False) sections = folder_name.split(". ", 1) index = sections[0] # add a title only if the exhibit path is a directory. For one-file # exhibits, the document name makes a title unnecessary if len(sections) > 1 and exhibit_path.is_dir(): title = sections[1] else: title = None # read evidentiary disputes file if there is one dispute_file = exhibit_path / DISPUTE_FILE if dispute_file.exists(): evidentiary_disputes = dispute_file.read_text() else: evidentiary_disputes = None # generate exhibit exhibit = cls( index, title, number_pages = number_pages, page_label_coords = page_label_coords, rotate_landscape_pics = rotate_landscape_pics, evidentiary_disputes = evidentiary_disputes, ) # add all evidence from the path to it if exhibit_path.is_dir(): for path in evidence_in_dir(exhibit_path, respect_exclusions): exhibit.add_doc(path, strip_leading_digits=strip_leading_digits) else: exhibit.add_doc( exhibit_path, title=sub("^(\d+|[A-Z])\. ", "", exhibit_path.stem) ) return exhibit def __init__( self, index: str, title: str = None, number_pages: bool = True, page_label_coords: tuple = (50, 3), rotate_landscape_pics: bool = True, evidentiary_disputes: str = None, ): """ This creates a bare-bones exhibit with only a cover sheet. You can then populate it by running add_doc() one or more times. """ # make a canvas write a cover page like "EXHIBIT 101" canvas = Canvas("never_save_to_this_path.pdf") canvas.setPageSize(pagesizes.letter) canvas.setFont("Helvetica", 32) x, y = canvas._pagesize[0] / 2, canvas._pagesize[1] / 7 canvas.drawCentredString(x, y, f"EXHIBIT {index}") canvas.showPage() # set this exhibit's various variables self.canvas: Canvas = canvas self.documents: list = [] self.index: str = index self.title: str = title self.evidentiary_disputes: str = evidentiary_disputes self.number_pages: bool = number_pages self.rotate_landscape_pics: bool = rotate_landscape_pics self.page_label_coords: tuple = page_label_coords self.page_count: int = 0 def add_doc( self, doc_path: Path, respect_exclusions: bool = True, strip_leading_digits: bool = True, title: str = None, ): """ Adds a document (i.e. an image, PDF, or a folder of either) to this exhibit. """ startpage = self.page_count + 1 if not title: title = _process_filename(doc_path.name, strip_leading_digits) if doc_path.is_dir(): # walk through directory and add files to doc file_paths = [] for extension in FILE_TYPES: file_paths += doc_path.glob("**/*." + extension) # add each file in order, except the ones marked for omission for path in sorted(file_paths): if respect_exclusions and search(EXCLUDE_PATTERN, path.name): continue self._insert_pdf_or_image(path) else: # add single-file document to exhibit self._insert_pdf_or_image(doc_path) self.documents.append( {"name": title, "page_span": (startpage, self.page_count), "path": doc_path} ) def _insert_pdf_or_image(self, path: Path): """ Checks whether the given file is a PDF or an image, and performs the appropriate actions to add it to the main PDF. """ if path.suffix in [".pdf", ".PDF"]: pages = PdfReader(path).pages pages = [buildxobj.pagexobj(page) for page in pages] for page in pages: self.canvas.setPageSize((page.BBox[2], page.BBox[3])) self.canvas.doForm(toreportlab.makerl(self.canvas, page)) self._finish_page() elif path.suffix[1:] in FILE_TYPES: # treat path as an image self.canvas.setPageSize(pagesizes.letter) page_w, page_h = self.canvas._pagesize # Rotate landscape images to fit portrait page img = Image.open(path) img_ratio = img.size[0] / img.size[1] if img_ratio > 1 and self.rotate_landscape_pics: self.canvas.saveState() self.canvas.rotate(-90) w, h = 0.9 * page_h, 0.9 * page_w rotated = True x = (-w - page_h) / 2 y = (page_w - h) / 2 # x = (page_h - w) / 2 # y = (-page_w - h) / 2 else: w, h = 0.9 * page_w, 0.9 * page_h x = (page_w - w) / 2 y = (page_h - h) / 2 rotated = False self.canvas.drawImage(path, x, y, w, h, preserveAspectRatio=True) if rotated: self.canvas.restoreState() self._finish_page() else: raise SyntaxError(f"{path} is not a supported type: {FILE_TYPES}") def _finish_page(self): """Print a page number (maybe), then move on to the next page.""" self.page_count += 1 if self.number_pages: string = f"{self.index}-{self.page_count}" mid = [ self.canvas._pagesize[x] * self.page_label_coords[x] / 100 for x in [0, 1] ] self.canvas.setFillColor(colors.white) self.canvas.rect(mid[0] - 25, mid[1] - 4, 50, 15, stroke=0, fill=1) self.canvas.setFillColor(colors.black) self.canvas.drawCentredString(mid[0], mid[1], string) self.canvas.showPage() def __str__(self): return self.path.stem # ###################################################################### # Module-Level Functions # ###################################################################### def write_pdf(exhibits: list[Exhibit], output_path: str): """Save the given list of exhibits to a PDF document.""" writer = PdfWriter() for exhibit in exhibits: reader = PdfReader(fdata=exhibit.canvas.getpdfdata()) writer.addpages(reader.pages) writer.write(output_path) def write_list( exhibits: list[Exhibit], output_path: str, attachment_no: int = 4, party_label: str = "Defense", show_page_numbers: bool = True, reserve_rebuttal: bool = True, row_per_doc: bool = True, ): """Save a Word document listing the given exhibits in detail.""" template = str(Path(__file__).parent.absolute() / "template.docx") exhibit_list = Document(template) # fill in title line exhibit_list.paragraphs[0].add_run( f"Attachment {attachment_no}: Exhibit List" ).bold = True # write table header exhibit_list.tables[0].rows[0].cells[0].paragraphs[0].add_run( f"{party_label.upper()} EXHIBITS" ).bold = True # treat each doc as its own exhibit if row_per_doc: new_exhibits = [] for exhibit in exhibits: for document in exhibit.documents: start = document['page_span'][0] end = document['page_span'][1] index = exhibit.index if len(exhibit.documents) == 1: pass elif end > start: index = f'{index}-{start}\nto\n{index}-{end}' else: index = f'{index}-{start}' new_exhibit = Exhibit( index = index, title = document['name'], ) new_exhibit.documents = [document] new_exhibits.append(new_exhibit) exhibits = new_exhibits for exhibit in exhibits: # add a table row, to represent the exhibit row = exhibit_list.tables[0].add_row() row.cells[0].text = exhibit.index # center-align the first two cells for c in [0, 1]: # center-align columns 0 and 1 row.cells[c].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER # write the exhibit title unless it would be redundant if ( exhibit.title and not ( len(exhibit.documents) == 1 and exhibit.documents[0]['name'] == exhibit.title ) ): if len(exhibit.documents) > 0: title_str = exhibit.title + ':' else: title_str = exhibit.title row.cells[3].paragraphs[0].text = title_str show_title = True else: show_title = False # add a line for each document in the exhibit for i, doc in enumerate(exhibit.documents): # use an existing blank paragraph then make one for each doc if i == 0 and not show_title: paragraph = row.cells[3].paragraphs[0] else: paragraph = row.cells[3].add_paragraph() description = doc["name"] if len(exhibit.documents) > 1 and show_page_numbers: span = doc['page_span'] if span[1] - span[0] > 0: description += f' (pp.{span[0]}-{span[1]})' else: description += f' (p.{span[0]})' paragraph.text = description row.cells[4].text = exhibit.evidentiary_disputes or "" if reserve_rebuttal: # calculate the next exhibit number or letter last_index = exhibits[-1].index if '-' in last_index: last_index = last_index.split('-')[0] if search("[A-Y]", last_index): next_index = chr(ord(last_index) + 1) else: next_index = str(int(last_index) + 1) # reserve that exhibit for rebuttal row = exhibit_list.tables[0].add_row() row.cells[0].text = next_index row.cells[3].text = "Reserved for Rebuttal" for c in [0, 1]: row.cells[c].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER exhibit_list.save(output_path) def evidence_in_dir(folder: Path, respect_exclusions: bool = True): returns = [] for path in sorted(folder.iterdir()): # skip unsupported files if not path.is_dir() and path.suffix[1:] not in FILE_TYPES: continue # skip files containing the exclude pattern (by default) if respect_exclusions and search(EXCLUDE_PATTERN, path.name): continue returns.append(path) return returns # if returns: # return returns # else: # raise FileNotFoundError(f"{folder} doesn't seem to contain any evidence.") def _process_filename(name: str, strip_leading_digits: bool = True) -> str: """ Convert a filename into a document description. Strips EXCLUDE_PATTERN, if present, and moves leading dates (YYYY-MM-DD or YYYYMMDD) to the end, in M/D/YY format. Also, converts things like "01. First Document" to "First Document" by default. """ # remove file extension filetypes_regex = '(\.' + '|\.'.join(FILE_TYPES) + ')$' name = sub(filetypes_regex, '', name) # remove the exclude pattern name = sub(" ?(" + EXCLUDE_PATTERN + ")", "", name) # if name begins with YYYY-MM-DD or YYYYMMDD, put M/D/YYYY at end date_match = search( "^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}) ", name ) if not date_match: date_match = search( "^(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2}) ", name ) if date_match: name = name.replace(date_match.group(0), '') g = date_match.groupdict() month, day = g['month'].lstrip('0'), g['day'].lstrip('0') year = g['year'] name += f' {month}/{day}/{year}' # if name starts with a number, period, and space, remove it elif strip_leading_digits: name = sub("^\d+\. ", "", name) return name
[ "pdfrw.PdfWriter", "pdfrw.toreportlab.makerl", "PIL.Image.open", "pathlib.Path", "pdfrw.buildxobj.pagexobj", "pdfrw.PdfReader", "re.fullmatch", "reportlab.pdfgen.canvas.Canvas", "re.sub", "docx.Document", "re.search" ]
[((9589, 9600), 'pdfrw.PdfWriter', 'PdfWriter', ([], {}), '()\n', (9598, 9600), False, 'from pdfrw import PdfReader, PdfWriter, buildxobj, toreportlab\n'), ((10154, 10172), 'docx.Document', 'Document', (['template'], {}), '(template)\n', (10162, 10172), False, 'from docx import Document\n'), ((14798, 14828), 're.sub', 'sub', (['filetypes_regex', '""""""', 'name'], {}), "(filetypes_regex, '', name)\n", (14801, 14828), False, 'from re import search, sub, fullmatch\n'), ((14878, 14922), 're.sub', 'sub', (["(' ?(' + EXCLUDE_PATTERN + ')')", '""""""', 'name'], {}), "(' ?(' + EXCLUDE_PATTERN + ')', '', name)\n", (14881, 14922), False, 'from re import search, sub, fullmatch\n'), ((15015, 15083), 're.search', 'search', (['"""^(?P<year>\\\\d{4})-(?P<month>\\\\d{2})-(?P<day>\\\\d{2}) """', 'name'], {}), "('^(?P<year>\\\\d{4})-(?P<month>\\\\d{2})-(?P<day>\\\\d{2}) ', name)\n", (15021, 15083), False, 'from re import search, sub, fullmatch\n'), ((4998, 5035), 'reportlab.pdfgen.canvas.Canvas', 'Canvas', (['"""never_save_to_this_path.pdf"""'], {}), "('never_save_to_this_path.pdf')\n", (5004, 5035), False, 'from reportlab.pdfgen.canvas import Canvas\n'), ((13279, 13306), 're.search', 'search', (['"""[A-Y]"""', 'last_index'], {}), "('[A-Y]', last_index)\n", (13285, 13306), False, 'from re import search, sub, fullmatch\n'), ((15147, 15213), 're.search', 'search', (['"""^(?P<year>\\\\d{4})(?P<month>\\\\d{2})(?P<day>\\\\d{2}) """', 'name'], {}), "('^(?P<year>\\\\d{4})(?P<month>\\\\d{2})(?P<day>\\\\d{2}) ', name)\n", (15153, 15213), False, 'from re import search, sub, fullmatch\n'), ((1731, 1789), 're.fullmatch', 'fullmatch', (['"""^(\\\\d+|[A-Y])(\\\\.?( .+)?)?"""', 'exhibit_path.stem'], {}), "('^(\\\\d+|[A-Y])(\\\\.?( .+)?)?', exhibit_path.stem)\n", (1740, 1789), False, 'from re import search, sub, fullmatch\n'), ((14101, 14135), 're.search', 'search', (['EXCLUDE_PATTERN', 'path.name'], {}), '(EXCLUDE_PATTERN, path.name)\n', (14107, 14135), False, 'from re import search, sub, fullmatch\n'), ((15604, 15630), 're.sub', 'sub', (['"""^\\\\d+\\\\. """', '""""""', 'name'], {}), "('^\\\\d+\\\\. ', '', name)\n", (15607, 15630), False, 'from re import search, sub, fullmatch\n'), ((7152, 7167), 'pdfrw.PdfReader', 'PdfReader', (['path'], {}), '(path)\n', (7161, 7167), False, 'from pdfrw import PdfReader, PdfWriter, buildxobj, toreportlab\n'), ((7195, 7219), 'pdfrw.buildxobj.pagexobj', 'buildxobj.pagexobj', (['page'], {}), '(page)\n', (7213, 7219), False, 'from pdfrw import PdfReader, PdfWriter, buildxobj, toreportlab\n'), ((7703, 7719), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (7713, 7719), False, 'from PIL import Image\n'), ((2709, 2760), 're.fullmatch', 'fullmatch', (['"""^(\\\\d+|[A-Y])\\\\. .+"""', 'exhibit_path.stem'], {}), "('^(\\\\d+|[A-Y])\\\\. .+', exhibit_path.stem)\n", (2718, 2760), False, 'from re import search, sub, fullmatch\n'), ((4410, 4457), 're.sub', 'sub', (['"""^(\\\\d+|[A-Z])\\\\. """', '""""""', 'exhibit_path.stem'], {}), "('^(\\\\d+|[A-Z])\\\\. ', '', exhibit_path.stem)\n", (4413, 4457), False, 'from re import search, sub, fullmatch\n'), ((6529, 6563), 're.search', 'search', (['EXCLUDE_PATTERN', 'path.name'], {}), '(EXCLUDE_PATTERN, path.name)\n', (6535, 6563), False, 'from re import search, sub, fullmatch\n'), ((7375, 7412), 'pdfrw.toreportlab.makerl', 'toreportlab.makerl', (['self.canvas', 'page'], {}), '(self.canvas, page)\n', (7393, 7412), False, 'from pdfrw import PdfReader, PdfWriter, buildxobj, toreportlab\n'), ((10083, 10097), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (10087, 10097), False, 'from pathlib import Path\n')]
from typing import List from fastapi import APIRouter, Depends from sqlmodel import select, Session from app.models import * from utils import get_session router = APIRouter() @router.get("/users", response_model=List[UserRead]) async def get_users(*, session: Session=Depends(get_session)): statement = select(User) results = session.exec(statement).all() return results @router.post("/tasks", response_model=List[TaskRead]) async def get_tasks(user: UserQuery, session: Session=Depends(get_session)): statement = select(Task).where(Task.owner_id == user.id) results = session.exec(statement).all() return results @router.post("/task", response_model=TaskRead) async def get_task(task: TaskQuery, session: Session=Depends(get_session)): statement = select(Task).where(Task.owner_id == task.owner_id and Task.id == task.id) result = session.exec(statement).one_or_none() return result @router.post("/create/task", response_model=StandardResponse) async def create_task(task: TaskCreate, session: Session=Depends(get_session)): db_task = Task.from_orm(task) session.add(db_task) session.commit() session.refresh(db_task) return StandardResponse() @router.post("/create/user", response_model=StandardResponse) async def create_user(user: UserCreate, session: Session=Depends(get_session)): db_user = User.from_orm(user) session.add(db_user) session.commit() session.refresh(db_user) return StandardResponse() @router.post("/delete/task", response_model=StandardResponse) async def delete_task(task: TaskQuery, session: Session=Depends(get_session)): statement = select(Task).where(Task.id == task.id and Task.owner_id == task.owner_id) result = session.exec(statement) task = result.one_or_none() if task: session.delete(task) session.commit() return StandardResponse() return StandardResponse(success="Failure", message="Invalid Task id or Owner id", code=400) @router.post("/delete/user", response_model=StandardResponse) async def delete_user(user: UserQuery, session: Session=Depends(get_session)): statement = select(User).where(User.id == user.id) result = session.exec(statement) user = result.one_or_none() if user: session.delete(user) session.commit() return StandardResponse() return StandardResponse(success="Failure", message="Invalid User id", code=400) @router.post("/update/task", response_model=StandardResponse) async def update_task(task: TaskRead, session: Session=Depends(get_session)): task = Task.from_orm(task) session.add(task) session.commit() session.refresh(task) return StandardResponse()
[ "fastapi.APIRouter", "fastapi.Depends", "sqlmodel.select" ]
[((165, 176), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (174, 176), False, 'from fastapi import APIRouter, Depends\n'), ((271, 291), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (278, 291), False, 'from fastapi import APIRouter, Depends\n'), ((310, 322), 'sqlmodel.select', 'select', (['User'], {}), '(User)\n', (316, 322), False, 'from sqlmodel import select, Session\n'), ((504, 524), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (511, 524), False, 'from fastapi import APIRouter, Depends\n'), ((753, 773), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (760, 773), False, 'from fastapi import APIRouter, Depends\n'), ((1056, 1076), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (1063, 1076), False, 'from fastapi import APIRouter, Depends\n'), ((1339, 1359), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (1346, 1359), False, 'from fastapi import APIRouter, Depends\n'), ((1621, 1641), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (1628, 1641), False, 'from fastapi import APIRouter, Depends\n'), ((2119, 2139), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (2126, 2139), False, 'from fastapi import APIRouter, Depends\n'), ((2569, 2589), 'fastapi.Depends', 'Depends', (['get_session'], {}), '(get_session)\n', (2576, 2589), False, 'from fastapi import APIRouter, Depends\n'), ((543, 555), 'sqlmodel.select', 'select', (['Task'], {}), '(Task)\n', (549, 555), False, 'from sqlmodel import select, Session\n'), ((792, 804), 'sqlmodel.select', 'select', (['Task'], {}), '(Task)\n', (798, 804), False, 'from sqlmodel import select, Session\n'), ((1660, 1672), 'sqlmodel.select', 'select', (['Task'], {}), '(Task)\n', (1666, 1672), False, 'from sqlmodel import select, Session\n'), ((2158, 2170), 'sqlmodel.select', 'select', (['User'], {}), '(User)\n', (2164, 2170), False, 'from sqlmodel import select, Session\n')]
# Copyright (c) 2009, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of the FreeBSD Project. import os import time import errno import random import sys import tensorflow as tf import datetime class GsFileLockException(Exception): pass def file_age( path ): file_stats = tf.gfile.Stat( path ) time_ns = file_stats.mtime_nsec time_s = int( time_ns/1000000000 ) datetime_inst = datetime.datetime.fromtimestamp( time_s ) return datetime.datetime.now()-datetime_inst class GsFileLock(object): """ A file locking mechanism that has context-manager support so you can use it in a with statement. This should be relatively cross compatible as it doesn't rely on msvcrt or fcntl for the locking. Compatible with Google Buckets. Includes a delay each time a lock is acquired to allow for consistency to propigate. """ __slots__ = ('is_locked', 'consistency_time', 'lockfile', 'file_name', 'timeout', 'delay', 'id', 'lock_expire_hr' ) def __init__(self, file_name, consistency_time, timeout=10, delay=.05, id=None, lock_expire_hr=None): """ Prepare the file locker. Specify the file to lock and optionally the maximum timeout and the delay between each attempt to lock. """ self.is_locked = False self.consistency_time = consistency_time if file_name.startswith( "gs:/" ): self.lockfile = "%s.lock" % file_name else: self.lockfile = os.path.join(os.getcwd(), "%s.lock" % file_name) self.file_name = file_name self.timeout = timeout self.delay = delay if id: self.id = id else: self.id = random.uniform(0,sys.maxsize) self.lock_expire_hr = lock_expire_hr def acquire(self): """ Acquire the lock, if possible. If the lock is in use, it check again every `wait` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception. """ start_time = time.time() pid = os.getpid() checkString = "<" + str(pid) + "." + str( self.id ) + ">" while not self.is_locked: if not tf.gfile.Exists( self.lockfile ) or \ (self.lock_expire_hr is not None and \ file_age(self.lockfile) > datetime.timedelta(hours=self.lock_expire_hr) ): print( "writing to lock file at " + str( self.lockfile) ) #write our number to it. with tf.gfile.Open( self.lockfile, "w" ) as writer: writer.write( checkString ) print( "Maybe..." + checkString ) #give time for someone else to accidentally overwrite our file. time.sleep( self.consistency_time ) #now read the file again and see if it has our number. with tf.gfile.Open( self.lockfile, "r" ) as reader: readString = reader.readline() #if it does then say we won. if readString.startswith( checkString ): self.is_locked = True #else: # print( "file currently exists" + self.lockfile ) if not self.is_locked: if self.timeout is None or (time.time() - start_time) >= self.timeout: raise GsFileLockException("Timeout occurred.") time.sleep(self.delay) def release(self): """ Get rid of the lock by deleting the lockfile. When working in a `with` statement, this gets automatically called at the end. """ if self.is_locked: tf.gfile.Remove( self.lockfile ) self.is_locked = False def __enter__(self): """ Activated when used in the with statement. Should automatically acquire a lock to be used in the with block. """ if not self.is_locked: self.acquire() return self def __exit__(self, type, value, traceback): """ Activated at the end of the with statement. It automatically releases the lock if it isn't locked. """ if self.is_locked: self.release()
[ "tensorflow.gfile.Open", "random.uniform", "datetime.datetime.fromtimestamp", "tensorflow.gfile.Exists", "tensorflow.gfile.Stat", "tensorflow.gfile.Remove", "time.sleep", "os.getcwd", "datetime.datetime.now", "os.getpid", "datetime.timedelta", "time.time" ]
[((1741, 1760), 'tensorflow.gfile.Stat', 'tf.gfile.Stat', (['path'], {}), '(path)\n', (1754, 1760), True, 'import tensorflow as tf\n'), ((1852, 1891), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['time_s'], {}), '(time_s)\n', (1883, 1891), False, 'import datetime\n'), ((1903, 1926), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1924, 1926), False, 'import datetime\n'), ((3548, 3559), 'time.time', 'time.time', ([], {}), '()\n', (3557, 3559), False, 'import time\n'), ((3574, 3585), 'os.getpid', 'os.getpid', ([], {}), '()\n', (3583, 3585), False, 'import os\n'), ((3155, 3185), 'random.uniform', 'random.uniform', (['(0)', 'sys.maxsize'], {}), '(0, sys.maxsize)\n', (3169, 3185), False, 'import random\n'), ((5234, 5264), 'tensorflow.gfile.Remove', 'tf.gfile.Remove', (['self.lockfile'], {}), '(self.lockfile)\n', (5249, 5264), True, 'import tensorflow as tf\n'), ((2950, 2961), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2959, 2961), False, 'import os\n'), ((4290, 4323), 'time.sleep', 'time.sleep', (['self.consistency_time'], {}), '(self.consistency_time)\n', (4300, 4323), False, 'import time\n'), ((4965, 4987), 'time.sleep', 'time.sleep', (['self.delay'], {}), '(self.delay)\n', (4975, 4987), False, 'import time\n'), ((3719, 3749), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['self.lockfile'], {}), '(self.lockfile)\n', (3734, 3749), True, 'import tensorflow as tf\n'), ((4047, 4080), 'tensorflow.gfile.Open', 'tf.gfile.Open', (['self.lockfile', '"""w"""'], {}), "(self.lockfile, 'w')\n", (4060, 4080), True, 'import tensorflow as tf\n'), ((4419, 4452), 'tensorflow.gfile.Open', 'tf.gfile.Open', (['self.lockfile', '"""r"""'], {}), "(self.lockfile, 'r')\n", (4432, 4452), True, 'import tensorflow as tf\n'), ((3862, 3907), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': 'self.lock_expire_hr'}), '(hours=self.lock_expire_hr)\n', (3880, 3907), False, 'import datetime\n'), ((4839, 4850), 'time.time', 'time.time', ([], {}), '()\n', (4848, 4850), False, 'import time\n')]