text stringlengths 38 1.54M |
|---|
import os
import json
import re
def parse_instrument(idx):
with open(os.path.join("E:\\WSM2020_proj", 'data/hshfy_wenshu', str(idx)+".json"), 'r', encoding='utf-8') as f:
dic = json.load(f)
return dic
class Case():
def __init__(self, info):
self.max_snippet_len = 200
self.type = str(info["type"])
self.sort_info = {'date': 0, 'money': 0} # attributes to be sorted
self.snippet = ""
self.idx = info['idx']
if info["type"] == '1': # parse data1
self.candidate_keys = ["iname", "age", "sexy", "duty", "performance", "publishDate"]
self.candidate_keys_lbl = ["姓名", "年龄", "性别", "判决", "履行情况", "判决日期"]
self.num_snippet_keys = 6
self.title = info["caseCode"]
self.sub_title = info["courtName"]
for i in range(self.num_snippet_keys):
if info[self.candidate_keys[i]] != "":
if i < 2: # basic info
self.snippet += self.candidate_keys_lbl[i] + ": " + str(info[self.candidate_keys[i]]) + "   "
else: # advanced info
self.snippet += self.candidate_keys_lbl[i] + ": " + str(info[self.candidate_keys[i]]) + "<br>"
self.sort_info['date'] = info['publishDate'].replace('年', '').replace('月', '').replace('日', '')
elif info["type"] == '2': # parse data2
self.candidate_keys = ["被执行人", "执行标的金额(元)", "申请执行人"]
self.candidate_keys_lbl = ["被执行人", "执行标的金额(元)", "申请执行人"]
self.num_snippet_keys = 3
self.title = info["案号"]
self.sub_title = info["承办法院、联系电话"]
for i in range(self.num_snippet_keys):
if info[self.candidate_keys[i]] != "":
self.snippet += self.candidate_keys_lbl[i] + ": " + str(info[self.candidate_keys[i]]) + "<br>"
self.sort_info['money'] = info['执行标的金额(元)']
self.snippet = self.snippet[: self.max_snippet_len]
def __str__(self):
return str(self.data1) + self.data2 + self.data3
class Instrument():
def __init__(self, meta):
idx, list_query = meta
idx = str(idx).split('.')[0]
info = parse_instrument(idx)
self.type = '3'
self.idx = idx
self.max_snippet_len = 300
self.max_title_len = 30
self.title = info['标题']
if len(self.title) > self.max_title_len:
self.title = self.title[:self.max_title_len] + '...'
self.sub_title = info['结案日期']
self.snippet = info['content']
# get the snippet according to the matching list
if len(list_query) > 0:
for q in list_query:
self.snippet = self.snippet.replace(q, '<span class=keyWord>%s</span>' % q)
self.snippet = self.snippet.replace('</span><span class=keyWord>', '')
highlights = re.findall("<span class=keyWord>(.*?)</span>", self.snippet)
highlights = sorted(list(set(highlights)), key=lambda i:len(i), reverse=True)
start_pos = self.snippet.index('<span class=keyWord>%s' % highlights[0])
self.snippet = self.snippet[start_pos: min(len(self.snippet), start_pos + self.max_snippet_len)]
self.snippet = '...' + self.snippet
else:
self.snippet = info['content'].replace('\n','')[:min(len(self.snippet), self.max_snippet_len)]
# "date" is used for sorting
self.date = float(''.join(info['结案日期'].split('-')))
def __str__(self):
return str(self.data1) + self.data2 + self.data3
if __name__ == '__main__':
instrument = Instrument((837, ['合同', '约定', '总', '房价款', '房屋', '建筑', '面积', '暂测', '实测', '一致', '原因', '外']))
print(instrument.snippet) |
"""Module wide settings.
"""
import logging
import yaml
import os
from ..database import get_db
log = logging.getLogger(__name__)
settings = {}
def get_settings():
"""Get the settings currently being used by QUEST.
Returns:
A dictionary of the current settings.
Example:
{'BASE_DIR': '/Users/dharhas/',
'CACHE_DIR': 'cache',
'PROJECTS_DIR': 'projects',
'USER_SERVICES': [],
}
"""
global settings
if not settings:
update_settings()
filename = _default_config_file()
if os.path.isfile(filename):
update_settings_from_file(filename)
return settings
def update_settings(config={}):
"""Update the settings file that is being stored in the Quest
settings directory.
Notes:
Only key/value pairs that are provided are updated,
any other existing pairs are left unchanged or defaults
are used.
Args:
config (dict): Key/value pairs of settings that are to be updated.
Returns:
Updated Settings
Example:
{'BASE_DIR': '/Users/dharhas/',
'CACHE_DIR': 'cache',
'PROJECTS_DIR': 'projects',
'USER_SERVICES': [],
}
"""
global settings
if 'BASE_DIR' in config.keys() and not os.path.isabs(config['BASE_DIR']):
config['BASE_DIR'] = os.path.join(os.getcwd(), config['BASE_DIR'])
settings.update(config)
settings.setdefault('BASE_DIR', _default_quest_dir())
settings.setdefault('CACHE_DIR', os.path.join('.cache', 'user_cache'))
settings.setdefault('PROJECTS_DIR', 'projects')
settings.setdefault('USER_SERVICES', [])
# reset connection to database in new PROJECT_DIR
if 'BASE_DIR' in config.keys() or 'PROJECTS_DIR' in config.keys():
get_db(reconnect=True)
# reload providers
if 'USER_SERVICES' in config.keys():
from ..plugins.plugins import load_providers
load_providers(update_cache=True)
return settings
def update_settings_from_file(filename):
"""Update the settings from a new yaml file.
Notes:
Only key/value pairs that are provided are updated,
any other existing pairs are left unchanged or defaults
are used.
Args:
filename (string): Path to the yaml file containing the new settings.
Returns:
Updated settings
Example:
{'BASE_DIR': '/Users/dharhas/',
'CACHE_DIR': 'cache',
'PROJECTS_DIR': 'projects',
'USER_SERVICES': [],
}
"""
with open(filename, 'r') as f:
config = yaml.safe_load(f)
# convert keys to uppercase
config = dict((k.upper(), v) for k, v in config.items())
# recursively parse for local providers
config['USER_SERVICES'] = _expand_dirs(config['USER_SERVICES'])
log.info('Settings read from %s' % filename)
update_settings(config=config)
log.info('Settings updated from file %s' % filename)
return settings
def save_settings(filename=None):
"""Save settings currently being used by QUEST to a yaml file.
Args:
filename (string): Path to the yaml file to save the settings.
Returns:
A true boolean if settings were saved successfully.
"""
if filename is None:
filename = _default_config_file()
path = os.path.dirname(filename)
if path:
os.makedirs(path, exist_ok=True)
with open(filename, 'w') as f:
f.write(yaml.safe_dump(settings, default_flow_style=False))
log.info('Settings written to %s' % filename)
log.info('Settings written to %s' % filename)
return True
def _default_config_file():
"""Gives the absolute path of where the settings directiory is.
Returns:
A string that is an absolute path to the settings directory.
"""
base = get_settings()['BASE_DIR']
return os.path.join(base, '.settings', 'quest_config.yml')
def _default_quest_dir():
"""Gives the locations of the Quest directory.
Returns:
A string that is an absolute path to the Quest directory.
"""
quest_dir = os.environ.get('QUEST_DIR')
if quest_dir is None:
quest_dir = os.path.join(os.path.expanduser("~"), 'Quest')
return quest_dir
def _expand_dirs(local_services):
"""Gives a list of paths that have a quest yaml file in them.
Notes:
If any dir ends in * then walk the subdirectories looking for quest.yml
Args:
local_services (list): A list of avaliable paths.
Returns:
A list of avaliable paths to the quest yaml file.
"""
if local_services == []:
return []
expanded = []
for path in local_services:
head, tail = os.path.split(path)
if tail == '*':
for root, dirs, files in os.walk(head):
if os.path.exists(os.path.join(root, 'quest.yml')):
expanded.append(root)
else:
expanded.append(path)
return expanded
|
# Generated by Django 3.0.6 on 2020-06-07 19:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0008_auto_20200607_2126'),
]
operations = [
migrations.RemoveField(
model_name='company',
name='user',
),
]
|
"""
Zhigao空调 BY 菲佣 1.0
"""
from datetime import timedelta
from base64 import b64encode, b64decode
import asyncio
import binascii
import logging
import socket
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.climate import (
PLATFORM_SCHEMA,
ClimateDevice, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW)
from homeassistant.const import (
TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_TEMPERATURE, ATTR_UNIT_OF_MEASUREMENT,
CONF_NAME, CONF_HOST, CONF_MAC, CONF_TIMEOUT)
from homeassistant.helpers import condition
from homeassistant.helpers.event import (
async_track_state_change, async_track_time_interval)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['sensor']
DEFAULT_TOLERANCE = 0.3
DEFAULT_NAME = 'Zhigao Thermostat'
DEFAULT_TIMEOUT = 10
DEFAULT_RETRY = 3
DEFAULT_MIN_TMEP = 16
DEFAULT_MAX_TMEP = 30
DEFAULT_STEP = 1
CONF_SENSOR = 'target_sensor'
CONF_TARGET_TEMP = 'target_temp'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_MAC): cv.string,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
vol.Required(CONF_SENSOR): cv.entity_id,
vol.Optional(CONF_TARGET_TEMP): vol.Coerce(float)
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the generic thermostat platform."""
import broadlink
ip_addr = config.get(CONF_HOST)
mac_addr = binascii.unhexlify(
config.get(CONF_MAC).encode().replace(b':', b''))
name = config.get(CONF_NAME)
sensor_entity_id = config.get(CONF_SENSOR)
target_temp = config.get(CONF_TARGET_TEMP)
broadlink_device = broadlink.rm((ip_addr, 80), mac_addr)
broadlink_device.timeout = config.get(CONF_TIMEOUT)
try:
broadlink_device.auth()
except socket.timeout:
_LOGGER.error("Failed to connect to device")
async_add_devices([DemoClimate(
hass, name, target_temp, None, None, None, None, None,
None, 'off', None, DEFAULT_MAX_TMEP, DEFAULT_MIN_TMEP,
broadlink_device, sensor_entity_id)])
class DemoClimate(ClimateDevice):
"""Representation of a demo climate device."""
def __init__(self, hass, name, target_temperature, target_humidity,
away, hold, current_fan_mode, current_humidity,
current_swing_mode, current_operation, aux,
target_temp_high, target_temp_low,
broadlink_device, sensor_entity_id):
"""Initialize the climate device."""
self.hass = hass
self._name = name if name else DEFAULT_NAME
self._target_temperature = target_temperature
self._target_humidity = target_humidity
self._away = away
self._hold = hold
self._current_humidity = current_humidity
self._current_fan_mode = current_fan_mode
self._current_operation = current_operation
self._aux = aux
self._current_swing_mode = current_swing_mode
self._fan_list = ['On Low', 'On High', 'Auto Low', 'Auto High', 'Off']
self._operation_list = ['heat', 'cool', 'auto', 'off']
self._swing_list = ['Auto', '1', '2', '3', 'Off']
self._target_temperature_high = target_temp_high
self._target_temperature_low = target_temp_low
self._max_temp = target_temp_high + 1
self._min_temp = target_temp_low - 1
self._target_temp_step = DEFAULT_STEP
self._unit_of_measurement = TEMP_CELSIUS
self._current_temperature = None
self._device = broadlink_device
async_track_state_change(
hass, sensor_entity_id, self._async_sensor_changed)
sensor_state = hass.states.get(sensor_entity_id)
if sensor_state:
self._async_update_temp(sensor_state)
@callback
def _async_update_temp(self, state):
"""Update thermostat with latest state from sensor."""
unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
try:
self._current_temperature = self.hass.config.units.temperature(
float(state.state), unit)
except ValueError as ex:
_LOGGER.error('Unable to update from sensor: %s', ex)
@asyncio.coroutine
def _async_sensor_changed(self, entity_id, old_state, new_state):
"""Handle temperature changes."""
if new_state is None:
return
self._async_update_temp(new_state)
yield from self.async_update_ha_state()
@property
def min_temp(self):
"""Return the minimum temperature."""
return self._min_temp
@property
def max_temp(self):
"""Return the maximum temperature."""
return self._max_temp
@property
def target_temperature_step(self):
return self._target_temp_step
@property
def should_poll(self):
"""Return the polling state."""
return False
@property
def name(self):
"""Return the name of the climate device."""
return self._name
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
@property
def current_temperature(self):
"""Return the current temperature."""
return self._current_temperature
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._target_temperature
@property
def target_temperature_high(self):
"""Return the highbound target temperature we try to reach."""
return self._target_temperature_high
@property
def target_temperature_low(self):
"""Return the lowbound target temperature we try to reach."""
return self._target_temperature_low
@property
def current_humidity(self):
"""Return the current humidity."""
return self._current_humidity
@property
def target_humidity(self):
"""Return the humidity we try to reach."""
return self._target_humidity
@property
def current_operation(self):
"""Return current operation ie. heat, cool, idle."""
return self._current_operation
@property
def operation_list(self):
"""Return the list of available operation modes."""
return self._operation_list
@property
def is_away_mode_on(self):
"""Return if away mode is on."""
return self._away
@property
def current_hold_mode(self):
"""Return hold mode setting."""
return self._hold
@property
def is_aux_heat_on(self):
"""Return true if away mode is on."""
return self._aux
@property
def current_fan_mode(self):
"""Return the fan setting."""
return self._current_fan_mode
@property
def fan_list(self):
"""Return the list of available fan modes."""
return self._fan_list
def set_temperature(self, **kwargs):
"""Set new target temperatures."""
if kwargs.get(ATTR_TEMPERATURE) is not None:
self._target_temperature = kwargs.get(ATTR_TEMPERATURE)
if kwargs.get(ATTR_TARGET_TEMP_HIGH) is not None and \
kwargs.get(ATTR_TARGET_TEMP_LOW) is not None:
self._target_temperature_high = kwargs.get(ATTR_TARGET_TEMP_HIGH)
self._target_temperature_low = kwargs.get(ATTR_TARGET_TEMP_LOW)
if self._target_temperature < self._target_temperature_low:
self._current_operation = 'off'
self._target_temperature = self._target_temperature_low
elif self._target_temperature > self._target_temperature_high:
self._current_operation = 'off'
self._target_temperature = self._target_temperature_high
elif self._current_temperature and (self._current_operation == "off" or self._current_operation == "idle"):
self.set_operation_mode('auto')
return
self._sendpacket()
self.schedule_update_ha_state()
def set_humidity(self, humidity):
"""Set new target temperature."""
self._target_humidity = humidity
self.schedule_update_ha_state()
def set_swing_mode(self, swing_mode):
"""Set new target temperature."""
self._current_swing_mode = swing_mode
self.schedule_update_ha_state()
def set_fan_mode(self, fan):
"""Set new target temperature."""
self._current_fan_mode = fan
self.schedule_update_ha_state()
def set_operation_mode(self, operation_mode):
"""Set new target temperature."""
self._current_operation = operation_mode
self._sendpacket()
self.schedule_update_ha_state()
@property
def current_swing_mode(self):
"""Return the swing setting."""
return self._current_swing_mode
@property
def swing_list(self):
"""List of available swing modes."""
return self._swing_list
def turn_away_mode_on(self):
"""Turn away mode on."""
self._away = True
self.schedule_update_ha_state()
def turn_away_mode_off(self):
"""Turn away mode off."""
self._away = False
self.schedule_update_ha_state()
def set_hold_mode(self, hold):
"""Update hold mode on."""
self._hold = hold
self.schedule_update_ha_state()
def turn_aux_heat_on(self):
"""Turn away auxillary heater on."""
self._aux = True
self.schedule_update_ha_state()
def turn_aux_heat_off(self):
"""Turn auxillary heater off."""
self._aux = False
self.schedule_update_ha_state()
def _auth(self, retry=2):
try:
auth = self._device.auth()
except socket.timeout:
auth = False
if not auth and retry > 0:
return self._auth(retry-1)
return auth
def _sendpacket(self,retry=2):
"""Send packet to device."""
cool = ("JgDIAMbxFTQVNBU0FTQUNRI3EjcSNxISEhISEhISFBAVDxUPExESNxI3FDUSNxQ1FTQVNBU0FQ8UEBUPFQ8VDxUPFBASEhISEhISNxI3EjUUNxM2FTQVMxY0FQ8VDxUPEhISEhISEjcSEhQQFTQVNBU0FTQTNhISEjcSNxISEhMVDxUPFQ8TNhE4EjcSNxI3EhISNxQ1FQ8VDxUPFQ8TERM2EhISEhISEjcSEhI3ExEVNBUPFQ8VNBUPFTQUEBUzExISNxI3EvMSAA0F",
"JgDIAMXzEjcSNxM2FDUVNBI3EjcVNBISERMRExISEhISEhMRFQ8UNRU0FDUUNRM1EzcROBE4EhISEhISEhIUEBUPFBAUEBQ1EhISNxE4ETgSNxI3EjcSEhQ1FBAVDxUPFBAVDxQQEzYSEhISETgSNxI3EjcTNhQQFDUVNBUPFBATERISERMRExI3EjcSNxI3FBAUNRQ1FDUVDxUPExESEhE4ERMSEhISEjcSEhQ1FRAUNRUPFQ8UNRISEjcRExI3EhISNxI3FvAUAA0F",
"JgDIAMfxFzQUNRU0FDUTNhI2EjcSOBESEhMVDxMREhESEhITFQ8UNRM2EjYSOBM2FDUTNxI3EhMRExISFBAUEBMTERMSEhQ1FBAUNRU0FDUUNRM1EzYTEhI4ERMTERQQFBAUEBUPFzQUEBMREjcSNhI3EjcSNxITEjcTNhQQFBAUEBUPERITNxMRFDUUNRU0FQ8UNRQ1EhIRNxISEhISEhI4EhIUEBQQFDUVDxQ1FBASNhISEhMSNxQQFDUUEBQ1FBAUNRM2EvISAA0F",
"JgDIAMjwFDUTNhI3ETgSNxI3EjcSNxISFBAVDxUPFRAREhUPFQ8UNRU0FTQUNRM2EjcSNxI3EhISEhMRFBAVDxQQFBAVDxM2EhISNxI3EjcSNxI3EjcUEBQ1FRATEBQQFQ8VDxUQEjcSEhISFDUVNBU0FTQVNBQQEzYSNxETEhISEhISEhIVDxUPFDUVNBU0ExESNxE4EjcSNxISEhITERQ1FQ8VDxUPFTQUEBI3EhIVNBUPFQ8VNBMREjcRExI3EhISNxI3EvMUAA0F",
"JgDIAMTzEjcSNxQ1FTQVNBU1FDUUNRMREhISEhESEhISEhISEhIbNxI3EjcSNxI3EjcVNBU0FRAUEBQQFBASEhIREhISEhI3EhETNxQ1FTQVNBU1FDUUEBM2EhIREhISEhISFBMREjcSERISEjcSNxY0FTQVNRQQEzYRNxISEhISEhUPFQ8VNhU1FBAUNRI2EhISNxI3EhISEhI3FQ8VERQ0FRAUEBQREjYSEhE3EhISNxYOFQ8VNBUQFDUUEBI3EhIRNxI3EvMSAA0F",
"JgDIAMT0EjcUNRI3EjcVNBQ1FTQVNBUPFBATERISERMRExISEhISNxQ1FTQVNBQ1FTQUNRM2EhIRExETERMSEhISFBATERI3ERMSNxE4ETgSNxI3EjcUEBQ1FBAUEBUPFRASEhISETgRExISEjcVNRU0FDUVNBUPEjcSNxISEhIUEBQQFBAWEBI3ERMROBI3EhIWNBM2EjcRExE4EhIRExE4EhISEhISFTQUEhI3EhITNhQQFQ8VNBUPFTQUEBI2ExIROBE4EvMSAA0F",
"JgDIAMjwFTUUNRQ1EjYTNhI3EjcSNhMSEhIVDxUQFBAUEBQQFBATNhI2EjcSNxI3EjcSNxU0FRAUEBQQFBAUEBMQExIREhI3EhISNxI3EjcVNBU1FDQVEBQ1FBATERESEhISEhISEjcSEhUQFDQVNRQ1FDUUNRMREjYTNhISEhISEhISEhMSNhISEhISNxI3EhIVNBU0FRAUMxY1ExETEBM2EhISEhISEjcSEhM2FQ8VNRQQFBAUNRQQFDUUEBQ1EhISNhI3EvMSAA0F",
"JgDIAMjwFDUTNhI3ETgSNxI3EjcSNxISFQ8VDxUPFQ8UEBUPFBAVNBQ1EzYSNxI3EjcSNxI3EhITERUPFRAREhUPFQ8VDxI3EhISORQ1EzYSNxI3EjcSEhI3EhITERUPFQ8VERETEjcSEhISEjcSOBU0FTIXNBQQFTQSNxISEhISEhISEhISEhMRFBAVNBU0FQ8UNRM2EjcSNxI3EhISEhI3ExEUEBUPFDUUEBQ1ExESNxISFBASNxISEjcSEhI3EhITNhQ1FfAUAA0F",
"JgDIAMXzEjcSNxI3EjcVNBU0FTQVNBUPFRARExETERISEhISEhISNxM2FTQVNBU0FTQVNBQ2ERISEhITERMREhISEhISEhI3EhIUNRU0FTQVNBU0FTQUERE3EhISEhISEhISEhISFTQVDxUPFTQVNBQ2ETgRNxISEjcSNxISEhIVDxUPFQ8VNBU0FTQVEBQ0FQ8VNRE2ExISEhISEjcVDxU0FQ8VDxUPFTURExE3EhISNxISEhISNxMRFTQVDxU0FQ8VNBQ2EfQRAA0F",
"JgDIAMbzEjcUNRQ1FDUVNBU0EzYSNxIREhISEhITERMSEhISERISNxI3EjgSNxM2FDUUNRQ1FBASEhISERISEhITERMSEhI3Fg8UNRU0FTQUNRI2EjgSEhM2FBAUEBMSERISEhISEjcSEhMSFDUUNRQ1ETcSNxcQFDUUNRQQEhIRExESFxAUEBI2EjcSEhI3ExISOBI3EzYUEBQQFTUUEBM2EhIREhISEjcSExI3ExEUNRQQFBAXNBQQEzUSEhI3EhIXNBQ1FfAUAA0F",
"JgDIAMb0ETcSNxI3EjcSNxI3FDUVNBUPFQ8VDxQQEhISEhISEhISNxI3EjcVNBU0FTQVNBU0FBASEhISEhISEhISEhISEhU0FQ8VNBU0FTQVNBM2EjcSEhI3EhISEhISEhIUEBUPFTQVDxUQFTQVNBI3EjcSNxISEjcSNxISFBAVEBESEhIVNBUPFTQVDxU0FBATNBc0FQ8VNxESEjcSEhI3EhIVDxUREzYSEhI3EhISNxITFQ8VNBQQFTMWDxQ1ExISNxI3EvMSAA0F",
"JgDIAMTzEjcSNxI3EjcUNRU0FTQVNRQQFBATERISERISEhISEhISNxI3FTQVNBU0FTUUNRQ1ExESEhESEhISEhISExIREhI3EhISNxI3EjcVNBU0FTQVEBQ1FBAUEBIREhISEhISEjcSEhQQFTQVNBU0FTQVNBQREzYSNhISFQ8VEBQQFBAUEBISETcSEhI3EhISNxI3FTQVNBUPFTQVEBQ1ExESERISEjcSEhI3EhISNxUPFQ8VNBUQFDUTERI3EhESNxI3EvQRAA0F",
"JgDIAMbzEjcSOBI3FDUUNRQ1FDUVMhYQExESEhETERISExETEhITNhQ1FTQUNRQ1FDUTNhI2EhISExESEhMSEhMRFBAUEBQ1FBAUNRM2EjYSNxI3EjQVExI3EhIUEBQQFBAUEBQQEzYSEhISETcSOBE4EjcSNxQQFDUUNRUPFBATERIREhMRNxI3EhMSEhE4EhITNhQ1FBEUDxU0FDUTERI2ExESEhITETgRExI3FBAUNRUPFBAUNRQREjYUEBQ1FBAVNBQ1FPESAA0F",
"JgDIAMXzEjcUNRQ1FTQUNRQ1FDQTNxISERMRExISEhISEhQQFBAUNRU0FDUTNhI3ETgROBM2EhIRExETEhISEhISFBAUEBI3EhIROBE4EjcUNRQ1FDUUEBU0FQ8UERIREhIRExETETYUEhISEzYUNRQ1FTQVNBUPFTQTNhISERMRExQQFBAUEBM2ExESEhE4ERMROBI3EjgSEhI3FDUUEBQzFw8VDxMREjcSEhE4ExISNxISEhIUNRQQFDUVDxQ1FBETNRU0FPMRAA0F",
"JgDIAMjxFDUUNRM2EjYSNxI3EjcSNxISFBAVDxUQFBAUEBQQEhISNhI3EjcSNxI3EjcSNxU0FQ8VEBQQExETERISEhESEhI3EhISNxI3FTQVNBU0FTQVDxU0FRASEhIREhISEhISEjcSEhQQFTQVNBU1FDUUNRISEjYSNxISEhISEhISFBAVNBUQFBAUEBQ1ExESNxI2EhISNxI3EjcSEhU0FQ8VEBUQFDUTERI3ERISNxMRFQ8VNBUQFDUUEBQ1EhISNhI3EvMSAA0F")
off = "JgDIAMXzEjcUNRU0FDUVNBU0FTQTORQPFBAUEBUPEhISEhQQFBAVNBU0EzYTNhI3EjcROBI3EhAUEhISFBAUEBQQFBAVDxU0ETgSNxI3EjcSNxQ1FDUVDxQQEhISEhISEhIUEBQQFTQUNRUPEzYSNxI3ETgROBISEhISNxISFBAUEBQQFQ8VDxM2EjcSEhE4ETcTNxI3EjcSEhQQFDUVDxQQFBASEhISETgRExI3EhISNxQQFQ8UNRQQFTQUEBM2ExESNxE4EvMSAA0F"
heat = ("JgDIAMfxFDUUNRQ1FDUUNRM2EjYSNxISEhITEhISFBAUEBQQFw8UNRQ0FDYSNxM2FDUUNRQ1FBAUEBQQFBAUEBUPERISEhMSEhIUNRQ1FDQVNRQ1FDUTNhI3ERISEhISEhISEhMSFDUUEBQQFDUSNhI3EjcSNxISFjQTNhMSExAUEBQQFQ8TNhM2EjcSNhI3EjcSNhMSExISEhQQFBAUEBQQFBAUNRISETcSEhI3EhISOBISExEUNBUQFDUUEBQ1ExESNhI3EvMSAA0F",
"JgDIAMfyFDUSNxI2EjcSNxI3EjcUNRUPFQ8VEBQQFBATERMREhESNxI3EjcWMxU1FDUUNBQ2EhISERISEhISEhISEhIVDxU0FRAUNRQ1FDUSNhM2EjcSEhI3EhIUEhISEhISEhISFTQVEBQPFTYVNRQ1FDUSNhMREjcSNxISEhISEhcPFBAUEBQ1EzQUNxM2FDUVMRgPFTQTERUPFQ8VDxUQERISNxISEjcSEhU0FQ8VNRQQFBATNhIREjcSEhI3EhISNxQ1FfAVAA0F",
"JgDIAMfxFDUTNhI2EjcSNxI3EjcSNxMRFRAUEBQQFBAUEBQQExESNhI3EjcSNxI3EjcUNRU0FRAUEBQQFBATERISEhESEhI3EhISNxM2FTQVNRQ1FDUUEBM2EhISERISEhISEhISEzYVDxUPFTUUNRQ1FDUUNRISEjYSNxISFBAVEBQQFBAUNRQQFDcTNhI3EjYSNxISEhISNxISFBEUEBQQFBAUNRQQEzYSERI3EhITNhUPFRAUNBUQFDUUEBM2EhIRNxI3EvMSAA0F",
"JgDIAMTzEjcSNxU0FTQVNBU1FDUTNRMREhISEhISEhISEhQREhISNxE3EjcSNxU0FTQVNBU0FRATERISERISEhISEhISEhI3FBIRNxQ1FTQVNBU0FTQVEBI2ExESEhIUFBAUEBQQEjYSEhISEjkVNBU0FTUUNRISETcSNxISFQ8VDxUPFRIUEBISETcSNxI3EjcSNxISFTQVNBUQFA8VDxUQFBATNRISEjoREhI3EhISNxISFBAVNBUPFTQSEhI3EhISNxQ1FfAVAA0F",
"JgDIAMT0EjcSNxI3EjcUNRQ1FTQVNBUPFBATERISERMSEhISFQ8VNBQ2FDQVNBI3EjcSNxI1FRESEhISEhISEhQQFBEUEBU0FQ8VNBU0EzYTNhI3ETgSEhI3EhISEhISFBAUEBUPFTcTEBQQFDUVNBU0FDUTNhISETgSNhMTFQ8UEBQQExEVNBQ1FREROBI3EjcSNxISFBAVDxU0FQ8TERMRERMROBISEjcSEhI3FBAVNBQQFQ8VNBQQEzYSEhE4EhISNxI3EvMUAA0F",
"JgDIAMTzEjcSNxI3EzYVNBU1FDUVMhYQFBATERISERISEhISEhISNxM2FDYUNBU0FTUUNRQ1ExESEhETERISEhISEhIUERQ0FRAUNRQ1FDUUNRM2EjYSEhI3EhISEhMRFRAUEBQQFDUTEBUQFDUUNRQ1FDUTNhISETcSNxISEhITERQRFBAUEBQ1FBAUNRQ1EzYSNhISEjcSEhI3FBEUEBQQExETNhISFDUUEBQ1FBATNhITExAVNRQQFDUUEBQ2ERISNxI3EvMUAA0F",
"JgDIAMjwFTQVNRU0FDUSNxE4EjcSNxISEhITERUPFQ8UEhMQFQ8VNBU0FTQVNBI3EjcROBI3FQ8VDxQQExEVDxUPFQ8VDxQ1EhIROBE4EjcSNxI3EjcVDxU0FQ8VDxUPExETERETETgSEhUPFDUVNBU0FTQUNhQPFTQVNBUPFQ8TERISERMSNxISEhISNxI3EjcUNRUPFQ8VNBU0FBATERISERMROBISEjcSEhI3FBAVNBUPFQ8VNBUPFTQTERU0FQ8VNBI3EvMSAA0F",
"JgDIAMfwFTQVNRQ1FTQVNBU1FDUTNBQSERISEhISEhISEhQQFQ8VNhU1FDMWNRQ1EzYSNhI3EhISEhYPFBAUEBQQEhIUEBQ1FBAUNRM2EjYSNxI3EjcSEhI3EhIVDxUPFRAUEBQQFDUTERIREjcSNxI3EjYTNxQQFTQVNBUQFBAUDxUQFBAUEBQQEhISNhI3EjcSNxISFDUVNBU0FQ8VEBQQFBAUNRISEjYSEhI3EhISNxISFQ8VNBUQFDUUEBQ1ExESNhI3EvMSAA0F",
"JgDIAMfwFTQVNBU0FTQUNRI3EjcSNxISEhISEhUPFQ8VDxUPFQ8UNRM2EjYTNxI3EjcSNxI3FBAVDxUPFQ8VDxUPExESExE3EhISNxI3EjcUNRU1EjcSEhI3EhISEhMRFREVDxMREjcSEhISEjcSNxI3FTQVNBUPFTQVNBUPFBASEhISEhISNxI3EjcVDxU0FTQVNBUPFBATERISEjcSEhISEhISNxISEjcSEhI3EhISNxUPFQ8VNBUQFDQVDxQ1ExESNxI3EvUSAA0F",
"JgDIAMjwFTQUNRM2EjcROBI3EjcSNxISFQ8VDxUPFQ8VDxUPExESNxE4EjcSNxI3EzYVNBI3EhISEhISEhISEhISFQ8VDxM2FBATNhE4ETgSNxI3EzgSEhI3EhITERUPFQ8WEBUPFTQVDxMREjcROBE4EjMWNxISEzYVNBQQFQ8VDxUPFQ8TERI3ETgRExI3EjcSNxISFTQVDxUPFTQVDxQQFBASNxETETgSEhI3EhITNhUQERITNhUPFTQVDxU0FQ8VNBM2E/ITAA0F",
"JgDIAMTzEjcSNxI3FTMWNBU0FTUUNBUQExESEhESEhISEhISEhISNxQ3ETcSNxI3EjcSNxU0FQ8VDxUPFRAVDxUPFRAUEBQ1EhIRNxY2EjYSNxI3EjcSEhI3FQ8VDxUPFRAUEBQREjYSEhISEjcSNxczFTUUNRQQEjcVMxUPFRAUEBMREhIRNxcPFTQVDxU0FTUUNRMRERISNxISEjcSEhQSEhISNxISEjcVDxU0FQ8VMBkQFBASNxIREjkSEhI3EhISNxI3FfAVAA0F",
"JgDIAMT0EjMWNxI3EjcTNhU0FDUVNBUPFBATERISERMSEhIUEhIROBI3EjcSNxE4ETgSNxI3EhIVDxIREhMRExUPFQ8TERM2EhIROBI3EjcSNxI3FDUVDxU0FQ8VDxQQEhIRExETEjcSEhISEjcSNxI3FTQVNBUQEzUVNBMRERMSEhISEhISEhQQFTQVDxU0FTQVNBUPFTQVNBUPFDUSEhETEhISNxISEjcTERU0FBAVNBUPFQ8TNhISETgRExI3EhISNxI3FfAVAA0F",
"JgDIAMTzFTUSNhI3EjcSNxI3EjcUNRUPFRAUEBQQFBAUEBQQExERNxI3EjcSNxI3EzYVNBU1FBAUEBQQFBATERESFg8UEBQ1FBAUNRM2EjYSNxI3EjcSEhI3FQ8VEBQQFBAUEBQQEzYSERISEjcSNxI3EjcVNBUQFDQVNRQQEhESEhISEhIVNBU0FRAUEBQ1FDUUNRMREhESEhI3EjcSEhISExEVNBUQFDUUEBQ1FBATNRMRExEUNRUPFTQVEBQ1ExESNxI3EvMSAA0F",
"JgDGABU0FTQTORQ0FTQUNRM2EjcSEhISEhISEhISFQ8VDxUPFTQVNBQ1EzYSNxI3EjcSNxISEhIUEBUPFQ8VDxUPFQ8UNRMREjcSNxI3EjcSNxI3FBAVNBUPFBAVDxUPFBASEhE4EhISEhI3EjcSNxU0FTQVDxU0FTQVDxMRExESEhISEhISNxISEhIVNBU0FTQVEBQ0FQ8VNBQ1EhIRExISEjcSEhU0FQ8TNxQPFTQVDxUPFTQVDxM2EhIROBISEjcSNxLzEgANBQAA",
"JgDIAMTzFTQVNBU1FDQVNRQ1EzYSNhISEhISEhISEhIUEBUPFRAUNRI2EjcSNxI3EjcTNhU0FRAUEBQQFBAUEBQQEhISERI3EhISNxI3EjcSNxU0FTQWEBQ0FRATERMRERISEhISFTYSEhISFTQVNRQ1FDUUNRQQEzYSNxESEhISEhITFBATNRMSERISEhI3EjcSNxQQFQ8VNBU0FTUUEBQQExESNhISEjcSEhI3EhIWNBQQFBATNhMRETcSEhI3EhISNxI3FfAVAA0F")
if (self._current_operation == 'idle') or (self._current_operation =='off'):
sendir = b64decode(off)
elif self._current_operation == 'heat':
sendir = b64decode(heat[int(self._target_temperature) - self._target_temperature_low])
elif self._current_operation == 'cool':
sendir = b64decode(cool[int(self._target_temperature) - self._target_temperature_low])
else:
if self._current_temperature and (self._current_temperature < self._target_temperature_low):
sendir = b64decode(heat[int(self._target_temperature) - self._target_temperature_low])
else:
sendir = b64decode(cool[int(self._target_temperature) - self._target_temperature_low])
try:
self._device.send_data(sendir)
except (socket.timeout, ValueError) as error:
if retry < 1:
_LOGGER.error(error)
return False
if not self._auth():
return False
return self._sendpacket(retry-1)
return True |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated 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.
"""Tests for lambda_executor.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import asyncio
from absl.testing import absltest
import tensorflow as tf
from tensorflow_federated.python.common_libs import anonymous_tuple
from tensorflow_federated.python.core.api import computation_types
from tensorflow_federated.python.core.api import computations
from tensorflow_federated.python.core.api import intrinsics
from tensorflow_federated.python.core.impl import computation_building_blocks
from tensorflow_federated.python.core.impl import eager_executor
from tensorflow_federated.python.core.impl import executor_test_utils
from tensorflow_federated.python.core.impl import federated_executor
from tensorflow_federated.python.core.impl import lambda_executor
from tensorflow_federated.python.core.impl import placement_literals
from tensorflow_federated.python.core.impl import type_constructors
class LambdaExecutorTest(absltest.TestCase):
def test_with_no_arg_tf_comp_in_no_arg_fed_comp(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
@computations.federated_computation
def comp():
return 10
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(ex.create_call(v1))
result = loop.run_until_complete(v2.compute())
self.assertEqual(result.numpy(), 10)
def test_with_one_arg_tf_comp_in_no_arg_fed_comp(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32)
def add_one(x):
return x + 1
@computations.federated_computation
def comp():
return add_one(10)
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(ex.create_call(v1))
result = loop.run_until_complete(v2.compute())
self.assertEqual(result.numpy(), 11)
def test_with_one_arg_tf_comp_in_one_arg_fed_comp(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32)
def add_one(x):
return x + 1
@computations.federated_computation(tf.int32)
def comp(x):
return add_one(add_one(x))
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(ex.create_value(10, tf.int32))
v3 = loop.run_until_complete(ex.create_call(v1, v2))
result = loop.run_until_complete(v3.compute())
self.assertEqual(result.numpy(), 12)
def test_with_one_arg_tf_comp_in_two_arg_fed_comp(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32, tf.int32)
def add_numbers(x, y):
return x + y
@computations.federated_computation(tf.int32, tf.int32)
def comp(x, y):
return add_numbers(x, x), add_numbers(x, y), add_numbers(y, y)
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(ex.create_value(10, tf.int32))
v3 = loop.run_until_complete(ex.create_value(20, tf.int32))
v4 = loop.run_until_complete(
ex.create_tuple(
anonymous_tuple.AnonymousTuple([(None, v2), (None, v3)])))
v5 = loop.run_until_complete(ex.create_call(v1, v4))
result = loop.run_until_complete(v5.compute())
self.assertEqual(
str(anonymous_tuple.map_structure(lambda x: x.numpy(), result)),
'<20,30,40>')
def test_with_functional_parameter(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32)
def add_one(x):
return x + 1
@computations.federated_computation(
computation_types.FunctionType(tf.int32, tf.int32), tf.int32)
def comp(f, x):
return f(f(x))
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(ex.create_value(add_one))
v3 = loop.run_until_complete(ex.create_value(10, tf.int32))
v4 = loop.run_until_complete(
ex.create_tuple(
anonymous_tuple.AnonymousTuple([(None, v2), (None, v3)])))
v5 = loop.run_until_complete(ex.create_call(v1, v4))
result = loop.run_until_complete(v5.compute())
self.assertEqual(result.numpy(), 12)
def test_with_tuples(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32, tf.int32)
def add_numbers(x, y):
return x + y
@computations.federated_computation
def comp():
return add_numbers(10, 20)
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(ex.create_call(v1))
result = loop.run_until_complete(v2.compute())
self.assertEqual(result.numpy(), 30)
def test_with_nested_lambdas(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32, tf.int32)
def add_numbers(x, y):
return x + y
@computations.federated_computation(tf.int32)
def comp(x):
@computations.federated_computation(tf.int32)
def nested_comp(y):
return add_numbers(x, y)
return nested_comp(1)
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(ex.create_value(10, tf.int32))
v3 = loop.run_until_complete(ex.create_call(v1, v2))
result = loop.run_until_complete(v3.compute())
self.assertEqual(result.numpy(), 11)
def test_with_block(self):
ex = lambda_executor.LambdaExecutor(eager_executor.EagerExecutor())
loop = asyncio.get_event_loop()
f_type = computation_types.FunctionType(tf.int32, tf.int32)
a = computation_building_blocks.Reference(
'a', computation_types.NamedTupleType([('f', f_type), ('x', tf.int32)]))
ret = computation_building_blocks.Block(
[('f', computation_building_blocks.Selection(a, name='f')),
('x', computation_building_blocks.Selection(a, name='x'))],
computation_building_blocks.Call(
computation_building_blocks.Reference('f', f_type),
computation_building_blocks.Call(
computation_building_blocks.Reference('f', f_type),
computation_building_blocks.Reference('x', tf.int32))))
comp = computation_building_blocks.Lambda(a.name, a.type_signature, ret)
@computations.tf_computation(tf.int32)
def add_one(x):
return x + 1
v1 = loop.run_until_complete(
ex.create_value(comp.proto, comp.type_signature))
v2 = loop.run_until_complete(ex.create_value(add_one))
v3 = loop.run_until_complete(ex.create_value(10, tf.int32))
v4 = loop.run_until_complete(
ex.create_tuple(anonymous_tuple.AnonymousTuple([('f', v2), ('x', v3)])))
v5 = loop.run_until_complete(ex.create_call(v1, v4))
result = loop.run_until_complete(v5.compute())
self.assertEqual(result.numpy(), 12)
def test_with_federated_apply(self):
eager_ex = eager_executor.EagerExecutor()
federated_ex = federated_executor.FederatedExecutor({
None: eager_ex,
placement_literals.SERVER: eager_ex
})
ex = lambda_executor.LambdaExecutor(federated_ex)
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32)
def add_one(x):
return x + 1
@computations.federated_computation(type_constructors.at_server(tf.int32))
def comp(x):
return intrinsics.federated_apply(add_one, x)
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(
ex.create_value(10, type_constructors.at_server(tf.int32)))
v3 = loop.run_until_complete(ex.create_call(v1, v2))
result = loop.run_until_complete(v3.compute())
self.assertEqual(result.numpy(), 11)
def test_with_federated_map_and_broadcast(self):
eager_ex = eager_executor.EagerExecutor()
federated_ex = federated_executor.FederatedExecutor({
None: eager_ex,
placement_literals.SERVER: eager_ex,
placement_literals.CLIENTS: [eager_ex for _ in range(3)]
})
ex = lambda_executor.LambdaExecutor(federated_ex)
loop = asyncio.get_event_loop()
@computations.tf_computation(tf.int32)
def add_one(x):
return x + 1
@computations.federated_computation(type_constructors.at_server(tf.int32))
def comp(x):
return intrinsics.federated_map(add_one,
intrinsics.federated_broadcast(x))
v1 = loop.run_until_complete(ex.create_value(comp))
v2 = loop.run_until_complete(
ex.create_value(10, type_constructors.at_server(tf.int32)))
v3 = loop.run_until_complete(ex.create_call(v1, v2))
result = loop.run_until_complete(v3.compute())
self.assertCountEqual([x.numpy() for x in result], [11, 11, 11])
def test_with_mnist_training_example(self):
executor_test_utils.test_mnist_training(
self, lambda_executor.LambdaExecutor(eager_executor.EagerExecutor()))
if __name__ == '__main__':
tf.compat.v1.enable_v2_behavior()
absltest.main()
|
from unittest import TestCase
import numpy as np
import matplotlib.pyplot as plt
from hyperspy.signals import Signal2D
from empyer.signals.power_signal import PowerSignal
class TestPowerSignal(TestCase):
def setUp(self):
d = np.random.rand(10, 10, 720, 180)
self.s = Signal2D(d)
self.ps = PowerSignal(self.s)
self.ps.set_axes(2,
name="k",
scale=.1,
units='nm^-1')
def test_i_vs_k(self):
self.ps.get_i_vs_k()
self.ps.get_i_vs_k(symmetry=[6])
def test_get_map(self):
mapped = self.ps.get_map(k_region=[3.0, 6.0])
mapped = self.ps.get_map(k_region=[3.0, 6.0], symmetry=10)
mapped = self.ps.get_map(k_region=[3.0, 6.0], symmetry=[8, 9, 10])
print(mapped)
mapped.plot()
plt.show()
self.ps.get_map(symmetry=10)
def test_lazy(self):
print(self.ps.as_lazy())
|
# this is first program for git testing
def printHelloWorld():
print('Hello World!')
if __name__ == '__main__':
printHelloWorld() |
import _initpath
import os
import re
import collections
import pyradox
province_map = pyradox.worldmap.ProvinceMap(game = 'EU4')
colormap = {}
for filename, data in pyradox.txt.parse_dir(os.path.join(pyradox.get_game_directory('EU4'), 'history', 'provinces'), verbose=False):
m = re.match('\d+', filename)
province_id = int(m.group(0))
if ('base_tax' in data and data['base_tax'] > 0):
colormap[province_id] = (255, 255, 255)
out = province_map.generate_image(colormap, default_land_color=(95, 95, 95))
pyradox.image.save_using_palette(out, 'out/blank_map.png')
|
# __init__.py are used to mark directories on disk as Python package directories
# importing all modules from dir |
from flask import Flask
app = Flask(__name__)
import histogram_exercises
import dictionary_words
# import tweetGenTutorials
import creating_randomness
import ClassDictogram as d
@app.route('/')
def generate_word():
return d.Dictogram.generate_sentence_from_markov_chain(10)
if __name__ == '__main__':
# Turn this on in debug mode to get detailled information about request related exceptions: http://flask.pocoo.org/docs/0.10/config/
app.config['TRAP_BAD_REQUEST_ERRORS'] = True
app.run(debug=True) |
from django.contrib.auth.views import LoginView
from django.shortcuts import render
# Create your views here.
from django.views import View
from accounts import handlers as accounts_handlers
class CustomerLoginView(View):
def get(self, request, *args, **kwargs):
return render(request, 'accounts/login.html')
def post(self, request, *args, **kwargs):
return accounts_handlers.customer_login_handler(request)
|
# Linear Search function used to find an item in a list.
def linear_search(my_item, my_list):
found = False
position = 0
while position < len(my_list) and not found:
if my_list[position] == my_item:
found = True
position = position + 1
return found
if __name__ == "__main__":
shopping_list = ["apples", "bananas", "cherries", "duraznos"]
item = input("What item do you want to find?")
is_it_found = linear_search(item, shopping_list)
if is_it_found:
print("Your item is on the list.")
else:
print("Your item is not on the list")
|
# This function is not intended to be invoked directly. Instead it will be
# triggered by an orchestrator function.
# Before running this sample, please:
# - create a Durable orchestration function
# - create a Durable HTTP starter function
# - add azure-functions-durable to requirements.txt
# - run pip install -r requirements.txt
import logging
#to use another method besides main, customize the entryPoint property in this function's function.json
def add_one(number: int) -> int:
return number + 1 |
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch(hosts="10.0.0.45")
doc = {
'name': 'David gidony',
'numberOfPeople': '3',
'groupName': 'Close Family',
'eMail': 'dudug@index.co.il',
'cellPhone': '0522808442',
'validated': 'yes',
'autoRemind': 'yes',
'comment': 'tesing 123...',
'timestamp': datetime.now()
}
res = es.index(index="guestsList", doc_type='doc', id=1, body=doc)
print(res['result'])
res = es.get(index="guestsList", doc_type='doc', id=2)
print(res['_source'])
es.indices.refresh(index="guestsList")
res = es.search(index="guestsList", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total'])
for hit in res['hits']['hits']:
print(hit) |
import os
import csv
from pdb import set_trace
import pickle
def extract_feature(base, csvpath):
events = [event for event in os.listdir(csvpath) if event.__contains__('event')]
comments = [comment for comment in os.listdir(csvpath) if comment.__contains__('comment')]
milestones = [milestone for milestone in os.listdir(csvpath) if milestone.__contains__('milestone')]
milestone_dict = get_milestone_dict(csvpath, milestones)
milestone_dict = load_obj(os.path.join(csvpath, 'DictMilestone'))
group_features1 = process_event(csvpath, events)
group_features2 = process_comment(csvpath, comments)
generate_assignees_csv(base, group_features1)
generate_issueDuration_csv(base, group_features1)
generate_issueMilestone_csv(base, group_features1)
generate_issueHasLabel_csv(base, group_features1)
generate_issueDelay_csv(base, group_features1)
generate_userCommentNum_csv(base, group_features2)
generate_issueCommentNum_csv(base, group_features2)
generate_issueParticipants_csv(base, group_features2)
print 'csv generated'
def get_milestone_dict(csvpath, comments):
group_dict = {}
for group in comments:
with open(os.path.join(csvpath, group), 'r') as csvinput:
milestone_dict = {}
reader = csv.DictReader(csvinput)
## begin extract information from each row, i.e. event.
for row in reader:
tmp = {row['id']: {'created_at': row['created_at'], 'due_at': row['due_at'], 'closed_at': row['closed_at']}}
milestone_dict.update(tmp)
groupID = (group.split('-'))[0][5:]
group_dict.update({groupID: milestone_dict})
save_obj(group_dict, os.path.join(csvpath, 'DictMilestone'))
return group_dict
def process_comment(csvpath, comments):
group_features = {}
for group in comments:
with open(os.path.join(csvpath, group), 'r') as csvinput:
user_comments = {}
issue_comments = {}
issue_uniqeUser = {}
reader = csv.DictReader(csvinput)
## begin extract information from each row, i.e. event.
for row in reader:
## (5) Number of People Commenting on an Issue
user = (row['user'].split('/'))[1]
if not user_comments.get(user):
user_comments[user] = 1
user_comments[user] += 1
## (8) Number of Comments on an Issue
issueID = row['issueID']
if not issue_comments.get(issueID):
issue_comments[issueID] = 1
issue_comments[issueID] += 1
## (11) Percentage of Comments by User
if not issue_uniqeUser.get(issueID):
issue_uniqeUser[issueID] = set([user])
issue_uniqeUser[issueID].add(user)
groupID = (group.split('-'))[0][5:]
if not group_features.get(groupID):
group_features[groupID] = {}
group_features[groupID]['User: CommentNum'] = user_comments
group_features[groupID]['Issues: CommentNum'] = issue_comments
group_features[groupID]['Issues: Participants'] = {k: len(v) for k,v in issue_uniqeUser.iteritems()}
print group + ' finished'
return group_features
def process_event(csvpath, events):
milestone_dict = load_obj(os.path.join(csvpath, 'DictMilestone'))
group_features = {}
for group in events:
groupID = (group.split('-'))[0][5:]
with open(os.path.join(csvpath, group), 'r') as csvinput:
issue_times = {}
issue_milestone = {}
issue_delay = {}
issue_hasLabel = {}
user_assigned = {}
reader = csv.DictReader(csvinput)
## begin extract information from each row, i.e. event.
for row in reader:
issueID = row['issueID']
## (1) Issues Durations
if not issue_times.get(issueID):
issue_times[issueID] = [row['time']]
else:
issue_times[issueID].append(row['time'])
## Issue missing milestones
if not issue_milestone.get(issueID):
issue_milestone[issueID] = row['milestone']
## Issue missing labels
if not issue_milestone.get(issueID):
issue_hasLabel[issueID] = False
if row['action'] == 'labeled':
issue_hasLabel[issueID] = True
## (2) Issues delay for its milestone
if row['action'] == 'closed' and row['milestone'] != '':
milestoneID = row['milestone']
tClose = row['time']
try:
ErrorFlag = 0
tDue = milestone_dict[groupID][milestoneID]['due_at']
except KeyError:
ErrorFlag = 1
print 'group ID: ' + groupID + ' milestone ID: ' + milestoneID
if not tDue or ErrorFlag:
delay = 0
else:
delay = (int(tDue)-int(tClose)) / (24*3600)
issue_delay[issueID] = delay
## (4) Equal Number of Issue Assignees
if row['action'] == 'assigned':
user = (row['user'].split('/'))[1]
if not user_assigned.get(user):
user_assigned[user] = [row['issueID']]
else:
user_assigned[user].append(row['issueID'])
if not group_features.get(groupID):
group_features[groupID] = {}
group_features[groupID]['Issue Assignees'] = user_assigned
group_features[groupID]['Issue Times'] = issue_times
group_features[groupID]['Issue Delays'] = issue_delay
group_features[groupID]['Issue Duration'] = {k: get_duration(v) for k,v in issue_times.iteritems()}
group_features[groupID]['Issue Milestones'] = issue_milestone
group_features[groupID]['Issue hasLabel'] = issue_hasLabel
print group + ' finished'
return group_features
def get_duration(times):
"return time in days"
if len(times) <= 1:
return 0
else:
return (int(max(times))-int(min(times))) / (24*3600)
def generate_assignees_csv(base, group_features):
result_file = os.path.join(base, 'featureCSV/issueAssignees.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['Issue Assignees']
users = dict.keys()
input_data = {'groupID': groupID}
input_data.update({user: len(issues) for user, issues in dict.iteritems()})
fileds = ['groupID']
fileds.extend(users)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def generate_userCommentNum_csv(base, group_features):
result_file = os.path.join(base, 'featureCSV/userCommentNum.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['User: CommentNum']
users = dict.keys()
input_data = {'groupID': groupID}
input_data.update(dict)
fileds = ['groupID']
fileds.extend(users)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def generate_issueDuration_csv(base, group_features):
result_file = os.path.join(base, 'featureCSV/issueDuration.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['Issue Duration']
issues = dict.keys()
input_data = {'groupID': groupID}
input_data.update(dict)
fileds = ['groupID']
fileds.extend(issues)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def generate_issueDelay_csv(base, group_features):
result_file = os.path.join(base, 'featureCSV/issueDelay.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['Issue Delays']
issues = dict.keys()
input_data = {'groupID': groupID}
input_data.update(dict)
fileds = ['groupID']
fileds.extend(issues)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def generate_issueMilestone_csv(base, group_features):
result_file = os.path.join(base, 'featureCSV/issueMilestone.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['Issue Milestones']
issues = dict.keys()
input_data = {'groupID': groupID}
input_data.update(dict)
fileds = ['groupID']
fileds.extend(issues)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def generate_issueHasLabel_csv(base, group_features):
result_file = os.path.join(base, 'featureCSV/issueHasLabel.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['Issue hasLabel']
issues = dict.keys()
input_data = {'groupID': groupID}
input_data.update(dict)
fileds = ['groupID']
fileds.extend(issues)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def generate_issueCommentNum_csv(base, group_features):
result_file = csvpath = os.path.join(base, 'featureCSV/issueCommentNum.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['Issues: CommentNum']
issues = dict.keys()
input_data = {'groupID': groupID}
input_data.update(dict)
fileds = ['groupID']
fileds.extend(issues)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def generate_issueParticipants_csv(base, group_features):
result_file = csvpath = os.path.join(base, 'featureCSV/issueParticipants.csv')
with open(result_file, 'w') as csvinput:
for groupID, feature in group_features.iteritems():
dict = feature['Issues: Participants']
issues = dict.keys()
input_data = {'groupID': groupID}
input_data.update(dict)
fileds = ['groupID']
fileds.extend(issues)
writer = csv.DictWriter(csvinput, fieldnames=fileds)
writer.writeheader()
writer.writerow(input_data)
def save_obj(obj, name):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
def issueDiscussionScore():
"for each issue, get the percentage of issues with < 3 followup comments"
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/issueCommentNum.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
commentNum = row[1:]
lessParticipants3 = [i for i in commentNum if int(i) < 3]
lessComment4 = [i for i in commentNum if int(i) < 4]
# percentage of issues with less than 3 comments
bad_smell[groupID] = {'Issue Discussions<3': float(len(lessParticipants3))/len(commentNum)}
bad_smell[groupID].update({'Issue Discussions<4': (float(len(lessComment4))/len(commentNum))})
return bad_smell
def issueParticipantScore():
"for each issue, get the percentage of issues with < 50% participants"
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/issueParticipants.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
participantNum = row[1:]
lessParticipants2 = [i for i in participantNum if int(i) < 2]
lessParticipants3 = [i for i in participantNum if int(i) < 3]
# percentage of issues with less than 3 comments
bad_smell[groupID] = {'Issue Participant<2': float(len(lessParticipants2))/len(participantNum)}
bad_smell[groupID].update({'Issue Participant<3': (float(len(lessParticipants3))/len(participantNum))})
return bad_smell
def longOpenIssues():
"for each issue, get the percentage of issues with >=20 days open"
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/issueDuration.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
duration = row[1:]
longOpen0 = [i for i in duration if int(i) == 0]
longOpen2 = [i for i in duration if int(i) >= 20]
longOpen3 = [i for i in duration if int(i) >= 30]
bad_smell[groupID] = {'Duration = 0': float(len(longOpen0))/len(duration)}
bad_smell[groupID].update({'Duration > 20': float(len(longOpen2))/len(duration)})
bad_smell[groupID].update({'Duration > 30': float(len(longOpen3))/len(duration)})
return bad_smell
def silentUserNum():
"for each group, find if some user far lower than 50% of average Comments Per User "
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/userCommentNum.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
user = removeTim_TA(row[1:])
userCommentNum = [int(num) for num in user[1:]]
average = float(sum(userCommentNum))/len(userCommentNum)
threshold = 0.5 * average
silentUser = 0
for num in userCommentNum:
if num < threshold:
silentUser += 1
bad_smell[groupID] = {'SilentUser Num': float(silentUser)/len(user)}
return bad_smell
def relaxedUserNum():
"for each group, find if some user far lower than 50% of average Issues Assigned to each User "
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/issueAssignees.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
user = removeTim_TA(row[1:])
userAssignmentNum = [int(num) for num in user]
average = float(sum(userAssignmentNum))/len(userAssignmentNum)
threshold = 0.5 * average
relaxedUser = 0
for num in userAssignmentNum:
if num < threshold:
relaxedUser += 1
bad_smell[groupID] = {'RelaxedUser Num': float(relaxedUser)/len(user)}
return bad_smell
def issueWoMilestone():
"for each group, find the percentage of issues without milestone"
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/issueMilestone.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
milestones = row[1:]
noMilestone = [m for m in milestones if not m]
percent = float(len(noMilestone))/len(milestones)
bad_smell[groupID] = {'Issue wo Milstone': percent}
return bad_smell
def issueWoLabel():
"for each group, find the percentage of issues without label"
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/issueHasLabel.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
hasLabel = row[1:]
noLabel = [l for l in hasLabel if l=='False']
percent = float(len(noLabel))/len(hasLabel)
bad_smell[groupID] = {'Issue wo Label': percent}
return bad_smell
def issueDelayed():
"for each group, find the percentage of issues that is closed after milestone duedate"
bad_smell = {}
inputFile = os.path.join(base, 'featureCSV/issueDelay.csv')
with open(inputFile, 'r') as csvinput:
reader = csv.reader(csvinput)
odd = 1
for row in reader:
if odd:
odd = 0
continue
else:
odd = 1
groupID = row[0]
closeTime = row[1:]
delays = [t for t in closeTime if int(t)>0 ]
percent = float(len(delays))/len(closeTime)
bad_smell[groupID] = {'Issue Delayed': percent}
return bad_smell
def removeTim_TA(users):
if len(users) <= 4:
return users
else:
users.sort(reverse = True)
return users[0:4]
def save_badsmell_csv(outputFile, bad_smell, fileds):
with open(outputFile, 'w') as csvoutput:
writer = csv.DictWriter(csvoutput, fieldnames=fileds)
writer.writeheader()
for groupID, bad_smells in bad_smell.iteritems():
row = {'groupID': groupID}
row.update(bad_smells)
writer.writerow(row)
def merge_dict(bad_smell1, bad_smell2):
for groupID, score in bad_smell1.iteritems():
bad_smell1[groupID].update(bad_smell2[groupID])
return bad_smell1
def get_badSmell(base, csvpath):
bad_smell1 = issueDiscussionScore()
bad_smell2 = issueParticipantScore()
bad_smell3 = silentUserNum()
bad_smell4 = relaxedUserNum()
bad_smell5 = longOpenIssues()
bad_smell6 = issueWoMilestone()
bad_smell7 = issueDelayed()
bad_smell8 = issueWoLabel()
bad_smell = merge_dict(bad_smell1, bad_smell2)
bad_smell = merge_dict(bad_smell, bad_smell3)
outputFile = os.path.join(base, 'badSmellScoreCSV/PoorCommunication_early.csv')
fileds = ['groupID', 'Issue Discussions<3', 'Issue Discussions<4', 'Issue Participant<2', 'Issue Participant<3', 'SilentUser Num']
save_badsmell_csv(outputFile, bad_smell, fileds)
bad_smell = merge_dict(bad_smell, bad_smell4)
outputFile = os.path.join(base, 'badSmellScoreCSV/AbsentGroupMember_early.csv')
fileds = ['groupID', 'Issue Discussions<3', 'Issue Discussions<4', 'Issue Participant<2', 'Issue Participant<3', 'SilentUser Num', 'RelaxedUser Num']
save_badsmell_csv(outputFile, bad_smell, fileds)
bad_smell = merge_dict(bad_smell4, bad_smell5)
bad_smell = merge_dict(bad_smell, bad_smell6)
bad_smell = merge_dict(bad_smell, bad_smell7)
bad_smell = merge_dict(bad_smell, bad_smell8)
outputFile = os.path.join(base, 'badSmellScoreCSV/PoorPlanning_early.csv')
fileds = ['groupID', 'Duration = 0', 'Duration > 20', 'Duration > 30', 'RelaxedUser Num', 'Issue wo Milstone', 'Issue wo Label', 'Issue Delayed']
save_badsmell_csv(outputFile, bad_smell, fileds)
print 'done'
if __name__ == "__main__":
base = os.path.abspath(os.path.dirname(__file__))
csvpath = os.path.join(base, 'dataCollectionInCSV_early')
extract_feature(base, csvpath)
get_badSmell(base, csvpath) |
def info_filter(src_string):
start = "#INFO#"
end = "#END#\r\n"
subtract_prefix = (src_string.split(start))[1]
subtract_postfix = subtract_prefix.split(end)[0]
if ':' in subtract_postfix:
execution_result = subtract_postfix.split(':')[0]
info_string = subtract_postfix.split(':')[1]
if execution_result == '0':
return info_string
else:
return 0
else:
return subtract_postfix
def search_log(hugedata, searchfor):
ignoreDict = ['\r\n', '/ # \r\n']
for key in hugedata.keys():
try:
if searchfor == hugedata[key] and searchfor not in ignoreDict:
# update_info_reg(key, "BOOTING")
return key
except Exception:
pass
return repr(searchfor)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import argparse
from PIL import Image
import time
import io
import tflite_runtime.interpreter as tflite
import cv2
import re
CAMERA_WIDTH = 640
CAMERA_HEIGHT = 480
def load_labels(path):
"""Loads the labels file. Supports files with or without index numbers."""
with open(path, 'r', encoding='utf-8') as f:
lines = f.readlines()
labels = {}
for row_number, content in enumerate(lines):
pair = re.split(r'[:\s]+', content.strip(), maxsplit=1)
if len(pair) == 2 and pair[0].strip().isdigit():
labels[int(pair[0])] = pair[1].strip()
else:
labels[row_number] = content.strip() #pair[0].strip()
return labels
def set_input_tensor(interpreter, image):
tensor_index = interpreter.get_input_details()[0]['index']
input_tensor = interpreter.tensor(tensor_index)()[0]
input_tensor[:, :] = image
def get_output_tensor(interpreter, index):
"""Returns the output tensor at the given index."""
output_details = interpreter.get_output_details()[index]
tensor = np.squeeze(interpreter.get_tensor(output_details['index']))
return tensor
def detect_objects(interpreter, image, threshold):
"""Returns a list of detection results, each a dictionary of object info."""
set_input_tensor(interpreter, image)
interpreter.invoke()
# Get all output details
boxes = get_output_tensor(interpreter, 0)
classes = get_output_tensor(interpreter, 1)
scores = get_output_tensor(interpreter, 2)
count = int(get_output_tensor(interpreter, 3))
results = []
print(classes)
print(scores)
for i in range(count):
if scores[i] >= threshold: # i>0 and
result = {
'bounding_box': boxes[i],
'class_id': classes[i],
'score': scores[i]
}
results.append(result)
return results
def visualize_objects(img, results, labels):
"""Draws the bounding box and label for each object in the results."""
for obj in results:
# Convert the bounding box figures from relative coordinates
# to absolute coordinates based on the original resolution
ymin, xmin, ymax, xmax = obj['bounding_box']
xmin = int(xmin * CAMERA_WIDTH)
xmax = int(xmax * CAMERA_WIDTH)
ymin = int(ymin * CAMERA_HEIGHT)
ymax = int(ymax * CAMERA_HEIGHT)
# Overlay the box, label, and score on the camera preview
startpoint = (xmin, ymin)
end_point = (xmax, ymax)
cv2.rectangle(img, startpoint, end_point ,color=(0, 255, 0), thickness=1) # Draw Rectangle with the coordinates
#annotator.bounding_box([xmin, ymin, xmax, ymax])
textlabel = '%s %.2f' % (labels[obj['class_id']], obj['score'])
# print(obj)
#print(int(obj['class_id']))
# print(textlabel)
text_size = 1
cv2.putText(img, textlabel, startpoint, cv2.FONT_HERSHEY_SIMPLEX, text_size, (0,255,0),thickness=1)
#annotator.text([xmin, ymin], '%s\n%.2f' % (labels[obj['class_id']], obj['score']))
def main():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-i',
'--image',
default='data/00871.jpg',
help='image to be classified')
parser.add_argument(
'--model', default='coco_ssd_mobilenet_v1_1/detect.tflite', help='File path of .tflite file.')
parser.add_argument(
'--labels', default='coco_ssd_mobilenet_v1_1/labelmap.txt', help='File path of labels file.')#, required=True
parser.add_argument(
'--threshold',
help='Score threshold for detected objects.',
required=False,
type=float,
default=0.5)
args = parser.parse_args()
labels = load_labels(args.labels)
print('Total classes in label: ', len(labels))
# Load TFLite model and allocate tensors.
interpreter = tflite.Interpreter(args.model)
interpreter.allocate_tensors()
# Get input tensor details
input_details = interpreter.get_input_details()
print(input_details)
output_details = interpreter.get_output_details()
print(output_details)
# check the type of the input tensor
#input_details[0]['dtype']
floating_model = input_details[0]['dtype'] == np.float32
# NxHxWxC, H:1, W:2
height = input_details[0]['shape'][1]
print(height)
width = input_details[0]['shape'][2]
print(width)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise Exception("Could not open video device")
# Set properties. Each returns === True on success (i.e. correct resolution)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, CAMERA_WIDTH)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, CAMERA_HEIGHT)
while(True):
ret, frame = cap.read()
#rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
resized = cv2.resize(frame, (width, height))
start_time = time.time()
results = detect_objects(interpreter, resized, args.threshold)
elapsed_ms = (time.time() - start_time) * 1000
visualize_objects(frame, results, labels)
cv2.putText(frame, '%.1fms' % (elapsed_ms), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
out = cv2.imwrite('capture.jpg', frame)
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main() |
import pandas as pd
df = pd.read_hdf("filtered_data.hdf", "df1")
def page_entity(page):
p = False
if page == "/":
p = 'home'
if "/item/" in page:
p = 'item'
if p == False:
p = 'unknown'
df_pv['page_entity'] = df_pv['data'].apply(lambda x: page_entity(x))
df_pv = df[(df.type == 'page_view') and (df.source == 1)]
len(df_pv.index)
|
from django.contrib.auth.models import AbstractUser
from django.db import models
import random
import string
# Create your models here
class User(AbstractUser):
phone_number = models.CharField(max_length=100)
address = models.CharField(max_length=200)
class Friend(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False, related_name='friends')
friend = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False,
related_name='knowns')
def __str__(self):
return f"{self.user.username} -> {self.friend.username}"
class Bunch(models.Model):
users = models.ManyToManyField(User, null=False, blank=False, related_name="%(class)s_members")
name = models.CharField(max_length=150, unique=False, blank=False, null=False)
creator = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False,
related_name='%(class)s_creator')
token_str = models.CharField(max_length=10, default=''.join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(10)))
def __str__(self):
return self.name
class Expense(models.Model):
main_payer = models.ForeignKey(User, on_delete=models.CASCADE, null=True,
related_name='%(class)s_main_payer')
bunch = models.ForeignKey(Bunch, on_delete=models.CASCADE, null=True,
related_name='%(class)s_bunch')
subject = models.CharField(max_length=150, blank=True, null=True, verbose_name='subject')
description = models.TextField(blank=True, unique=False, null=True, verbose_name='description')
location = models.TextField(blank=True, unique=False, null=True, verbose_name='location')
amount = models.FloatField(max_length=15, verbose_name="amount")
date = models.CharField(max_length=20, blank=True, null=True, verbose_name='date')
picture = models.ImageField(upload_to="images", blank=True, null=True, verbose_name='picture',
default="images/no_image.png")
type_of_calculation = models.IntegerField(blank=True, null=True)
token_str = models.CharField(max_length=10, default=''.join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(10)))
def __str__(self):
return f"{self.main_payer.username} -> {self.bunch.name}"
class Pay(models.Model):
expense = models.ForeignKey(Expense, on_delete=models.CASCADE, null=True)
payer = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
amount = models.FloatField(max_length=15, verbose_name="amount")
def __str__(self):
return f"{self.payer.username} -> {self.amount}"
|
from django.conf.urls import include, url
from django.contrib import admin
from .import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'bulding_api/$', views.BuildinListApiView.as_view(), name='buidinglist'),
url(r'bulding_api/(?P<pk>\d+)/$', views.DetailedBuildingApiView.as_view(), name='buidingdetailed'),
url(r'property_api/$', views.PropertyListApiView.as_view(), name='propertylist'),
url(r'property_api/(?P<pk>\d+)/$', views.DetailedPropertyApiView.as_view(), name='propertydetailed'),
url(r'tenant_api/$', views.TenantListApiView.as_view(), name='tenantlist'),
url(r'tenant_api/(?P<pk>\d+)/$', views.DetailedTenantApiView.as_view(), name='tenetdetailed'),
url(r'company_detail_api/$', views.CompanyDetailListApiView.as_view(), name='companylist'),
url(r'company_detail_api/(?P<pk>\d+)/$', views.DetailedTCompanyDetailApiView.as_view(), name='companydetailed'),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Image, sys
a=1
#sys.path.insert(0,'.')
sys.path.insert(0,'..')
import CLClasses
#import repeatsAverage
class Matrix(CLClasses.Base):
fileCount = 1
def __init__(self, eitherJogosObjOrS2):
CLClasses.Base.__init__(self, eitherJogosObjOrS2)
self.folhaA4 = Image.new('L',(400,400),'white')
def setJogo(self, jogo):
self.jogo = jogo
def generateMatrix(self):
print '='*30
print self.jogo
print '='*30; outMatrix = []
for col in range(self.nOfCols):
outRow = []
for row in range(self.nOfLins):
found = False
for dezena in self.jogo:
y = (dezena-1) / 5
x = (dezena % 5) - 1
if x == -1:
x = 5 - 1
if x==row and y==col:
found = True
dezenaOut = dezena
break
if found:
outRow.append(1)
print str(dezenaOut).zfill(2),
else:
outRow.append(0)
print '__',
outMatrix.append(outRow)
print
self.outMatrix = list(outMatrix)
return outMatrix
def generateVolante(self, folhaDx=0, folhaDy=0):
volante = Image.new('L',(200,200),'white')
dotBlock =Image.new('L',(15,15),'black')
crop = dotBlock.crop((0,0,15,15))
x = 0; y = 0
for row in self.outMatrix:
for col in row:
if col == 1:
volante.paste(crop, (x,y,x+15,y+15))
x = x + 15
y += 15
x = 0
crop = volante.crop((0,0,200,200))
self.folhaA4.paste(crop, (folhaDx,folhaDy,folhaDx+200,folhaDy+200))
print 'folhaDx,folhaDy,folhaDx+200,folhaDy+200', folhaDx,folhaDy,folhaDx+200,folhaDy+200
#volante.show()
def generateFolha(self, jogos):
folhaCoords = ((0,0), (200,0),(0,200),(200,200))
i=0
for jogo in jogos:
self.setJogo(jogo)
self.generateMatrix()
folhaDx, folhaDy = folhaCoords[i]
self.generateVolante(folhaDx, folhaDy)
i+=1
self.savePdf()
def savePdf(self):
self.fileCount += 1
print 'self.fileCount', self.fileCount
filename = 'test%d.pdf' %(self.fileCount)
filename = 'test1.pdf'
self.folhaA4.save(filename)
def cardPrint(jogo):
points=[]
for dezena in jogo:
y = (dezena-1) / 5
x = (dezena % 5) - 1
if x == 0:
x = 5 - 1
point = (x, y)
points.append(point)
print jogo
generateMatrix(points)
if __name__ == '__main__':
pass
'''
jogos = repeatsAverage.getHistoryJogos()
for i in range(2):
jogo = jogos[i]
cardPrint(jogo)
matrix = Matrix('lf')
matrix.setJogo(jogo)
matrix.generateMatrix()
matrix.generateVolante
#generateMatrix(jogo)
''' |
# Import Packages
import cv2
from matplotlib import pyplot as plt
from matplotlib import gridspec as gridspec
import numpy as np
# Gridspec (Untuk mengatur letak gambar output)
gs = gridspec.GridSpec(5, 6)
# File path (sesuai directory file input)
path = r'D:\User Projects\PCD\tugasPCD\image-sample.JPG'
# import file
original = cv2.imread(path)
""" --- Show the Image --- """
plt.subplot(gs[0:2, 0:2])
plt.title('1. Original Image')
plt.imshow(original, cmap="gray", vmin=0, vmax=255)
"""Preprocessing"""
# Convert image in grayscale
gray_im = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
""" --- Show the Image --- """
plt.subplot(gs[0:2, 2:4])
plt.title('2. Grayscale Image')
plt.imshow(gray_im, cmap="gray", vmin=0, vmax=255)
# Contrast adjusting with gamma correction y = 1.2
gray_correct = np.array(255 * (gray_im / 255) ** 1.2 , dtype='uint8')
""" --- Show the Image --- """
plt.subplot(gs[0:2, 4:6])
plt.title('3. Contrast Adjusting')
plt.imshow(gray_correct, cmap="gray", vmin=0, vmax=255)
# Contrast adjusting with histogramm equalization
gray_equ = cv2.equalizeHist(gray_im)
""" --- Show the Image --- """
#plt.subplot(222)
#plt.title('Histogram equilization')
#plt.imshow(gray_correct, cmap="gray", vmin=0, vmax=255)
""" ---Processing--- """
# Local adaptive threshold
thresh = cv2.adaptiveThreshold(gray_correct, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 255, 19)
thresh = cv2.bitwise_not(thresh)
""" --- Show the Image --- """
plt.subplot(gs[3:5, 0:2])
plt.title('4. Local Adaptive Threshold')
plt.imshow(thresh, cmap="gray", vmin=0, vmax=255)
# Dilation & erosion
kernel = np.ones((15,15), np.uint8)
img_dilation = cv2.dilate(thresh, kernel, iterations=1)
img_erode = cv2.erode(img_dilation,kernel, iterations=1)
# clean all noise after dilatation and erosion
img_erode = cv2.medianBlur(img_erode, 7)
""" --- Show the Image --- """
plt.subplot(gs[3:5, 2:4])
plt.title('5. Dilation & erosion')
plt.imshow(img_erode, cmap="gray", vmin=0, vmax=255)
# Labeling
ret, labels = cv2.connectedComponents(img_erode)
label_hue = np.uint8(179 * labels / np.max(labels))
blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
labeled_img[label_hue == 0] = 0
""" --- Show the Image --- """
plt.subplot(gs[3:5, 4:6])
plt.title('6. Objects counted:'+ str(ret-1))
plt.imshow(labeled_img)
# Output
print('objects number is:', ret-1)
plt.show() |
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
## Abstact iterator class.
class Iterator(object):
def __init__(self, scene_node):
super(Iterator, self).__init__() # Call super to make multiple inheritence work.
self._scene_node = scene_node
self._node_stack = []
self._fillStack()
## Fills the list of nodes by a certain order. The strategy to do this is to be defined by the child.
def _fillStack(self):
raise NotImplementedError("Iterator is not correctly implemented. Requires a _fill_stack implementation.")
def __iter__(self):
return iter(self._node_stack) |
# -*- coding: utf-8 -*-
import logging
import hashlib
from django.conf import settings
from django.dispatch import Signal, receiver
from django.utils.timezone import now as tz_now
from django.utils.crypto import get_random_string
from .models import ImpersonationLog
logger = logging.getLogger(__name__)
# signal sent when an impersonation session begins
session_begin = Signal(
providing_args=['impersonator', 'impersonating', 'request']
)
# signal sent when an impersonation session ends
session_end = Signal(
providing_args=['impersonator', 'impersonating', 'request']
)
def gen_unique_id():
return hashlib.sha1(
u'{0}:{1}'.format(get_random_string(), tz_now()).encode('utf-8')
).hexdigest()
@receiver(session_begin, dispatch_uid='impersonate.signals.on_session_begin')
def on_session_begin(sender, **kwargs):
''' Create a new ImpersonationLog object.
'''
impersonator = kwargs.get('impersonator')
impersonating = kwargs.get('impersonating')
logger.info(u'{0} has started impersonating {1}.'.format(
impersonator,
impersonating,
))
if getattr(settings, 'IMPERSONATE_DISABLE_LOGGING', False):
return
request = kwargs.get('request')
session_key = gen_unique_id()
ImpersonationLog.objects.create(
impersonator=impersonator,
impersonating=impersonating,
session_key=session_key,
session_started_at=tz_now()
)
request.session['_impersonate_session_id'] = session_key
request.session.modified = True
@receiver(session_end, dispatch_uid='impersonate.signals.on_session_end')
def on_session_end(sender, **kwargs):
''' Update ImpersonationLog with the end timestamp.
This uses the combination of session_key, impersonator and
user being impersonated to look up the corresponding
impersonation log object.
'''
impersonator = kwargs.get('impersonator')
impersonating = kwargs.get('impersonating')
logger.info(u'{0} has finished impersonating {1}.'.format(
impersonator,
impersonating,
))
if getattr(settings, 'IMPERSONATE_DISABLE_LOGGING', False):
return
request = kwargs.get('request')
session_key = request.session.get('_impersonate_session_id', None)
try:
# look for unfinished sessions that match impersonator / subject
log = ImpersonationLog.objects.get(
impersonator=impersonator,
impersonating=impersonating,
session_key=session_key,
session_ended_at__isnull=True,
)
log.session_ended_at = tz_now()
log.save()
except ImpersonationLog.DoesNotExist:
logger.warning(
(u'Unfinished ImpersonationLog could not be found for: '
u'{0}, {1}, {2}').format(
impersonator,
impersonating,
session_key,
)
)
except ImpersonationLog.MultipleObjectsReturned:
logger.warning(
(u'Multiple unfinished ImpersonationLog matching: '
u'{0}, {1}, {2}').format(
impersonator,
impersonating,
session_key,
)
)
del request.session['_impersonate_session_id']
request.session.modified = True
|
import socket
import sys
import time
import os
import hashlib
FLAGS = None
class ClientSocket():
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.bind((FLAGS.ip, FLAGS.port))
self.buf = 1024
self.timeout = 3
def socket_send(self):
while True:
data, addr = self.socket.recvfrom(self.buf)
data_size, addr = self.socket.recvfrom(self.buf)
data_md, addr = self.socket.recvfrom(self.buf)
file_name = data.decode()
file_size = int(data_size.decode())
if data:
print("file_name:", data.decode())
print("file_size:", file_size)
print("file_md:", data_md.decode('utf-8'))
f = open(data.strip(), 'wb')
md5 = hashlib.md5()
i = 0
j = 0
while(i * self.buf <= file_size + 1023):
i = i + 1
data,addr = self.socket.recvfrom(self.buf)
hash_recv, addr = self.socket.recvfrom(self.buf)
f.write(data)
if(data):
hash_data = hashlib.md5(data).hexdigest()
md5.update(data)
hash_recv = hash_recv.decode(errors='replace').strip()
if(hash_recv == hash_data):
print(hash_data)
print(hash_recv)
print("same md5")
else:
print("error")
j = j +1
else:
break
get_percent = (self.buf * i / file_size * 100)
os.system('cls' if os.name == 'nt' else 'clear')
print('\r[{0}] {1}%'.format('#'*(int(get_percent/2)), get_percent))
print("current_size / total_size =", self.buf * i, "/", file_size)
print("Error rate : ", 100 - ((i - j ) / i) * 100, "%")
if(i * self.buf > file_size):
break
if(md5.hexdigest() == data_md.decode('utf-8')):
print("ok")
os.system('cls' if os.name == 'nt' else 'clear')
print('\r[{0}] {1}%'.format('#'*(int(get_percent/2)), 100))
print("current_size / total_size =", file_size , "/", file_size)
print("%s receive finished!" % file_name)
else:
print("Receive failed..")
print("Error rate : ", 100 - ((i - j ) / i) * 100, "%")
print("(send)md5: ", data_md.decode('utf-8'))
print("(recv)md5: ", md5.hexdigest())
f.close()
break;
def main(self):
self.socket_send()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--ip', type=str, default='127.0.0.1')
parser.add_argument('-p', '--port', type=int, default=1234)
FLAGS, _ = parser.parse_known_args()
client_socket = ClientSocket()
client_socket.main()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Implementation of https://arxiv.org/pdf/1512.03385.pdf.
# See section 4.2 for model architecture on CIFAR-10.
# Some part of the code was referenced below.
# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
import os
import torch
import torch.nn as nn
from torch.autograd import Variable
# Residual Block
class ResidualBlock(nn.Module):
def __init__(self, num_features=64, is_biased=True):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(num_features, num_features, kernel_size=3, stride=1, padding=1, bias=is_biased)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(num_features, num_features, kernel_size=3, stride=1, padding=1, bias=is_biased)
def forward(self, x):
out = self.conv1(x)
out = self.relu(out)
out = self.conv2(out)
out += x
return out
class SrResnet(nn.Module):
def __init__(self, in_channel=3, num_blocks=16, num_features=64, is_biased=True, init_state_path=None):
super(SrResnet, self).__init__()
self.conv1 = nn.Conv2d(in_channel, num_features, kernel_size=3, stride=1, padding=1, bias=is_biased)
self.relu1 = nn.ReLU(True)
self.blocks = self.make_blocks_(num_blocks)
self.conv2 = nn.Conv2d(num_features, num_features, kernel_size=3, stride=1, padding=1, bias=is_biased)
self.relu2 = nn.ReLU(True)
self.conv3 = nn.Conv2d(num_features, in_channel, kernel_size=3, stride=1, padding=1, bias=is_biased)
self.weights_init()
if init_state_path:
checkpoint = torch.load(init_state_path, map_location=lambda storage, loc: storage)
self.load_state_dict(checkpoint)
def make_blocks_(self, num):
layers = []
for i in range(num):
layers.append(ResidualBlock())
return nn.Sequential(*layers)
def forward(self, x, target=None):
# stage 1
conv1 = self.conv1(x)
relu1 = self.relu1(conv1)
# stage 2
blocks_out = self.blocks(relu1)
conv2 = self.conv2(blocks_out)
relu2 = self.relu2(conv2)
out2 = relu2 + relu1
out = self.conv3(out2)
if target is not None:
pairs = {'out': (out, target)}
return pairs, self.exports(x, out, target)
else:
return self.exports(x, out, target)
def exports(self, x, output, target):
result = {'input': x, 'output': output}
if target is not None:
result['target'] = target
return result
def weights_init(self):
for idx, m in enumerate(self.modules()):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('Linear') != -1:
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
|
import argparse
import os
from lazyme import color_print
import XmlParser
import gitAdressParser
## change these default variables as needed or use command line arguments ##############################################################################################################################
git_repo_address = 'git@st-gitlab:test/example.git' # The address to the git repo that you wish to move the files in SourceGear Vault to
gitDestination = "" # The name of the git repo. should be the last part of the git address minus the .git
vaultRepo = "TableHeat" # change just the name of the vault repo you wish to migrate to git
vaultFolder = "EX3Main" # change just the name of the vault folder you wish to migrate to git
vaultUser = "vpuser"
vaultPasswd = "archive"
vaultHost = "st-eng"
SourceGearLocation = "C:/Program Files (x86)/SourceGear/VaultPro Client " # The location of the SourceGear Client on your machine
auto_pusher = 0
gitIgnoreFile = ""
###################################################################################################################################################################
parser = argparse.ArgumentParser()
parser.add_argument("--user", "-u", help="Sourcegear Vault user\n")
parser.add_argument("--password", "-p", help="SourceGear Vault password\n")
parser.add_argument("--host", help="The host that your SourceGear Vault is located on (eq: localhost)")
parser.add_argument("--vaultrepo", "-vr", help="SourceGear Vault repo name (eq: RepoName)")
parser.add_argument("--vaultfolder", "-vf", help="SourceGear Vault folder name (eq: FolderName)")
parser.add_argument("--gitaddress", "-ga", help="The git repo address that you wish to migrate your SourceGear Vault repo to (eq: git@github.com:rapaportg/VaultToGit.git")
#parser.add_argument("--gitdestination", "-gd", help="The name of the git repo. should be the last part of the git address minus the .git")
parser.add_argument("--sourcegear_location","-sgl", help="The location of the SourceGear Client on your machine")
parser.add_argument("--auto_push", "-ap", help="set to 0 or 1 if you would like the git repo to automatically push")
parser.add_argument("--gitignore", "-gi", help= "input the path to your .gitignore file")
args = parser.parse_args()
if args.user:
vaultUser = args.user
if args.password:
vaultPasswd = args.password
if args.host:
vaultHost = args.host
if args.vaultrepo:
vaultRepo = args.vaultrepo
if args.vaultfolder:
vaultFolder = args.vaultfolder
if args.gitaddress:
git_repo_address = args.gitaddress
#if args.gitdestination:
#gitDestination = args.gitdestination
if args.sourcegear_location:
SourceGearLocation = args.sourcegear_location
if args.auto_push:
auto_pusher = args.auto_push
if args.gitignore:
gitIgnoreFile = args.gitignore
gitDestination = gitAdressParser.gitParser(git_repo_address)
# initalizing local git repo
os.system('cd /D C:\Temp && git clone ' + git_repo_address)
os.system('git config user.name "Vault"')
# creating .gitignore
gitpathcommand = 'cd /D C:\Temp\\' + gitDestination
#os.system(gitpathcommand + " && del .gitignore")
gitpath = "copy "+gitIgnoreFile+ " C:\Temp\\"+gitDestination
color_print(gitpath, color='red')
os.system("copy "+ gitIgnoreFile + " C:\Temp\\"+gitDestination)
# Grabing the Revision History to use as a guide for cloning each commit
credentials = " -host " + vaultHost + " -user " + vaultUser + " -password " + vaultPasswd
getRevHistory = "vault VERSIONHISTORY -rowlimit 0 " + credentials
beginVersion = " -beginversion 0 "
RevHistoryLocation = ' "C:/Temp/temp.xml"'
vaultFolder_full = " $/" + vaultFolder
getRevHistoryCommand = getRevHistory + " -repository " + vaultRepo + beginVersion + vaultFolder_full + " > " + RevHistoryLocation
color_print(getRevHistoryCommand, color='blue')
os.system("cd /D " + SourceGearLocation + "&& " + getRevHistoryCommand)
#os.system("cd /D"+ vault2git_script_location)
XmlParser.init()
comments = XmlParser.CommentA()
version = XmlParser.VersionA()
txid = XmlParser.TxidA()
objverid = XmlParser.ObjveridA()
date = XmlParser.DateA()
user = XmlParser.UserA()
gitDestination_full = " C:/Temp/" + gitDestination
# if the script fails part way through change startVersion to match the last know vault version to be committed to git.
# vault version are recorded at the beginning of the git commit messages
startVersion = 0
loopLength = len(version)
print('\n\nThere are ', loopLength, ' commits to migrate\n\n')
for x in range(startVersion, loopLength, 1):
commit_version = str(version[x])
commit_user = str(user[x])
commit_message = str(comments[x])
commit_txid = str(txid[x])
commit_objverid = str(objverid[x])
commit_date = str(date[x])
git_commit_msg = '"'+ commit_message + " " + 'Original Vault commit: version ' + commit_version + " on " + commit_date + "(txid="+commit_txid+')"'
if(commit_message == "None"):
git_commit_msg = '"Original Vault commit version ' + commit_version + " on " + commit_date + " (txid="+commit_txid+')"'
getRepoCommand = "vault GETVERSION" + credentials +" -repository " + vaultRepo +" "+ commit_version + vaultFolder_full +" " + gitDestination_full
color_print( getRepoCommand, color="pink")
color_print( git_commit_msg,color="yellow")
os.system("cd /D " + SourceGearLocation + " && " + getRepoCommand)
os.system("cd /D " + gitDestination_full + " && git add . ")
os.system("git branch --unset-upstream ")
git_user_email = commit_user+'@autobag.com'
git_commit = "cd /D " + gitDestination_full + " && "+ " git commit" + ' --author '+'"'+ commit_user + '<'+ git_user_email +'>"' +" --date=" + '"'+ commit_date +'" ' +" -m " + git_commit_msg
print('\n\n', git_commit, '\n\n')
os.system("git gc")
os.system(git_commit)
clearWorkingDir = "cd /D " + gitDestination_full + ' && git rm .'
os.system(clearWorkingDir)
if (auto_pusher == 1):
os.system("git push -u origin master")
else:
color_print("To push the git repository please go to the directory it is located in review the repo and push manually", color="green")
|
from django.conf.urls import url, include
from rest_framework import routers
from cumlaudeUcla import views
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
router = routers.DefaultRouter()
router.register(r'Estudiantes', views.EstudianteViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^admin/', admin.site.urls),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
] |
#!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Example of automatic vehicle control from client side.
"""
from __future__ import print_function
import argparse
import collections
import datetime
import glob
import logging
import math
import os
import random
import re
import sys
import weakref
from collections import deque
import numpy as np
import xlwt
import time
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_0
from pygame.locals import K_9
from pygame.locals import K_BACKQUOTE
from pygame.locals import K_BACKSPACE
from pygame.locals import K_COMMA
from pygame.locals import K_DOWN
from pygame.locals import K_ESCAPE
from pygame.locals import K_F1
from pygame.locals import K_LEFT
from pygame.locals import K_PERIOD
from pygame.locals import K_RIGHT
from pygame.locals import K_SLASH
from pygame.locals import K_SPACE
from pygame.locals import K_TAB
from pygame.locals import K_UP
from pygame.locals import K_a
from pygame.locals import K_c
from pygame.locals import K_d
from pygame.locals import K_h
from pygame.locals import K_m
from pygame.locals import K_p
from pygame.locals import K_q
from pygame.locals import K_r
from pygame.locals import K_s
from pygame.locals import K_w
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
try:
import numpy as np
except ImportError:
raise RuntimeError(
'cannot import numpy, make sure numpy package is installed')
# ==============================================================================
# -- find carla module ---------------------------------------------------------
# ==============================================================================
try:
sys.path.append(glob.glob('**/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
from carla import ColorConverter as cc
# from agents.navigation.agent import *
# from agents.navigation.roaming_agent import *
# from agents.navigation.basic_agent import *
from agents.tools.misc import distance_vehicle, get_speed
from agents.navigation.SpeedDistance_controller import SpeedDistance_VehiclePIDController
from agents.navigation.controller import VehiclePIDController
from agents.tools.misc import *
from enum import Enum
import networkx as nx
# ==============================================================================
# -- Global functions ----------------------------------------------------------
# ==============================================================================
def find_weather_presets():
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x))
presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]
return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]
def get_actor_display_name(actor, truncate=250):
name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
return (name[:truncate-1] + u'\u2026') if len(name) > truncate else name
# ==============================================================================
# -- TrafficDetector ---------------------------------------------------------------
# ==============================================================================
class TrafficDetector(object):
def __init__(self, vehicle, target_waypoint, sign_distance, vehicle_distance):
self._vehicle = vehicle
self._world = self._vehicle.get_world()
self._map = self._world.get_map()
self._last_traffic_light = None
self._lightslist = self._world.get_actors().filter("*traffic_light*")
self._vehiclelist = self._world.get_actors().filter("*vehicle*")
self._speedlimit_list = self._world.get_actors().filter("*speed_limit*")
self._sign_distance = sign_distance
self._vehicle_distance = vehicle_distance
self._target_waypoint = target_waypoint
self._last_us_traffic_light = None
self._lane_history = []
self._speedlimit_history = []
self._speedlimit_history.append("Init")
def record_lane_id(self):
vehicle = self._vehicle
current_map = self._map
speed_limit_list = self._speedlimit_list
ego_vehicle_location = vehicle.get_location()
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
self._lane_history.append(ego_vehicle_waypoint.lane_id)
def search_front_vehicle(self):
vehicle = self._vehicle
vehicle_list = self._vehiclelist
current_map = self._map
distance = self._vehicle_distance
ego_vehicle_location = vehicle.get_location()
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
for target_vehicle in vehicle_list:
# do not account for the ego vehicle
if target_vehicle.id == vehicle.id:
continue
# if the object is not in our lane it's not an obstacle
target_vehicle_waypoint = current_map.get_waypoint(target_vehicle.get_location())
if target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or \
target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
loc = target_vehicle.get_location()
if is_within_distance_ahead(loc,ego_vehicle_location,
vehicle.get_transform().rotation.yaw,distance):
# print (target_vehicle.id == vehicle_list[0])
return (True,target_vehicle)
return (False,None)
def search_rear_vehicle_left_lane(self):
vehicle = self._vehicle
vehicle_list = self._vehiclelist
current_map = self._map
distance = self._vehicle_distance
ego_vehicle_location = vehicle.get_location()
ego_vehicle_location.y = ego_vehicle_location.y -3.5
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
for target_vehicle in vehicle_list:
# do not account for the ego vehicle
if target_vehicle.id == vehicle.id:
continue
# if the object is not in our lane it's not an obstacle
target_vehicle_waypoint = current_map.get_waypoint(target_vehicle.get_location())
if target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or \
target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
loc = target_vehicle.get_location()
if is_within_distance_ahead(loc,ego_vehicle_location,
180.0 + vehicle.get_transform().rotation.yaw,50.0):
# print (target_vehicle.id == vehicle_list[0])
return (True,target_vehicle)
return (False,None)
def search_front_vehicle_left_lane(self):
vehicle = self._vehicle
vehicle_list = self._vehiclelist
current_map = self._map
distance = self._vehicle_distance
ego_vehicle_location = vehicle.get_location()
ego_vehicle_location.y = ego_vehicle_location.y -3.5
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
for target_vehicle in vehicle_list:
# do not account for the ego vehicle
if target_vehicle.id == vehicle.id:
continue
# if the object is not in our lane it's not an obstacle
target_vehicle_waypoint = current_map.get_waypoint(target_vehicle.get_location())
if target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or \
target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
loc = target_vehicle.get_location()
if is_within_distance_ahead(loc,ego_vehicle_location,
vehicle.get_transform().rotation.yaw,50.0):
# print (target_vehicle.id == vehicle_list[0])
return (True,target_vehicle)
return (False,None)
def search_rear_vehicle_right_lane(self):
vehicle = self._vehicle
vehicle_list = self._vehiclelist
current_map = self._map
distance = self._vehicle_distance
ego_vehicle_location = vehicle.get_location()
ego_vehicle_location.y = ego_vehicle_location.y +3.5
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
# shadow_location = carla.Location(x= ego_vehicle_location.x, y= ego_vehicle_location.y + 3.5, z= ego_vehicle_location.z)
# shadow_waypoint = self._map.get_waypoint(shadow_location)
for target_vehicle in vehicle_list:
# do not account for the ego vehicle
if target_vehicle.id == vehicle.id:
continue
# if the object is not in our lane it's not an obstacle
target_vehicle_waypoint = current_map.get_waypoint(target_vehicle.get_location())
if target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or \
target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
# print (target_vehicle)
loc = target_vehicle.get_location()
if is_within_distance_ahead(loc,ego_vehicle_location,
180.0 + vehicle.get_transform().rotation.yaw,50.0):
return (True,target_vehicle)
return (False,None)
def search_front_vehicle_right_lane(self):
vehicle = self._vehicle
vehicle_list = self._vehiclelist
current_map = self._map
distance = self._vehicle_distance
ego_vehicle_location = vehicle.get_location()
ego_vehicle_location.y = ego_vehicle_location.y +3.5
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
# shadow_location = carla.Location(x= ego_vehicle_location.x, y= ego_vehicle_location.y + 3.5, z= ego_vehicle_location.z)
# shadow_waypoint = self._map.get_waypoint(shadow_location)
for target_vehicle in vehicle_list:
# do not account for the ego vehicle
if target_vehicle.id == vehicle.id:
continue
# if the object is not in our lane it's not an obstacle
target_vehicle_waypoint = current_map.get_waypoint(target_vehicle.get_location())
if target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or \
target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
# print (target_vehicle)
loc = target_vehicle.get_location()
if is_within_distance_ahead(loc,ego_vehicle_location,
vehicle.get_transform().rotation.yaw,50.0):
return (True,target_vehicle)
return (False,None)
def define_hazard_vehicle(self):
vehicle = self._vehicle
vehicle_list = self._vehiclelist
current_map = self._map
ego_vehicle_location = vehicle.get_location()
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
for target_vehicle in vehicle_list:
# do not account for the ego vehicle
if target_vehicle.id == vehicle.id:
continue
# if the object is not in our lane it's not an obstacle
target_vehicle_waypoint = current_map.get_waypoint(target_vehicle.get_location())
if target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or \
target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
loc = target_vehicle.get_location()
if is_within_distance_ahead(loc,ego_vehicle_location,
vehicle.get_transform().rotation.yaw,15.0):
return (True,target_vehicle)
return (False,None)
def get_speed_limit(self):
"""
"""
vehicle = self._vehicle
current_map = self._map
speed_limit_list = self._speedlimit_list
ego_vehicle_location = vehicle.get_location()
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
# while Ture:
if len(self._speedlimit_history) > 4000:
last_value = self._speedlimit_history[-1]
self._speedlimit_history.pop(0)
self._speedlimit_history.append(last_value)
for speed_limit in speed_limit_list:
# print (len(speed_limit_list))
# speed_limit_history.append("a")
object_waypoint = current_map.get_waypoint(speed_limit.get_location())
if object_waypoint.road_id != ego_vehicle_waypoint.road_id or \
object_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
loc = speed_limit.get_location()
if is_within_distance_ahead(loc, ego_vehicle_location,
vehicle.get_transform().rotation.yaw,
20.0):
# if traffic_light.state == carla.libcarla.TrafficLightState.Red:
speed_limit_value = (str(speed_limit).split('.'))[-1]
speed_limit_value = speed_limit_value[0] + speed_limit_value[1]
# print (type(speed_limit_value))
self._speedlimit_history.append(speed_limit_value)
# print (speed_limit_value + str(len(speed_limit_history)))
return (self._speedlimit_history[-1])
# print (str(len(speed_limit_history)))
return (self._speedlimit_history[-1])
def is_light_red(self):
"""
Method to check if there is a red light affecting us. This version of
the method is compatible with both European and US style traffic lights.
:param lights_list: list containing TrafficLight objects
:return: a tuple given by (bool_flag, traffic_light), where
- bool_flag is True if there is a traffic light in RED
affecting us and False otherwise
- traffic_light is the object itself or None if there is no
red traffic light affecting us
"""
world = self._world
if world.map_name == 'Town01' or world.map_name == 'Town02':
return self._is_light_red_europe_style()
else:
return self._is_light_red_us_style()
def _is_light_red_europe_style(self):
"""
This method is specialized to check European style traffic lights.
:param lights_list: list containing TrafficLight objects
:return: a tuple given by (bool_flag, traffic_light), where
- bool_flag is True if there is a traffic light in RED
affecting us and False otherwise
- traffic_light is the object itself or None if there is no
red traffic light affecting us
"""
vehicle = self._vehicle
lights_list = self._lightslist
current_map = self._map
distance = self._sign_distance
ego_vehicle_location = vehicle.get_location()
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
for traffic_light in lights_list:
object_waypoint = current_map.get_waypoint(traffic_light.get_location())
if object_waypoint.road_id != ego_vehicle_waypoint.road_id or \
object_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
loc = traffic_light.get_location()
if is_within_distance_ahead(loc, ego_vehicle_location,
vehicle.get_transform().rotation.yaw,
distance):
if traffic_light.state == carla.libcarla.TrafficLightState.Red:
return (True, traffic_light)
return (False, None)
def _is_light_red_us_style(self):
"""
This method is specialized to check US style traffic lights.
:param lights_list: list containing TrafficLight objects
:return: a tuple given by (bool_flag, traffic_light), where
- bool_flag is True if there is a traffic light in RED
affecting us and False otherwise
- traffic_light is the object itself or None if there is no
red traffic light affecting us
"""
last_us_traffic_light = self._last_us_traffic_light
vehicle = self._vehicle
lights_list = self._lightslist
current_map = self._map
target_waypoint = self._target_waypoint
ego_vehicle_location = vehicle.get_location()
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
if ego_vehicle_waypoint.is_intersection:
# It is too late. Do not block the intersection! Keep going!
return (False, None)
if target_waypoint is not None:
suitable_waypoint = optimize_target_waypoint(current_map,target_waypoint,vehicle.get_transform().rotation.yaw)
if suitable_waypoint.is_intersection:
# if self._local_planner._target_waypoint.is_intersection:
# potential_lights = []
min_angle = 180.0
sel_magnitude = 0.0
sel_traffic_light = None
for traffic_light in lights_list:
loc = traffic_light.get_location()
magnitude, angle = compute_magnitude_angle(loc,
ego_vehicle_location,
vehicle.get_transform().rotation.yaw)
if magnitude < 80.0 and angle < min(25.0, min_angle):
# if magnitude < 280.0 and angle < 40.0:
sel_magnitude = magnitude
sel_traffic_light = traffic_light
min_angle = angle
if sel_traffic_light is not None:
print('=== Magnitude = {} | Angle = {} | ID = {} | Status = {}'.format(sel_magnitude, min_angle, sel_traffic_light.id, sel_traffic_light.state ))
if last_us_traffic_light is None:
last_us_traffic_light = sel_traffic_light
if last_us_traffic_light.state == carla.libcarla.TrafficLightState.Red:
return (True, last_us_traffic_light)
else:
last_us_traffic_light = None
return (False, None)
# ==============================================================================
# -- World ---------------------------------------------------------------
# ==============================================================================
class World(object):
def __init__(self, carla_world, hud):
self.world = carla_world
self.hud = hud
self.vehicle = None
self.collision_sensor = None
self.lane_invasion_sensor = None
self.camera_manager = None
self._weather_presets = find_weather_presets()
self._weather_index = 0
self.restart()
self.world.on_tick(hud.on_world_tick)
def restart(self):
# Keep same camera config if the camera manager exists.
cam_index = self.camera_manager._index if self.camera_manager is not None else 0
cam_pos_index = self.camera_manager._transform_index if self.camera_manager is not None else 0
# blueprint = random.choice(self.world.get_blueprint_library().filter('vehicle.tesla.*'))
blueprint = random.choice(self.world.get_blueprint_library().filter('vehicle.lincoln.mkz2017'))
# blueprint = random.choice(self.world.get_blueprint_library().filter('vehicle.bmw.grandtourer'))
blueprint.set_attribute('role_name', 'hero')
# blueprint.set_attribute('color', '120,0,0')
blueprint.set_attribute('color', '230,230,230')
# if blueprint.has_attribute('color'):
# color = random.choice(blueprint.get_attribute('color').recommended_values)
# blueprint.set_attribute('color', color)
# Spawn the vehicle.
if self.vehicle is not None:
spawn_point = self.vehicle.get_transform()
spawn_point.location.z += 2.0
spawn_point.rotation.roll = 0.0
spawn_point.rotation.pitch = 0.0
self.destroy()
spawn_points = self.world.get_map().get_spawn_points()
spawn_point = spawn_points[1]
self.vehicle = self.world.spawn_actor(blueprint, spawn_point)
while self.vehicle is None:
spawn_points = self.world.get_map().get_spawn_points()
# spawn_point = spawn_points[10]
spawn_point = random.choice(spawn_points)
# self.vehicle = self.world.spawn_actor(blueprint, spawn_point)
# support_actor = random.choice(self.world.get_actors().filter("*vehicle*"))
# support_actor_point = support_actor.get_transform()
# spawn_point = support_actor_point
# spawn_point.location.y = spawn_point.location.y - 10.0
# spawn_point = carla.Transform(carla.Location(x=373.40, y=-8.7, z=0.40), carla.Rotation(pitch=0, yaw=-181.00004, roll=0))
# Tesla spawn parameter
# spawn_point_1 = carla.Transform(carla.Location(x=-2.10 ,y=-135, z=0.80), carla.Rotation(pitch=0, yaw=90.0, roll=0))
spawn_point_2 = carla.Transform(carla.Location(x=-2420 ,y=12.25, z=0.40), carla.Rotation(pitch=0, yaw=0, roll=0))
spawn_point_3 = carla.Transform(carla.Location(x=2420 ,y=-8.25, z=0.40), carla.Rotation(pitch=0, yaw=180, roll=0))
# spawn_point.rotation.roll = 90.0
# spawn_point.rotation.pitch = 90.0
# spawn_point = carla.Transform (carla.Location(x=232,y=160,z=2),carla.Rotation(roll=0,pitch=0,yaw=180))
self.vehicle = self.world.try_spawn_actor(blueprint, spawn_point_2)
# Set up the sensors.
self.collision_sensor = CollisionSensor(self.vehicle, self.hud)
self.lane_invasion_sensor = LaneInvasionSensor(self.vehicle, self.hud)
self.camera_manager = CameraManager(self.vehicle, self.hud)
self.camera_manager._transform_index = cam_pos_index
self.camera_manager.set_sensor(cam_index, notify=False)
actor_type = get_actor_display_name(self.vehicle)
self.hud.notification(actor_type)
# def record(self,ve-
# global counter-
# name = str(get_actor_display_name(vehicle, truncate=20))
# velocity = vehicle.get_velocity()
# speed = 3.6 * math.sqrt(velocity.x**2 + velocity.y**2 + velocity.z**2)
# wb = xlwt.Workbook()
# sheet1 = wb.add_sheet(name)
# row = counter
# sheet1.write(row,0,'jajaja')
# wb.save('record_2.xlsx')
def next_weather(self, reverse=False):
self._weather_index += -1 if reverse else 1
self._weather_index %= len(self._weather_presets)
preset = self._weather_presets[self._weather_index]
self.hud.notification('Weather: %s' % preset[1])
self.vehicle.get_world().set_weather(preset[0])
def tick(self, clock):
self.hud.tick(self, clock)
def render(self, display):
self.camera_manager.render(display)
self.hud.render(display)
def destroy(self):
actors = [
self.camera_manager.sensor,
self.collision_sensor.sensor,
self.lane_invasion_sensor.sensor,
self.vehicle]
for actor in actors:
if actor is not None:
actor.destroy()
# ==============================================================================
# -- KeyboardControl -----------------------------------------------------------
# ==============================================================================
class KeyboardControl(object):
def __init__(self, world, start_in_autopilot):
self._autopilot_enabled = start_in_autopilot
self._control = carla.VehicleControl()
self._steer_cache = 0.0
world.vehicle.set_autopilot(self._autopilot_enabled)
world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
def parse_events(self, world, clock):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
elif event.type == pygame.KEYUP:
if self._is_quit_shortcut(event.key):
return True
elif event.key == K_BACKSPACE:
world.restart()
elif event.key == K_F1:
world.hud.toggle_info()
elif event.key == K_h or (event.key == K_SLASH and pygame.key.get_mods() & KMOD_SHIFT):
world.hud.help.toggle()
elif event.key == K_TAB:
world.camera_manager.toggle_camera()
elif event.key == K_c and pygame.key.get_mods() & KMOD_SHIFT:
world.next_weather(reverse=True)
elif event.key == K_c:
world.next_weather()
elif event.key == K_BACKQUOTE:
world.camera_manager.next_sensor()
elif event.key > K_0 and event.key <= K_9:
world.camera_manager.set_sensor(event.key - 1 - K_0)
elif event.key == K_r:
world.camera_manager.toggle_recording()
elif event.key == K_q:
self._control.gear = 1 if self._control.reverse else -1
elif event.key == K_m:
self._control.manual_gear_shift = not self._control.manual_gear_shift
self._control.gear = world.vehicle.get_vehicle_control().gear
world.hud.notification(
'%s Transmission' % ('Manual' if self._control.manual_gear_shift else 'Automatic'))
elif self._control.manual_gear_shift and event.key == K_COMMA:
self._control.gear = max(-1, self._control.gear - 1)
elif self._control.manual_gear_shift and event.key == K_PERIOD:
self._control.gear = self._control.gear + 1
elif event.key == K_p:
self._autopilot_enabled = not self._autopilot_enabled
world.vehicle.set_autopilot(self._autopilot_enabled)
world.hud.notification('Autopilot %s' % ('On' if self._autopilot_enabled else 'Off'))
if not self._autopilot_enabled:
self._parse_keys(pygame.key.get_pressed(), clock.get_time())
self._control.reverse = self._control.gear < 0
def _parse_keys(self, keys, milliseconds):
self._control.throttle = 1.0 if keys[K_UP] or keys[K_w] else 0.0
steer_increment = 5e-4 * milliseconds
if keys[K_LEFT] or keys[K_a]:
self._steer_cache -= steer_increment
elif keys[K_RIGHT] or keys[K_d]:
self._steer_cache += steer_increment
else:
self._steer_cache = 0.0
self._steer_cache = min(0.7, max(-0.7, self._steer_cache))
self._control.steer = round(self._steer_cache, 1)
self._control.brake = 1.0 if keys[K_DOWN] or keys[K_s] else 0.0
self._control.hand_brake = keys[K_SPACE]
@staticmethod
def _is_quit_shortcut(key):
return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)
# ==============================================================================
# -- ACC_Controller -----------------------------------------------------------
# ==============================================================================
class RoadOption(Enum):
"""
RoadOption represents the possible topological configurations when moving from a segment of lane to other.
"""
VOID = -1
LEFT = 1
RIGHT = 2
STRAIGHT = 3
LANEFOLLOW = 4
class ACC_Controller(object):
MIN_DISTANCE_PERCENTAGE = 0.9
def __init__(self,vehicle, opt_dict={}):
self._vehicle = vehicle
self._world = self._vehicle.get_world()
self._map = self._world.get_map()
self._last_us_traffic_light = None
self._dt = None
self._target_speed = None
self._sampling_radius = None
self._min_distance = None
self._current_waypoint = None
self._target_road_option = None
self._next_waypoints = None
self._target_waypoint = None
self._SpeedDistance_vehicle_controller = None
self._Speed_vehicle_controller = None
self._current_plan = None
self._global_plan = None
self._trigger_counter = 0
self._traffic_detector = TrafficDetector(self._vehicle,self._target_waypoint,12.5,140.0)
self._lane_id = self._map.get_waypoint(self._vehicle.get_location()).lane_id
# queue with tupltarget_vehicle_waypoints of (waypoint, RoadOption)
self._hop_resolution = 2.0
self._waypoints_queue = deque(maxlen=600)
self._buffer_size = 5
self._waypoint_buffer = deque(maxlen=self._buffer_size)
# this is for the traffic detector
self._lightslist = self._world.get_actors().filter("*traffic_light*")
self._vehiclelist = self._world.get_actors().filter("*vehicle*")
# SETTING controller
self.preset_speed = 60.0
self._target_distance = 10.0
self.initialize_PID_controller(opt_dict)
# Initialize the overtake parameters
self._overtake_intention = False
self._overtake_leftchange = False
self._overtake_rightchange = False
self._front_overtake_target = None
self._rear_overtake_target = None
self._overtake_done = False
self._first_move_done = False
def refresh_traffic_detector(self):
self._traffic_detector._target_waypoint = self._target_waypoint
def set_sampling_radius(self):
if get_speed(self._vehicle) <= 15.0:
return 2.0 # 0.5 seconds horizon
elif get_speed(self._vehicle)>15.0 and get_speed(self._vehicle) <= 45.0:
return get_speed(self._vehicle) * 0.5 / 3.8 # 0.5 seconds horizon
elif get_speed(self._vehicle) > 45.0 and get_speed(self._vehicle) <= 65.0:
return get_speed(self._vehicle) * 0.5 / 3.2
elif get_speed(self._vehicle) > 65.0:
return 12.0
def emergency_brake_situation(self):
emergency_1 = False
# emergency_2 = False
hazard_vehicle_state, hazard_vehicle = self._traffic_detector.define_hazard_vehicle()
# light_state, traffic_light = self._traffic_detector.is_light_red()
if hazard_vehicle_state:
if get_speed(hazard_vehicle) <= 0.30 * get_speed(self._vehicle) or get_speed(hazard_vehicle) < 5.0:
emergency_1 = True
if emergency_1 is True:
return True
return False
def set_target_speed(self):
vehicle_state, front_vehicle = self._traffic_detector.search_front_vehicle()
if vehicle_state:
if (get_speed(front_vehicle) < self.preset_speed * 0.85) and (self.emergency_brake_situation() is False):
self._front_overtake_target = front_vehicle
self._overtake_intention = True
return self.preset_speed * 0.65
return get_speed(front_vehicle)
return self.preset_speed
def set_target_distance(self):
front_vehicle_state, front_vehicle = self._traffic_detector.search_front_vehicle()
t0=1.5
Cv=0.05
Ca=0.3
th_max=1.6
th_min=0.2
delta_t = 0.0
if front_vehicle_state:
# ego_x = self._vehicle.get_location().x
# ego_y = self._vehicle.get_location().y
# front_x = front_vehicle.get_location().x
# front_y = front_vehicle.get_location().y
# dx = ego_x - front_x
# dy = ego_y - front_y
# init_distance = math.sqrt(dx * dx + dy * dy)
RelaSpeed = (get_speed(front_vehicle) - get_speed(self._vehicle)) / 3.6
# print("RelaSpeed",RelaSpeed)
ap = front_vehicle.get_acceleration()
front_acceleration = math.sqrt(ap.x**2+ap.y**2+ap.z**2)
th = t0 - Cv * RelaSpeed - Ca * front_acceleration
if th >= th_max:
delta_t = th_max
elif th > th_min and th < th_max:
delta_t = th
else:
delta_t = th_min
return delta_t * (get_speed(self._vehicle) / 3.6) + 15.0
# print("self._target_distance",self._target_distance)
# return self._target_distance
def left_lane_change(self):
self._waypoints_queue.clear()
new_waypoint = self._map.get_waypoint(carla.Location(self._vehicle.get_location().x + 70.0,
self._vehicle.get_location().y - 3.5,
self._vehicle.get_location().z))
self._waypoints_queue.append((new_waypoint, RoadOption.LANEFOLLOW))
pass
def right_lane_change(self):
self._waypoints_queue.clear()
new_waypoint = self._map.get_waypoint(carla.Location(self._vehicle.get_location().x + 70.0,
self._vehicle.get_location().y + 3.5,
self._vehicle.get_location().z))
self._waypoints_queue.append((new_waypoint, RoadOption.LANEFOLLOW))
pass
def refresh_overtake_target(self):
threshold = 150.0
vehicle = self._vehicle
vehicle_list = self._vehiclelist
current_map = self._map
ego_vehicle_location = vehicle.get_location()
ego_vehicle_location.y = ego_vehicle_location.y +3.5
ego_vehicle_waypoint = current_map.get_waypoint(ego_vehicle_location)
cars_right_lane = []
overtake_target = None
for target_vehicle in vehicle_list:
# do not account for the ego vehicle
if target_vehicle.id == vehicle.id:
continue
# if the object is not in our lane it's not an obstacle
target_vehicle_waypoint = current_map.get_waypoint(target_vehicle.get_location())
if target_vehicle_waypoint.road_id != ego_vehicle_waypoint.road_id or \
target_vehicle_waypoint.lane_id != ego_vehicle_waypoint.lane_id:
continue
cars_right_lane.append(target_vehicle)
if len(cars_right_lane) != 0:
for car in cars_right_lane:
distance = self._vehicle.get_location().x - car.get_location().x
if distance <= threshold and distance > 0.0:
threshold = distance
overtake_target = target_vehicle
if overtake_target is not None:
return (True,overtake_target)
else:
return (False, None)
return (False,None)
def decide_on_overtake(self):
rear_right_vehicle_state, rear_vehicle_right_lane = self._traffic_detector.search_rear_vehicle_right_lane()
rear_left_vehicle_state, rear_vehicle_left_lane = self._traffic_detector.search_rear_vehicle_left_lane()
front_right_vehicle_state, front_vehicle_right_lane = self._traffic_detector.search_front_vehicle_right_lane()
front_left_vehicle_state, front_vehicle_left_lane = self._traffic_detector.search_front_vehicle_left_lane()
if self._overtake_intention is True:
# print (self._front_overtake_target is not None)
threshold_distance = 0.0
if self._front_overtake_target is not None and self._overtake_leftchange is False and self._overtake_rightchange is False and \
rear_left_vehicle_state is False and front_left_vehicle_state is False and self._overtake_done is False:
self.left_lane_change()
self._overtake_leftchange= True
if self._overtake_leftchange is True and self._first_move_done is False and self._overtake_rightchange is False and self._overtake_done is False:
if self._map.get_waypoint(self._vehicle.get_location()).lane_id == self._lane_id + 1:
self._front_overtake_target = None
self._first_move_done = True
print ("I reach frist move")
self._lane_id = self._map.get_waypoint(self._vehicle.get_location()).lane_id
if self._first_move_done is True and self._overtake_rightchange is False and self._overtake_done is False:
_ , self._rear_overtake_target = self.refresh_overtake_target()
threshold_distance = self._vehicle.get_location().x - self._rear_overtake_target.get_location().x if self._rear_overtake_target is not None else 0.0
# print (threshold_distance)
if self._rear_overtake_target is not None:
if (self._first_move_done is True and threshold_distance >= 20.0 and self._overtake_leftchange is True \
and self._overtake_rightchange is False and self._overtake_done is False ):
self.right_lane_change()
self._overtake_rightchange = True
print ("I reach second move")
else:
if (self._first_move_done is True and rear_right_vehicle_state is False and self._overtake_leftchange is True and \
self._overtake_rightchange is False and front_right_vehicle_state is False and \
rear_right_vehicle_state is False and self._overtake_done is False):
self.right_lane_change()
self._overtake_rightchange = True
print ("I reach second move")
if self._first_move_done is True and self._overtake_rightchange is True and self._overtake_done is False:
if self._map.get_waypoint(self._vehicle.get_location()).lane_id == self._lane_id - 1:
self._lane_id = self._map.get_waypoint(self._vehicle.get_location()).lane_id
self._overtake_done = True
if self._first_move_done is True and self._overtake_rightchange is True and self._overtake_done is True:
self._overtake_intention = False
self._front_overtake_target = None
self._rear_overtake_target = None
self._overtake_leftchange = False
self._overtake_rightchange = False
self._overtake_done = False
self._first_move_done = False
pass
def emergency_stop(self):
control = carla.VehicleControl()
control.steer = 0.0
control.throttle = 0.0
control.brake = 1.0
control.hand_brake = False
return control
def initialize_PID_controller(self, opt_dict):
self._dt = 1.0 / 20.0
self._target_speed = self.preset_speed # Km/h
self._sampling_radius = 4.0
# self._sampling_radius = self._target_speed * 0.5 / 2.8 # 0.5 seconds horizon
self._min_distance = self._sampling_radius * self.MIN_DISTANCE_PERCENTAGE
# vehicle_state, front_vehicle = self._traffic_detector.search_front_vehicle()
args_lateral_dict = {
'K_P': 1.1,
'K_D': 0.0001,
'K_I': 1.2,
'dt': self._dt}
SpeedDistance_args_longitudinal_dict = {
'K_Pv': 0.4,
'K_Dv': 0.01,
'K_Iv':0.2,
'K_Pd': -0.05,
'K_Dd': 0.0,
'K_Id': -0.02,
'dt': self._dt}
Speed_args_longitudinal_dict = {
'K_P': 1.1,
'K_D': 0.02,
'K_I':1.0,
'dt': self._dt}
if 'dt' in opt_dict:
self._dt = opt_dict['dt']
if 'target_speed' in opt_dict:
self._target_speed = opt_dict['target_speed']
if 'sampling_radius' in opt_dict:
self._sampling_radius = self._target_speed * \
opt_dict['sampling_radius'] / 3.6
if 'lateral_control_dict' in opt_dict:
args_lateral_dict = opt_dict['lateral_control_dict']
if ' Speed_longitudinal_control_dict' in opt_dict:
Speed_args_longitudinal_dict = opt_dict['longitudinal_control_dict']
if ' SpeedDistance_longitudinal_control_dict' in opt_dict:
SpeedDistance_args_longitudinal_dict = opt_dict['SpeedDistance_longitudinal_control_dict']
self._current_waypoint = self._map.get_waypoint(
self._vehicle.get_location())
self._SpeedDistance_vehicle_controller = SpeedDistance_VehiclePIDController(self._vehicle,None,
args_lateral=args_lateral_dict,
args_longitudinal= SpeedDistance_args_longitudinal_dict)
self._Speed_vehicle_controller = VehiclePIDController(self._vehicle,
args_lateral=args_lateral_dict,
args_longitudinal= Speed_args_longitudinal_dict)
self._global_plan = False
# compute initial waypoints
self._waypoints_queue.append( (self._current_waypoint.next(self._sampling_radius)[0], RoadOption.LANEFOLLOW))
self._target_road_option = RoadOption.LANEFOLLOW
# fill waypoint trajectory queue
self._compute_next_waypoints(k=100)
def _compute_next_waypoints(self, k=1):
"""
Add new waypoints to the trajectory queue.
Calculate each waypoint in the path and work out the corresponding operation.
:param k: how many waypoints to compute
:return:
"""
# check we do not overflow the queue
available_entries = self._waypoints_queue.maxlen - len(self._waypoints_queue)
k = min(available_entries, k)
for _ in range(k):
last_waypoint = self._waypoints_queue[-1][0]
next_waypoints = list(last_waypoint.next(self._sampling_radius))
if len(next_waypoints) == 1:
# only one option available ==> lanefollowing
next_waypoint = next_waypoints[0]
road_option = RoadOption.LANEFOLLOW
else:
# random choice between the possible options
road_options_list = retrieve_options(
next_waypoints, last_waypoint)
road_option = random.choice(road_options_list)
next_waypoint = next_waypoints[road_options_list.index(
road_option)]
# print (road_option)
self._waypoints_queue.append((next_waypoint, road_option))
# print (str(self._waypoints_queue[1].name))
def run_step(self, debug=True):
"""
Execute one step of local planning which involves running the longitudinal and lateral PID controllers to
follow the waypoints trajectory.
:param debug: boolean flag to activate waypoints debugging
:return:
"""
# self._traffic_detector.search_rear_vehicle_right_lane()
self.refresh_traffic_detector()
# print (self._overtake_intention)
# if len(self._SpeedDistance_vehicle_controller._lon_controller._ed_buffer) > 0:
# print (self._SpeedDistance_vehicle_controller._lon_controller._ed_buffer[-1])
# not enough waypoints in the horizon? => add more!
if len(self._waypoints_queue) < int(self._waypoints_queue.maxlen * 0.5):
if not self._global_plan:
self._compute_next_waypoints(k=50)
if len(self._waypoints_queue) == 0:
control = carla.VehicleControl()
control.steer = 0.0
control.throttle = 0.0
control.brake = 0.0
control.hand_brake = False
control.manual_gear_shift = False
return control
# Buffering the waypoints
if not self._waypoint_buffer:
for i in range(self._buffer_size):
if self._waypoints_queue:
self._waypoint_buffer.append(
self._waypoints_queue.popleft())
else:
break
self._sampling_radius = self.set_sampling_radius()
self._traffic_detector.get_speed_limit()
# current vehicle waypoint
self._current_waypoint = self._map.get_waypoint(self._vehicle.get_location())
# target waypoint
vehicle_state, front_vehicle = self._traffic_detector.search_front_vehicle()
# refresh the target speed and target distance for PID controller.
self._target_speed = self.set_target_speed()
# print ("target distance is " + str(self._target_distance))
self._target_waypoint, self._target_road_option = self._waypoint_buffer[0]
# print (self._overtake_intention)
if self.emergency_brake_situation() is False:
if self._overtake_intention is False:
if vehicle_state:
self._target_distance = self.set_target_distance() - 20.0
self._SpeedDistance_vehicle_controller._lon_controller._front_vehicle = front_vehicle
# print ("I am using speed-distance PID.")
control = self._SpeedDistance_vehicle_controller.run_step(self._target_speed,self._target_distance, self._target_waypoint)
else:
control = self._Speed_vehicle_controller.run_step(self._target_speed, self._target_waypoint)
# print ("I am using speed PID.")
else:
self.decide_on_overtake()
control = self._Speed_vehicle_controller.run_step(self.preset_speed, self._target_waypoint)
else:
control = self.emergency_stop()
# purge the queue of obsolete waypoints
vehicle_transform = self._vehicle.get_transform()
max_index = -1
for i, (waypoint, _) in enumerate(self._waypoint_buffer):
if distance_vehicle(
waypoint, vehicle_transform) < self._min_distance:
max_index = i
if max_index >= 0:
for i in range(max_index + 1):
self._waypoint_buffer.popleft()
if debug:
draw_waypoints(self._vehicle.get_world(), [self._target_waypoint], self._vehicle.get_location().z + 1.0)
return control
def retrieve_options(list_waypoints, current_waypoint):
"""
Compute the type of connection between the current active waypoint and the multiple waypoints present in
list_waypoints. The result is encoded as a list of RoadOption enums.
:param list_waypoints: list with the possible target waypoints in case of multiple options
:param current_waypoint: current active waypoint
:return: list of RoadOption enums representing the type of connection from the active waypoint to each
candidate in list_waypoints
"""
options = []
for next_waypoint in list_waypoints:
# this is needed because something we are linking to
# the beggining of an intersection, therefore the
# variation in angle is small
next_next_waypoint = next_waypoint.next(3.0)[0]
link = compute_connection(current_waypoint, next_next_waypoint)
options.append(link)
return options
def compute_connection(current_waypoint, next_waypoint):
"""
Compute the type of topological connection between an active waypoint (current_waypoint) and a target waypoint
(next_waypoint).
:param current_waypoint: active waypoint
:param next_waypoint: target waypoint
:return: the type of topological connection encoded as a RoadOption enum:
RoadOption.STRAIGHT
RoadOption.LEFT
RoadOption.RIGHT
"""
n = next_waypoint.transform.rotation.yaw
n = n % 360.0
c = current_waypoint.transform.rotation.yaw
c = c % 360.0
diff_angle = (n - c) % 180.0
if diff_angle < 1.0:
return RoadOption.STRAIGHT
elif diff_angle > 90.0:
return RoadOption.LEFT
else:
return RoadOption.RIGHT
# ==============================================================================
# -- HUD -----------------------------------------------------------------
# ==============================================================================
class HUD(object):
def __init__(self, width, height):
self.dim = (width, height)
font = pygame.font.Font(pygame.font.get_default_font(), 20)
fonts = [x for x in pygame.font.get_fonts() if 'mono' in x]
default_font = 'ubuntumono'
mono = default_font if default_font in fonts else fonts[0]
mono = pygame.font.match_font(mono)
self._font_mono = pygame.font.Font(mono, 14)
self._notifications = FadingText(font, (width, 40), (0, height - 40))
self.help = HelpText(pygame.font.Font(mono, 24), width, height)
self.server_fps = 0
self.frame_number = 0
self.simulation_time = 0
self._show_info = True
self._info_text = []
self._server_clock = pygame.time.Clock()
def on_world_tick(self, timestamp):
self._server_clock.tick()
self.server_fps = self._server_clock.get_fps()
self.frame_number = timestamp.frame_count
self.simulation_time = timestamp.elapsed_seconds
def tick(self, world, clock):
if not self._show_info:
return
t = world.vehicle.get_transform()
v = world.vehicle.get_velocity()
c = world.vehicle.get_vehicle_control()
heading = 'N' if abs(t.rotation.yaw) < 89.5 else ''
heading += 'S' if abs(t.rotation.yaw) > 90.5 else ''
heading += 'E' if 179.5 > t.rotation.yaw > 0.5 else ''
heading += 'W' if -0.5 > t.rotation.yaw > -179.5 else ''
colhist = world.collision_sensor.get_collision_history()
collision = [colhist[x + self.frame_number - 200] for x in range(0, 200)]
max_col = max(1.0, max(collision))
collision = [x / max_col for x in collision]
vehicles = world.world.get_actors().filter('vehicle.*')
self._info_text = [
'Server: % 16d FPS' % self.server_fps,
'',
'Vehicle: % 20s' % get_actor_display_name(world.vehicle, truncate=20),
'Map: % 20s' % world.world.map_name,
'Simulation time: % 12s' % datetime.timedelta(seconds=int(self.simulation_time)),
'',
'Speed: % 15.0f km/h' % (3.6 * math.sqrt(v.x**2 + v.y**2 + v.z**2)),
u'Heading:% 16.0f\N{DEGREE SIGN} % 2s' % (t.rotation.yaw, heading),
'Location:% 20s' % ('(% 5.1f, % 5.1f)' % (t.location.x, t.location.y)),
'Height: % 18.0f m' % t.location.z,
'Traffic_lights: % 16d FPS' % self.server_fps,
'',
'',
('Throttle:', c.throttle, 0.0, 1.0),
('Steer:', c.steer, -1.0, 1.0),
('Brake:', c.brake, 0.0, 1.0),
('Reverse:', c.reverse),
('Hand brake:', c.hand_brake),
('Manual:', c.manual_gear_shift),
'Gear: %s' % {-1: 'R', 0: 'N'}.get(c.gear, c.gear),
'',
'Collision:',
collision,
'',
'Number of vehicles: % 8d' % len(vehicles)
]
if len(vehicles) > 1:
self._info_text += ['Nearby vehicles:']
distance = lambda l: math.sqrt((l.x - t.location.x)**2 + (l.y - t.location.y)**2 + (l.z - t.location.z)**2)
vehicles = [(distance(x.get_location()), x) for x in vehicles if x.id != world.vehicle.id]
for d, vehicle in sorted(vehicles):
if d > 200.0:
break
vehicle_type = get_actor_display_name(vehicle, truncate=22)
self._info_text.append('% 4dm %s' % (d, vehicle_type))
self._notifications.tick(world, clock)
def toggle_info(self):
self._show_info = not self._show_info
def notification(self, text, seconds=2.0):
self._notifications.set_text(text, seconds=seconds)
def error(self, text):
self._notifications.set_text('Error: %s' % text, (255, 0, 0))
def render(self, display):
if self._show_info:
info_surface = pygame.Surface((220, self.dim[1]))
info_surface.set_alpha(100)
display.blit(info_surface, (0, 0))
v_offset = 4
bar_h_offset = 100
bar_width = 106
for item in self._info_text:
if v_offset + 18 > self.dim[1]:
break
if isinstance(item, list):
if len(item) > 1:
points = [(x + 8, v_offset + 8 + (1.0 - y) * 30) for x, y in enumerate(item)]
pygame.draw.lines(display, (255, 136, 0), False, points, 2)
item = None
v_offset += 18
elif isinstance(item, tuple):
if isinstance(item[1], bool):
rect = pygame.Rect((bar_h_offset, v_offset + 8), (6, 6))
pygame.draw.rect(display, (255, 255, 255), rect, 0 if item[1] else 1)
else:
rect_border = pygame.Rect((bar_h_offset, v_offset + 8), (bar_width, 6))
pygame.draw.rect(display, (255, 255, 255), rect_border, 1)
f = (item[1] - item[2]) / (item[3] - item[2])
if item[2] < 0.0:
rect = pygame.Rect((bar_h_offset + f * (bar_width - 6), v_offset + 8), (6, 6))
else:
rect = pygame.Rect((bar_h_offset, v_offset + 8), (f * bar_width, 6))
pygame.draw.rect(display, (255, 255, 255), rect)
item = item[0]
if item: # At this point has to be a str.
surface = self._font_mono.render(item, True, (255, 255, 255))
display.blit(surface, (8, v_offset))
v_offset += 18
self._notifications.render(display)
self.help.render(display)
# ==============================================================================
# -- FadingText ----------------------------------------------------------------
# ==============================================================================
class FadingText(object):
def __init__(self, font, dim, pos):
self.font = font
self.dim = dim
self.pos = pos
self.seconds_left = 0
self.surface = pygame.Surface(self.dim)
def set_text(self, text, color=(255, 255, 255), seconds=2.0):
text_texture = self.font.render(text, True, color)
self.surface = pygame.Surface(self.dim)
self.seconds_left = seconds
self.surface.fill((0, 0, 0, 0))
self.surface.blit(text_texture, (10, 11))
def tick(self, _, clock):
delta_seconds = 1e-3 * clock.get_time()
self.seconds_left = max(0.0, self.seconds_left - delta_seconds)
self.surface.set_alpha(500.0 * self.seconds_left)
def render(self, display):
display.blit(self.surface, self.pos)
# ==============================================================================
# -- HelpText ------------------------------------------------------------------
# ==============================================================================
class HelpText(object):
def __init__(self, font, width, height):
lines = __doc__.split('\n')
self.font = font
self.dim = (680, len(lines) * 22 + 12)
self.pos = (0.5 * width - 0.5 * self.dim[0], 0.5 * height - 0.5 * self.dim[1])
self.seconds_left = 0
self.surface = pygame.Surface(self.dim)
self.surface.fill((0, 0, 0, 0))
for n, line in enumerate(lines):
text_texture = self.font.render(line, True, (255, 255, 255))
self.surface.blit(text_texture, (22, n * 22))
self._render = False
self.surface.set_alpha(220)
def toggle(self):
self._render = not self._render
def render(self, display):
if self._render:
display.blit(self.surface, self.pos)
# ==============================================================================
# -- CollisionSensor -----------------------------------------------------------
# ==============================================================================
class CollisionSensor(object):
def __init__(self, parent_actor, hud):
self.sensor = None
self._history = []
self._parent = parent_actor
self._hud = hud
world = self._parent.get_world()
bp = world.get_blueprint_library().find('sensor.other.collision')
self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid circular
# reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event))
def get_collision_history(self):
history = collections.defaultdict(int)
for frame, intensity in self._history:
history[frame] += intensity
return history
@staticmethod
def _on_collision(weak_self, event):
self = weak_self()
if not self:
return
actor_type = get_actor_display_name(event.other_actor)
self._hud.notification('Collision with %r, id = %d' % (actor_type, event.other_actor.id))
impulse = event.normal_impulse
intensity = math.sqrt(impulse.x ** 2 + impulse.y ** 2 + impulse.z ** 2)
self._history.append((event.frame_number, intensity))
if len(self._history) > 4000:
self._history.pop(0)
# ==============================================================================
# -- LaneInvasionSensor --------------------------------------------------------
# ==============================================================================
class LaneInvasionSensor(object):
def __init__(self, parent_actor, hud):
self.sensor = None
self._parent = parent_actor
self._hud = hud
world = self._parent.get_world()
bp = world.get_blueprint_library().find('sensor.other.lane_detector')
self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid circular
# reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: LaneInvasionSensor._on_invasion(weak_self, event))
@staticmethod
def _on_invasion(weak_self, event):
self = weak_self()
if not self:
return
text = ['%r' % str(x).split()[-1] for x in set(event.crossed_lane_markings)]
self._hud.notification('Crossed line %s' % ' and '.join(text))
# ==============================================================================
# -- CameraManager -------------------------------------------------------------
# ==============================================================================
class CameraManager(object):
def __init__(self, parent_actor, hud):
self.sensor = None
self._surface = None
self._parent = parent_actor
self._hud = hud
self._recording = False
self._camera_transforms = [
# carla.Transform(carla.Location(x=0.1,y=-0.3, z=1.2), carla.Rotation(pitch=-15)),
carla.Transform(carla.Location(x=-5.5, z=2.8), carla.Rotation(pitch=-15)),
carla.Transform(carla.Location(x=1.6, z=1.7))]
self._transform_index = 1
self._sensors = [
['sensor.camera.rgb', cc.Raw, 'Camera RGB'],
['sensor.camera.depth', cc.Raw, 'Camera Depth (Raw)'],
['sensor.camera.depth', cc.Depth, 'Camera Depth (Gray Scale)'],
['sensor.camera.depth', cc.LogarithmicDepth, 'Camera Depth (Logarithmic Gray Scale)'],
['sensor.camera.semantic_segmentation', cc.Raw, 'Camera Semantic Segmentation (Raw)'],
['sensor.camera.semantic_segmentation', cc.CityScapesPalette,
'Camera Semantic Segmentation (CityScapes Palette)'],
['sensor.lidar.ray_cast', None, 'Lidar (Ray-Cast)']]
world = self._parent.get_world()
bp_library = world.get_blueprint_library()
for item in self._sensors:
bp = bp_library.find(item[0])
if item[0].startswith('sensor.camera'):
bp.set_attribute('image_size_x', str(hud.dim[0]))
bp.set_attribute('image_size_y', str(hud.dim[1]))
item.append(bp)
self._index = None
def toggle_camera(self):
self._transform_index = (self._transform_index + 1) % len(self._camera_transforms)
self.sensor.set_transform(self._camera_transforms[self._transform_index])
def set_sensor(self, index, notify=True):
index = index % len(self._sensors)
needs_respawn = True if self._index is None \
else self._sensors[index][0] != self._sensors[self._index][0]
if needs_respawn:
if self.sensor is not None:
self.sensor.destroy()
self._surface = None
self.sensor = self._parent.get_world().spawn_actor(
self._sensors[index][-1],
self._camera_transforms[self._transform_index],
attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid
# circular reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda image: CameraManager._parse_image(weak_self, image))
if notify:
self._hud.notification(self._sensors[index][2])
self._index = index
def next_sensor(self):
self.set_sensor(self._index + 1)
def toggle_recording(self):
self._recording = not self._recording
self._hud.notification('Recording %s' % ('On' if self._recording else 'Off'))
def render(self, display):
if self._surface is not None:
display.blit(self._surface, (0, 0))
@staticmethod
def _parse_image(weak_self, image):
self = weak_self()
if not self:
return
if self._sensors[self._index][0].startswith('sensor.lidar'):
points = np.frombuffer(image.raw_data, dtype=np.dtype('f4'))
points = np.reshape(points, (int(points.shape[0] / 3), 3))
lidar_data = np.array(points[:, :2])
lidar_data *= min(self._hud.dim) / 100.0
lidar_data += (0.5 * self._hud.dim[0], 0.5 * self._hud.dim[1])
lidar_data = np.fabs(lidar_data)
lidar_data = lidar_data.astype(np.int32)
lidar_data = np.reshape(lidar_data, (-1, 2))
lidar_img_size = (self._hud.dim[0], self._hud.dim[1], 3)
lidar_img = np.zeros(lidar_img_size)
lidar_img[tuple(lidar_data.T)] = (255, 255, 255)
self._surface = pygame.surfarray.make_surface(lidar_img)
else:
image.convert(self._sensors[self._index][1])
array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
array = np.reshape(array, (image.height, image.width, 4))
array = array[:, :, :3]
array = array[:, :, ::-1]
self._surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
if self._recording:
image.save_to_disk('_out/%08d' % image.frame_number)
# # ==============================================================================
# # -- Recorder() ---------------------------------------------------------
# # ==============================================================================
class Recorder(object):
def __init__(self,vehicle,controller,workbook):
self.vehicle = vehicle
self.world = vehicle.get_world()
self.controller = controller
self.front_vehicle_state, self.front_vehicle = controller._traffic_detector.search_front_vehicle()
self.workbook = workbook
self.counter = 1
self.sheetname = "Raw_data"
self.sheet = workbook.add_sheet(self.sheetname)
self.vehicle_list = self.world.get_actors().filter("vehicle*")
self.workbookname = str(time.strftime('%Y.%m.%d_%H%M%S',time.localtime(time.time()))) \
+ '_ID_' + str(vehicle.id) + '.xls'
self.sheet.write(0,0,"Ego_Speed")
self.sheet.write(0,1,"Ego_TargetSpeed")
self.sheet.write(0,2,"Ego_Acceleration")
self.sheet.write(0,3,"Ego_Throttle")
self.sheet.write(0,4,"Ego_Steering")
self.sheet.write(0,5,"Ego_Brake")
self.sheet.write(0,6,"Ego_Location_x")
self.sheet.write(0,7,"Ego_Location_y")
self.sheet.write(0,8,"Ego_Rotation_Yaw")
self.sheet.write(0,9,"Ego_Rotation_Pitch")
self.sheet.write(0,10,"Ego_Rotation_Roll")
self.sheet.write(0,11,"Front_Speed")
self.sheet.write(0,12,"Front_Acceleration")
self.sheet.write(0,13,"Front_Throttle")
self.sheet.write(0,14,"Front_Steering")
self.sheet.write(0,15,"Front_Brake")
self.sheet.write(0,16,"Front_Location_x")
self.sheet.write(0,17,"Front_Location_y")
self.sheet.write(0,18,"Front_Rotation_Yaw")
self.sheet.write(0,19,"Front_Rotation_Pitch")
self.sheet.write(0,20,"Front_Rotation_Roll")
self.sheet.write(0,21,"Relative_Distance")
self.sheet.write(0,22,"Target_Relative_Distance")
def start_recorder(self):
wb = self.workbook
vehicle = self.vehicle
controller = self.controller
front_vehicle_state, front_vehicle = controller._traffic_detector.search_front_vehicle()
row = self.counter
worksheet = self.sheet
controller = self.controller
# Export the data of Ego car.
ego_speed = get_speed(vehicle)
ego_target_speed = controller.set_target_speed()
ego_acceleration_vector = vehicle.get_acceleration()
ego_acceleration = math.sqrt(ego_acceleration_vector.x**2 + ego_acceleration_vector.y**2 + ego_acceleration_vector.z**2)
ego_control = vehicle.get_vehicle_control()
ego_throttle = ego_control.throttle
ego_steering = ego_control.steer
ego_brake = ego_control.brake
ego_location_x = vehicle.get_location().x
ego_location_y = vehicle.get_location().y
ego_rotation_yaw = vehicle.get_transform().rotation.yaw
ego_rotation_pitch = vehicle.get_transform().rotation.pitch
ego_rotation_roll = vehicle.get_transform().rotation.roll
worksheet.write(row,0,ego_speed)
worksheet.write(row,1,ego_target_speed)
worksheet.write(row,2,ego_acceleration)
worksheet.write(row,3,ego_throttle )
worksheet.write(row,4,ego_steering)
worksheet.write(row,5,ego_brake)
worksheet.write(row,6,ego_location_x)
worksheet.write(row,7,ego_location_y)
worksheet.write(row,8, ego_rotation_yaw)
worksheet.write(row,9, ego_rotation_pitch)
worksheet.write(row,10, ego_rotation_roll)
# Export the data of Front car.
if front_vehicle_state:
front_speed = get_speed(front_vehicle)
front_acceleration_vector = front_vehicle.get_acceleration()
front_acceleration = math.sqrt(front_acceleration_vector.x**2 + front_acceleration_vector.y**2 + front_acceleration_vector.z**2)
front_control = front_vehicle.get_vehicle_control()
front_throttle = front_control.throttle
front_steering = front_control.steer
front_brake = front_control.brake
front_location_x = front_vehicle.get_location().x
front_location_y = front_vehicle.get_location().y
front_rotation_yaw = front_vehicle.get_transform().rotation.yaw
front_rotation_pitch = front_vehicle.get_transform().rotation.pitch
front_rotation_roll = front_vehicle.get_transform().rotation.roll
relative_distance = math.sqrt((front_location_x - ego_location_x)**2 + (front_location_y - ego_location_y)**2)
target_relative_distance = controller.set_target_distance()
worksheet.write(row,11,front_speed)
worksheet.write(row,12,front_acceleration)
worksheet.write(row,13,front_throttle)
worksheet.write(row,14,front_steering)
worksheet.write(row,15,front_brake)
worksheet.write(row,16,front_location_x)
worksheet.write(row,17,front_location_y)
worksheet.write(row,18,front_rotation_yaw)
worksheet.write(row,19,front_rotation_pitch)
worksheet.write(row,20,front_rotation_roll)
worksheet.write(row,21,relative_distance)
worksheet.write(row,22,target_relative_distance)
self.counter += 1
wb.save(self.workbookname)
def finish_recorder(self):
wb = self.workbook
wb.save()
# ==============================================================================
# -- game_loop() ---------------------------------------------------------
# ==============================================================================
def game_loop(args):
pygame.init()
pygame.font.init()
world = None
supporting_actor_list = []
try:
client = carla.Client(args.host, args.port)
client.set_timeout(4.0)
display = pygame.display.set_mode(
(args.width, args.height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
hud = HUD(args.width, args.height)
world = World(client.get_world(), hud)
# transform_1 = carla.Transform (carla.Location(x=-2.10, y=-125.30, z=0.4),carla.Rotation(pitch=0, yaw=90.0, roll=0))
transform_2 = carla.Transform (carla.Location(x=2400, y=-8.25, z=0.4),carla.Rotation(pitch=0, yaw=180, roll=0))
transform_3 = carla.Transform (carla.Location(x=-2410, y=5.7, z=0.4),carla.Rotation(pitch=0, yaw=0, roll=0))
transform_4 = carla.Transform(carla.Location(x=-2405 ,y=12.25, z=0.40), carla.Rotation(pitch=0, yaw=0, roll=0))
# carModel_1 = random.choice (blueprint.filter('vehicle.tesla.*'))
carModel_1 = world.world.get_blueprint_library().find('vehicle.tesla.model3')
carModel_1.set_attribute('color','10,10,10')
carActor_1 = world.world.try_spawn_actor(carModel_1,transform_3)
carActor_1.set_autopilot (True)
supporting_actor_list.append(carActor_1)
spawn_number = 0
bp_stream = world.world.get_blueprint_library().filter('vehicle*')
bp_stream = [x for x in bp_stream if int(x.get_attribute('number_of_wheels')) == 4]
bp_stream = [x for x in bp_stream if not x.id.endswith('isetta')]
for vehicle_index in range(0,spawn_number):
vehicle_model = random.choice(bp_stream)
vehicle_model.set_attribute('role_name','autopilot')
vehicle_actor = world.world.try_spawn_actor(vehicle_model,random.choice(world.world.get_map().get_spawn_points()))
if vehicle_actor is not None:
supporting_actor_list.append(vehicle_actor)
# vehicle_actor.apply_control (carla.VehicleControl (throttle = 0.5, steer=0.0, brake =0.0) )
vehicle_actor.set_autopilot(True)
# print (vehicle_actor.get_transform())
controller = KeyboardControl(world, False)
hero = world.vehicle
ACC_controller =ACC_Controller(hero)
# ACC_controller.set_destination((-2300,12.2,1.23))
# if args.agent == "Roaming":
# agent = RoamingAgent(world.vehicle)
# else:
# agent = BasicAgent(world.vehicle)
# spawn_point = world.world.get_map().get_spawn_points()[0]
# agent.set_destination((spawn_point.location.x,
# spawn_point.location.y,
# spawn_point.location.z))
clock = pygame.time.Clock()
# this vehicle list only has 1 member
vehicle_list_1 = world.world.get_actors().filter("*vehicle*")
# this vehicle list has 2 members
# vehicle_list_2 = PID_contoller._world.get_actors().filter("*vehicle*")
wb = xlwt.Workbook()
ego_recorder = Recorder(hero,ACC_controller,wb)
while True:
# print (way_point)
if controller.parse_events(world, clock):
return
# as soon as the server is ready continue!
if not world.world.wait_for_tick(10.0):
continue
# print (front_vehicle.get_location())
world.tick(clock)
world.render(display)
pygame.display.flip()
control = ACC_controller.run_step()
world.vehicle.apply_control(control)
ego_recorder.start_recorder()
# print (counter)
# sheet1.write(counter,0,'haha')
# counter = counter + 1
# wb.save('xlwt example_4.xlsx')
# print (world.vehicle.get_location().x)
finally:
if world is not None:
world.destroy()
print('\ndestroying %d actors' % len(supporting_actor_list))
for actor in supporting_actor_list:
actor.destroy()
pygame.quit()
# ==============================================================================
# -- main() --------------------------------------------------------------
# ==============================================================================
def main():
argparser = argparse.ArgumentParser(
description='CARLA Manual Control Client')
argparser.add_argument(
'-v', '--verbose',
action='store_true',
dest='debug',
help='print debug information')
argparser.add_argument(
'--host',
metavar='H',
default='127.0.0.1',
help='IP of the host server (default: 127.0.0.1)')
argparser.add_argument(
'-p', '--port',
metavar='P',
default=2000,
type=int,
help='TCP port to listen to (default: 2000)')
argparser.add_argument(
'--res',
metavar='WIDTHxHEIGHT',
default='1280x720',
help='window resolution (default: 1280x720)')
argparser.add_argument("-a", "--agent", type=str,
choices=["Roaming", "Basic"],
help="select which agent to run",
default="Basic")
args = argparser.parse_args()
args.width, args.height = [int(x) for x in args.res.split('x')]
log_level = logging.DEBUG if args.debug else logging.INFO
logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
logging.info('listening to server %s:%s', args.host, args.port)
print(__doc__)
actor_list = []
try:
game_loop(args)
except KeyboardInterrupt:
print('\nCancelled by user. Bye!')
except Exception as error:
logging.exception(error)
finally:
print('\ndestroying %d actors' % len(actor_list))
for actor in actor_list:
actor.destroy()
if __name__ == '__main__':
main()
|
from myParentclass import *
WIDTH = 900
HEIGHT = 500
class scene_block(sprite):
def __init__(self, width, height, x=0, y=0): # add frames input
sprite.__init__(self, x, y)
self.width = width
self.height = height
self.dim = (self.width, self.height)
self.typ = random.randrange(3)
self.dir = 1
self.xspd = 30
self.surface = pygame.Surface(self.dim, pygame.SRCALPHA, 32)
self.red = 0
self.green = 0
self.blue = 0
self.color = (self.red, self.green, self.blue)
self.surface.fill(self.color)
def move(self):
self.x += self.xspd*self.dir
self.pos = (self.x, self.y)
'''if (self.x > WIDTH - self.width):
del self'''
class ground(sprite): # the mid ground for climbing
def __init__(self, width, height, x=0, y=0): # add frames input
sprite.__init__(self, x, y)
self.width = width
self.height = height
self.dim = (self.width, self.height)
self.typ = random.randrange(3)
self.surface = pygame.Surface(self.dim, pygame.SRCALPHA, 32)
self.setColor((0, 0, 0))
self.surface = pygame.image.load('media/grassground.png').convert_alpha()
self.imagecounter = -1
self.surface = pygame.transform.scale(self.surface, (width, min(height, 300)))
self.images = []
i = self.x
'''while (i < self.x + self.width):
self.images.append(image('media/grassground.png', i, self.y, 1200, min(self.height, 500)))
if (self.x + self.width - i < 1200):
self.images.append(image('media/grassground.png', self.x - self.width - 10, self.y, self.x + self.width - i, min(self.height, 500)))'''
def bonfire_anim(self):
self.imagecounter += 1
if self.imagecounter >= 24:
self.imagecounter = 0
self.surface = pygame.image.load('media/bonfire_0' + str(int(self.imagecounter / 2)) + '.png').convert_alpha()
self.surface = pygame.transform.scale(self.surface, (100, 150))
class trigger(sprite): # the mid ground for climbing
def __init__(self, width, height, x=0, y=0): # add frames input
sprite.__init__(self, x, y)
self.width = width
self.height = height
self.dim = (self.width, self.height)
self.typ = random.randrange(3)
self.surface = pygame.Surface(self.dim, pygame.SRCALPHA, 32)
self.setColor((0, 0, 0))
self.surface.fill(self.color)
def move_x(self, dist):
self.setPos(self.x + dist, self.y)
def move_y(self, dist):
self.setPos(self.x, self.y + dist)
class moving_ground(ground):
def __init__(self, width, height, x=0, y=0): # add frames input
ground.__init__(self, width, height, x, y)
self.move_rangex = (0, 0)
self.move_rangey = (0, 0)
self.xspd = 10
self.yspd = 10
self.dir = 1
self.dir1 = -1
def set_rangex(self, l, r):
self.move_rangex = (l, r)
def set_rangey(self, l, r):
self.move_rangey = (l, r)
def ground_move(self, player, onX = 1, onY = 1): # try to detect player
if (onX == 1):
'''if (self.dir == -1):
self.xspd = 10
else:
self.xspd = 25'''
self.x += self.xspd * self.dir
if (self.checkcollision(self, player)):
player.x += self.xspd * self.dir
if (self.x < self.move_rangex[0]):
self.x = self.move_rangex[0]
self.dir = -self.dir
if (self.x > self.move_rangex[1] - self.width):
self.x = self.move_rangex[1] - self.width
self.dir = -self.dir
if (onY == 1):
self.y += self.yspd * self.dir1
if (self.checkcollision(self, player)):
player.y += self.yspd * self.dir1
if (self.y < self.move_rangey[0]):
self.y = self.move_rangey[0]
self.dir1 = -self.dir1
if (self.y > self.move_rangey[1] - self.height):
self.y = self.move_rangey[1] - self.height
self.dir1 = -self.dir1
self.pos = (self.x, self.y)
class trap(sprite):
def __init__(self, width, height, x=0, y=0): # add frames input
sprite.__init__(self, x, y)
self.width = width
self.height = height
self.dim = (self.width, self.height)
self.typ = random.randrange(3)
self.surface = pygame.Surface(self.dim, pygame.SRCALPHA, 32)
self.red = 0
self.green = 0
self.blue = 0
self.color = (self.red, self.green, self.blue)
self.surface.fill(self.color)
def trap_attack(self, player):
if (self.checkcollision(self, player)):
player.hp = 0
player.jump = -15
player.bounce = True
if (player.x > self.x + self.width/2):
player.dir = 1
else:
player.dir = -1
self.pos = (self.x, self.y)
class moving_trap(trap):
def __init__(self, width, height, x=0, y=0): # add frames input
trap.__init__(self, width, height, x, y)
self.move_range = (0, 0)
self.yspd = 10
self.imagecounter = -1
def set_rangey(self, l, r):
self.move_range = (l, r)
def trap_move(self, player): # try to detect player
self.trap_anim()
self.y += self.yspd * self.dir1
if (self.y < self.move_range[0]):
self.dir1 = 1
if (self.y > self.move_range[1]):
self.dir1 = -1
if (self.checkcollision(self, player) and player.y > self.y + 100 and self.x + 50 <= player.x <= self.x + self.width - 50):
player.hp = 0
if (player.x > self.x + self.width/2):
player.dir = 1
else:
player.dir = -1
self.pos = (self.x , self.y)
def trap_anim(self):
self.imagecounter += 1
if self.imagecounter >= 30:
self.imagecounter = 0
self.surface = pygame.image.load('media/moving_trap0' + str(int(self.imagecounter / 10)) + '.png').convert_alpha()
self.surface = pygame.transform.scale(self.surface, (self.width, 800))
class water(sprite):
def __init__(self, width, height, x=0, y=0): # add frames input
sprite.__init__(self, x, y)
self.width = width
self.height = height
self.dim = (self.width, self.height)
self.typ = random.randrange(3)
self.surface = pygame.Surface(self.dim, pygame.SRCALPHA, 32)
self.surface = pygame.image.load('media/waterbackground6000.png').convert_alpha()
self.surface = pygame.transform.scale(self.surface, (width, height))
|
import RPi.GPIO as GPIO
from time import sleep
from threading import Thread
m1_in1 = 24
m1_in2 = 23
m1_en = 25
temp1=1
m2_in1 = 10
m2_in2 = 9
m2_en = 11
temp2=1
GPIO.setmode(GPIO.BCM)
GPIO.setup(m1_in1,GPIO.OUT)
GPIO.setup(m1_in2,GPIO.OUT)
GPIO.setup(m1_en,GPIO.OUT)
GPIO.output(m1_in1,GPIO.LOW)
GPIO.output(m1_in2,GPIO.LOW)
m1_p=GPIO.PWM(m1_en,100)
m1_p.start(100)
GPIO.setup(14, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(m2_in1,GPIO.OUT)
GPIO.setup(m2_in2,GPIO.OUT)
GPIO.setup(m2_en,GPIO.OUT)
GPIO.output(m2_in1,GPIO.LOW)
GPIO.output(m2_in2,GPIO.LOW)
m2_p=GPIO.PWM(m2_en,100)
m2_p.start(100)
GPIO.setup(14, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def collision_avoid():
while True:
is_collision = GPIO.input(14)
if is_collision:
m1_p.ChangeDutyCycle(0)
m2_p.ChangeDutyCycle(0)
thread = Thread(target=collision_avoid)
thread.daemon = True
thread.start()
def m1_forwards():
GPIO.output(m1_in1,GPIO.HIGH)
GPIO.output(m1_in2,GPIO.LOW)
def m2_forwards():
GPIO.output(m2_in1,GPIO.HIGH)
GPIO.output(m2_in2,GPIO.LOW)
def m1_backwards():
GPIO.output(m1_in1,GPIO.LOW)
GPIO.output(m1_in2,GPIO.HIGH)
def m2_backwards():
GPIO.output(m2_in1,GPIO.LOW)
GPIO.output(m2_in2,GPIO.HIGH)
def move_forwards():
m1_forwards()
m2_forwards()
print("forwards")
def move_backwards():
m1_backwards()
m2_backwards()
print("backwards")
def move_left():
# First motor forwards
m1_backwards()
m2_forwards()
print("left")
def move_right():
# First motor forwards
m1_forwards()
m2_backwards()
print("right")
def start():
m1_p.ChangeDutyCycle(100)
m2_p.ChangeDutyCycle(100)
print("started")
def stop():
m1_p.ChangeDutyCycle(0)
m2_p.ChangeDutyCycle(0)
print("started")
|
#!/usr/bin/env python
from Grammar import Grammar
from Grammar import Parser
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
rules = form['rules'].value.split('\r\n')
cmd = form['cmd'].value
g = Grammar()
p = Parser(g)
p.parse_rules(rules)
if cmd == 'generate':
print(g.derive('S'))
elif cmd == 'cnf':
print(g.to_cnf())
|
# noqa: D100
import re
from pathlib import Path
from setuptools import find_packages, setup
def parse_reqs(file):
"""Parse dependencies from requirements file with regex."""
egg_regex = re.compile(r"#egg=(\w+)")
reqs = list()
for req in open(file):
req = req.strip()
git_url_match = egg_regex.search(req)
if git_url_match:
req = git_url_match.group(1)
reqs.append(req)
return reqs
with open(Path(__file__).parent / "birdy" / "__init__.py") as f:
version = re.search(r'__version__ = [\'"](.+?)[\'"]', f.read()).group(1)
description = "Birdy provides a command-line tool to work with Web Processing Services."
long_description = (
open("README.rst").read()
+ "\n"
+ open("AUTHORS.rst").read()
+ "\n"
+ open("CHANGES.rst").read()
)
requirements = parse_reqs("requirements.txt")
dev_requirements = parse_reqs("requirements_dev.txt")
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Science/Research",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering :: Atmospheric Science",
]
setup(
name="birdhouse-birdy",
version=version,
description=description,
long_description=long_description,
long_description_content_type="text/x-rst",
classifiers=classifiers,
keywords="wps pywps owslib geopython birdy birdhouse",
author="Carsten Ehbrecht",
author_email="ehbrecht@dkrz.de",
url="https://github.com/bird-house/birdy",
license="Apache License v2.0",
# This qualifier can be used to selectively exclude Python versions -
# in this case early Python 2 and 3 releases
python_requires=">=3.6.0",
packages=find_packages(),
include_package_data=True,
install_requires=requirements,
extras_require={
"dev": dev_requirements, # pip install ".[dev]"
},
entry_points={"console_scripts": ["birdy=birdy.cli.run:cli"]},
)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-04-06 17:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('samples', '0003_auto_20171229_0830'),
]
operations = [
migrations.AddField(
model_name='sample',
name='raw',
field=models.TextField(blank=True),
),
migrations.AlterField(
model_name='sample',
name='position',
field=models.IntegerField(blank=True, null=True),
),
]
|
import re
import csv
import string
import sys
fastq = sys.argv[1]
output = sys.argv[2]
file = open(fastq)
map = open(output,'w')
header = ['#SampleID','BarcodeSequence','LinkerPrimerSequence','Description','Length']
map.write("\t".join(header)+"\n")
line = file.readline()
while line:
if line.startswith('@'):
line = line[1:]
row = re.split(' ',line)
ex = [row[0],'','',row[1],row[2][7:]]
map.write("\t".join(ex))
line = file.readline()
|
#!/usr/bin/env python
# coding=UTF-8
# author: zhangjiaqi <1399622866@qq.com>
# File: 03.insert_sort
# Date: 5/12/2019
import random
def insert_sort(li):
"""
思路:从无序区第一个插入到有序区,主要是有序去的变化。
有两种判断插入区域方式:
因为循环次数固定(通过break)则需要判定跳出循环;另一种方式时:时指针方式,只要指针对应的值大
:param li:
:return:
"""
for i in range(1, len(li)): # 从1开始是因为第一个躺直接放入有序区
# 方式一:
# tmp = li[i]
# for j in range(i):
# k = i - j - 1
# if tmp < li[k]:
# li[k], li[k + 1] = li[k + 1], li[k]
# else:
# break
# 方式二:
j = i - 1
tmp = li[i]
while j >= 0 and li[j] > tmp:
li[j + 1] = li[j]
j -= 1
li[j + 1] = tmp
list01 = list(range(10))
random.shuffle(list01)
print(list01)
insert_sort(list01)
print(list01)
if __name__ == '__main__':
pass
|
import torch
import numpy as np
import ipdb
import core.utils_data as utils_disco
st = ipdb.set_trace
import torch.nn.functional as F
XMIN = -7.5 # right (neg is left)
XMAX = 7.5 # right
YMIN = -7.5 # down (neg is up)
YMAX = 7.5 # down
ZMIN = 0.0 # forward
ZMAX = 16.0 # forward
def Ref2Mem(xyz, Z, Y, X):
# xyz is B x N x 3, in ref coordinates
# transforms velo coordinates into mem coordinates
B, N, C = list(xyz.shape)
mem_T_ref = get_mem_T_ref(B, Z, Y, X)
xyz = utils_disco.apply_4x4(mem_T_ref, xyz)
return xyz
def get_mem_T_ref(B, Z, Y, X):
# sometimes we want the mat itself
# note this is not a rigid transform
# for interpretability, let's construct this in two steps...
# translation
center_T_ref = utils_disco.eye_4x4(B)
center_T_ref[:,0,3] = -XMIN
center_T_ref[:,1,3] = -YMIN
center_T_ref[:,2,3] = -ZMIN
VOX_SIZE_X = (XMAX-XMIN)/float(X)
VOX_SIZE_Y = (YMAX-YMIN)/float(Y)
VOX_SIZE_Z = (ZMAX-ZMIN)/float(Z)
# scaling
mem_T_center = utils_disco.eye_4x4(B)
mem_T_center[:,0,0] = 1./VOX_SIZE_X
mem_T_center[:,1,1] = 1./VOX_SIZE_Y
mem_T_center[:,2,2] = 1./VOX_SIZE_Z
mem_T_ref = utils_disco.matmul2(mem_T_center, center_T_ref)
return mem_T_ref
def Mem2Ref(xyz_mem, Z, Y, X):
# xyz is B x N x 3, in mem coordinates
# transforms mem coordinates into ref coordinates
B, N, C = list(xyz_mem.shape)
ref_T_mem = get_ref_T_mem(B, Z, Y, X)
xyz_ref = utils_disco.apply_4x4(ref_T_mem, xyz_mem)
return xyz_ref
def get_ref_T_mem(B, Z, Y, X):
mem_T_ref = get_mem_T_ref(B, Z, Y, X)
# note safe_inverse is inapplicable here,
# since the transform is nonrigid
ref_T_mem = mem_T_ref.inverse()
return ref_T_mem
|
valorx = float(input("digite o valor para x:"))
if(valorx <= 1):
valorx = 1
elif(valorx > 1 and valorx <= 2):
valorx = 2
elif(valorx > 2 and valorx <= 3):
valorx = (valorx**2)
elif(valorx > 3):
valorx = (valorx**3)
print(round(valorx,2)) |
import os
from os.path import exists
import tqdm
import numpy as np
import torch.utils.data
from torchvision.datasets import ImageFolder
from torchvision import transforms
import functools
import PIL
import re
class VideoFolderDataset(torch.utils.data.Dataset):
def __init__(self, folder, counter = None, cache=None, min_len=4, data_type='train'):
assert data_type in ['train', 'test', 'valid']
self.lengths = []
self.followings = []
dataset = ImageFolder(folder)
self.dir_path = folder
self.total_frames = 0
self.images = []
self.labels = np.load(os.path.join(folder,'labels.npy'),
allow_pickle=True, encoding = 'latin1').item()
path_img_cache = os.path.join(cache, "img_cache{}.npy".format(min_len))
path_follow_cache = os.path.join(cache, "following_cache{}.npy".format(min_len))
if cache is not None and exists(path_img_cache) and exists(path_follow_cache) :
self.images = np.load( path_img_cache, allow_pickle=True, encoding = 'latin1')
self.followings = np.load( path_follow_cache, allow_pickle=True, encoding = 'latin1')
else:
for idx, (im, _) in enumerate(
tqdm.tqdm(dataset, desc="Counting total number of frames")):
img_path, _ = dataset.imgs[idx]
v_name = img_path.replace(folder,'') # get the video name
id = v_name.split('/')[-1]
id = int(id.replace('.png', ''))
v_name = re.sub(r"[0-9]+.png",'', v_name)
if id > counter[v_name] - min_len:
continue
following_imgs = []
for i in range(min_len):
following_imgs.append(v_name + str(id+i+1) + '.png')
self.images.append(img_path.replace(folder, ''))
self.followings.append(following_imgs)
np.save(folder + 'img_cache' + str(min_len) + '.npy', self.images)
np.save(folder + 'following_cache' + str(min_len) + '.npy', self.followings)
train_id, test_id = np.load(self.dir_path + 'train_test_ids.npy', allow_pickle=True, encoding = 'latin1')
orders = train_id if data_type == 'train' else test_id
orders = np.array(orders).astype('int32')
self.images = self.images[orders]
self.followings = self.followings[orders]
print("[{}] Total number of clips {}".format(data_type,len(self.images)))
def sample_image(self, im):
shorter, longer = min(im.size[0], im.size[1]), max(im.size[0], im.size[1])
video_len = longer // shorter
se = np.random.randint(0,video_len, 1)[0]
return im.crop((0, se * shorter, shorter, (se+1)*shorter))
def __getitem__(self, item):
# return a training list
lists = [self.images[item]]
for i in range(len(self.followings[item])):
lists.append(str(self.followings[item][i]))
return lists
def __len__(self):
return len(self.images)
class StoryDataset(torch.utils.data.Dataset):
def __init__(self, dataset, textvec, transform):
# dataset: VideoFolderDataset
# textvec: dir_path, a path to the npy file about the text
self.dir_path = dataset.dir_path
self.dataset = dataset
lat = 'latin1'
self.descriptions = np.load(os.path.join(textvec, 'descriptions_vec.npy'),
allow_pickle=True,encoding=lat).item()
self.attributes = np.load(os.path.join(textvec, 'descriptions_attr.npy'),
allow_pickle=True,encoding=lat).item()
self.subtitles = np.load(os.path.join(textvec, 'subtitles_vec.npy'),
allow_pickle=True,encoding=lat).item()
self.descriptions_original = np.load(os.path.join(textvec,'descriptions.npy'),
allow_pickle=True,encoding=lat).item()
self.transforms = transform
self.labels = dataset.labels # character labels
def save_story(self, output, save_path = './'):
all_image = []
images = output['images_numpy']
texts = output['text']
for i in range(images.shape[0]):
all_image.append(np.squeeze(images[i]))
output = PIL.Image.fromarray(np.concatenate(all_image, axis = 0))
output.save(save_path + 'image.png')
fid = open(save_path + 'text.txt', 'w')
for i in range(len(texts)):
fid.write(texts[i] +'\n' )
fid.close()
return
def __getitem__(self, item):
lists = self.dataset[item] # list that contains a sequence of image names
labels = []
image = []
subs = []
des = []
attri = []
text = []
for v in lists:
if type(v) == np.bytes_:
v = v.decode('utf-8')
elif v.split('\'')[0] == 'b':
v = v.replace('b', '').replace('\'', '')
id = v.replace('.png', '')
path = self.dir_path + id + '.png'
im = PIL.Image.open(path) # open the image
im = im.convert('RGB') # convert to RGB
image.append( np.expand_dims(np.array( self.dataset.sample_image(im)), axis = 0) ) # cropping
se = 0
if len(self.descriptions_original[id]) > 1:
# if the description for an image is more than 1, than random pick one
se = np.random.randint(0,len(self.descriptions_original[id]),1)
se = se[0]
text.append( self.descriptions_original[id][se])
des.append(np.expand_dims(self.descriptions[id][se], axis = 0))
subs.append(np.expand_dims(self.subtitles[id][0], axis = 0))
labels.append(np.expand_dims(self.labels[id], axis = 0))
attri.append(np.expand_dims(self.attributes[id][se].astype('float32'), axis = 0))
subs = np.concatenate(subs, axis = 0)
attri = np.concatenate(attri, axis = 0)
des = np.concatenate(des, axis = 0)
labels = np.concatenate(labels, axis = 0)
image_numpy = np.concatenate(image, axis = 0)
# image is T x H x W x C
image = self.transforms(image_numpy) # permuation and convert numpy into torch
# After transform, image is C x T x H x W
##
des = np.concatenate([des, attri], 1) # shape: 5, 128+228=356
##
des = torch.tensor(des)
subs = torch.tensor(subs)
attri = torch.tensor(attri)
labels = torch.tensor(labels.astype(np.float32))
return {'images': image, 'text':text, 'description': des,
'subtitle': subs, 'images_numpy':image_numpy, 'labels':labels}
def __len__(self):
return len(self.dataset.images)
class ImageDataset(torch.utils.data.Dataset):
def __init__(self, dataset, textvec, image_transform,
segment_transform=None, use_segment=False, segment_name='img_segment'):
# dataset: VideoFolderDataset
# tectvec: a path to the npy file about text
self.dir_path = dataset.dir_path
self.dataset = dataset
self.use_segment = use_segment
lat = 'latin1'
self.descriptions = np.load(os.path.join(textvec,'descriptions_vec.npy'),
allow_pickle=True,encoding=lat).item()
self.attributes = np.load(os.path.join(textvec,'descriptions_attr.npy'),
allow_pickle=True,encoding=lat).item()
self.subtitles = np.load(os.path.join(textvec,'subtitles_vec.npy'),
allow_pickle=True,encoding=lat).item()
self.descriptions_original = np.load(os.path.join(textvec,'descriptions.npy'),
allow_pickle=True,encoding=lat).item()
self.transforms = image_transform
self.transforms_seg = segment_transform
self.labels = dataset.labels
self.segment_name = segment_name
print('segment dir: ', self.segment_name)
def __getitem__(self, item):
# Read segmentation image
sub_path = self.dataset[item][0].decode('utf-8')
if self.use_segment:
path = '{}/{}/{}'.format(self.dir_path, self.segment_name, '_'.join(sub_path.split('/')[-2:]) )#self.dir_path+'/''/'+'_'.join(sub_path.split('/')[-2:])
im = PIL.Image.open(path)
# v2
im = im.convert('L')
image_seg = np.array( self.dataset.sample_image(im))
image_seg = self.transforms_seg(image_seg)
# Read orginal image
path = self.dir_path + sub_path
im = PIL.Image.open(path)
im = im.convert('RGB')
image = np.array( self.dataset.sample_image(im))
image = self.transforms(image)
# Read subtitle
id = sub_path.replace('.png','')
subs = self.subtitles[id][0]
# Read text des (embedding),text attribute (one-hot), raw text, character label (one-hot)
se = 0
if len(self.descriptions_original[id]) > 1:
se = np.random.randint(0,len(self.descriptions_original[id]),1)
se = se[0]
des = self.descriptions[id][se]
attri = self.attributes[id][se].astype('float32')
text = self.descriptions_original[id][se]
label = self.labels[id].astype(np.float32)
lists = self.dataset[item]
content = []
attri_content = []
attri_label = []
for v in lists:
if type(v) == np.bytes_:
v = v.decode('utf-8')
elif v.split('\'')[0] == 'b':
v = v.replace('b', '').replace('\'', '')
img_id = v.replace('.png','')
se = 0
if len(self.descriptions[img_id]) > 1:
se = np.random.randint(0,len(self.descriptions[img_id]),1)
se = se[0]
content.append(np.expand_dims(self.descriptions[img_id][se], axis = 0))
attri_content.append(np.expand_dims(self.attributes[img_id][se].astype('float32'), axis = 0))
attri_label.append(np.expand_dims(self.labels[img_id].astype('float32'), axis = 0))
base_content = np.concatenate(content, axis = 0)
attri_content = np.concatenate(attri_content, axis = 0)
attri_label = np.concatenate(attri_label, axis = 0)
content = np.concatenate([base_content, attri_content, attri_label], 1)
des = np.concatenate([des, attri])
##
content = torch.tensor(content)
output = {'images': image, 'text':text, 'description': des,
'subtitle': subs, 'labels':label, 'content': content }
if self.use_segment:
output['images_seg'] = image_seg
return output
def __len__(self):
return len(self.dataset.images)
if __name__ == "__main__":
from datasets.utils import video_transform
n_channels = 3
image_transforms = transforms.Compose([
PIL.Image.fromarray,
transforms.Resize((64, 64)),
transforms.ToTensor(),
lambda x: x[:n_channels, ::],
transforms.Normalize((0.5, 0.5, .5), (0.5, 0.5, 0.5)),
])
image_transforms_seg = transforms.Compose([
PIL.Image.fromarray,
transforms.Resize((64, 64) ),
#transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])])
video_transforms = functools.partial(video_transform, image_transform=image_transforms)
# test run here
counter = np.load('/mnt/storage/img_pororo/frames_counter.npy', allow_pickle=True).item()
base= VideoFolderDataset('/mnt/storage/img_pororo/', counter = counter, cache = '/mnt/storage/img_pororo/')
imagedataset = ImageDataset(base, '/mnt/storage/img_pororo/', (image_transforms, image_transforms_seg))
storydataset = StoryDataset(base, '/mnt/storage/img_pororo/', video_transforms)
storyloader = torch.utils.data.DataLoader(
imagedataset, batch_size=13,
drop_last=True, shuffle=True, num_workers=8)
for batch in storyloader:
print(batch['description'].shape) |
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 3*np.pi, 0.1)
y = np.sin(x)
#Plot the points
plt.plot(x,y)
plt.show() #in Ubuntu Linux
|
from heapq import heappush, heappop, heapify
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
"""Priority queue.
Running time: O(mnlogmn) where m, n are the size of heightMap.
"""
if not heightMap:
return 0
m, n = len(heightMap), len(heightMap[0])
visited = [[False] * n for i in range(m)]
pq = []
heapify(pq)
res = 0
for i in range(m):
heappush(pq, [heightMap[i][0], i, 0])
heappush(pq, [heightMap[i][n-1], i, n-1])
visited[i][0] = visited[i][n-1] = True
for j in range(n):
heappush(pq, [heightMap[0][j], 0, j])
heappush(pq, [heightMap[m-1][j], m-1, j])
visited[0][j] = visited[m-1][j] = True
while pq:
h, i, j = heappop(pq)
for ni, nj in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
if 0 <= ni < m and 0 <= nj < n and not visited[ni][nj]:
visited[ni][nj] = True
res += max(0, h - heightMap[ni][nj])
heappush(pq, [max(h, heightMap[ni][nj]), ni, nj])
return res
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from APHandler import APcreateHandler, APaskHandler, APregistHandler
from sqlalchemy.orm import scoped_session, sessionmaker
from tornado.options import define, options
#import RegisterHandler
# from AppointmentsAskHandler import AskAppointment
# #from Database.tables import Activity,ActivityParticipate,Appointment,AppointmenmtEntry,AppointmentRegister,Estimation,Style,User
# from AppointmentHandler import CreateAppointment, RegistAppointment
from Database.models import engine
from RegisterHandler import RegisterHandler
from ImageCallback import ImageCallback
from loginHandler import LoginHandler
from ACHandler import ActivityCreate,ActivityRegister
from AcaskHandler import AskActivity
from AcentryHandler import AskEntry
from ACHandler import ActivityCreate
define("port", default=800, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/appointment/create", APcreateHandler),
(r"/appointment/ask", APaskHandler),
(r"/appointment/register",APregistHandler),
# (r"/appointment/ask", AskAppointment),
# (r"/appointment/register", RegistAppointment),
(r"/login", LoginHandler),
(r"/regist", RegisterHandler),
# (r"/Activity/create", ActivityCommit),
(r"/Activity/ask", AskActivity),
(r"/Activity/entry",AskEntry),
(r"/activity/create", ActivityCreate),
(r"/activity/register",ActivityRegister),
# (r"/Activity/ask", AskActivity),
# (r"/Activity/register", ActivityJoin),
(r"/ImageCallback",ImageCallback),
]
tornado.web.Application.__init__(self, handlers)
self.db = scoped_session(sessionmaker(bind=engine,
autocommit=False, autoflush=True,
expire_on_commit=False))
# session负责执行内存中的对象和数据库表之间的同步工作 Session类有很多参数,使用sessionmaker是为了简化这个过程
if __name__ == "__main__":
print "HI,I am in main "
tornado.options.parse_command_line()
Application().listen(options.port)
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
|
from flask import Flask, redirect, request, render_template, session
import random, datetime
app = Flask(__name__)
app.secret_key = '@#$%#&%**%^%^%^#%^*(*'
@app.route('/')
def index():
if (not 'gold_count' in session) or (not 'activities' in session):
session['gold_count'] = 0
session['activities'] = []
return render_template('index.html', gold_count = session['gold_count'])
def store_data(tuple_range, location):
activity_str = ''
count = random.randint(tuple_range[0], tuple_range[1])
if location != 'casino':
session['gold_count'] += count
activity_str = 'Earned {} golds from the {}! ({})'.format(count, location, datetime.datetime.now())
else:
if (random.randint(0, 1) == 0):
session['gold_count'] -= count
activity_str = 'Lost {} golds from the {}...quit gambling! ({})'.format(count, location, datetime.datetime.now())
else:
session['gold_count'] += count
activity_str = 'Earned {} golds from the {}! ({})'.format(count, location, datetime.datetime.now())
session['activities'].append(activity_str)
@app.route('/process_gold', methods=['POST'])
def process_gold():
location = request.form['location']
if location == 'farm':
store_data((10, 20), 'farm')
elif location == 'cave':
store_data((5, 10), 'cave')
elif location == 'house':
store_data((2, 5), 'house')
elif location == 'casino':
store_data((0, 50), 'casino')
return redirect('/')
@app.route('/reset')
def reset():
session.clear()
return redirect('/')
app.run(debug=True) |
import smtplib
mail = "youremail@gmail.com"
password = "yourpassword"
mail_server = smtplib.SMTP("smtp.gmail.com", 587) # smtp.gmail.com is server and 587 is port. You can choose 465 or 2525 too
mail_server.starttls() #starts security protocol
mail_server.login(mail, password) #login to mail
message = "Example message"
receiever = mail
mail_server.sendmail(mail, receiever,message)
print("Mail sent")
|
import cv2
import imutils
def crop_ct101_bb(image, bb, padding=10, dst_size=(32, 32)):
(y, h, x, w) = bb
(x, y) = (max(x - padding, 0), max(y - padding, 0))
roi = image[y:h+padding, x:w+padding]
roi = cv2.resize(roi, dst_size, interpolation=cv2.INTER_AREA)
return roi
def pyramid(image, scale=1.5, min_size=(30, 30)):
yield image
while True:
w = int(image.shape[1] / scale)
image = imutils.resize(image, width=w)
if image.shape[0] < min_size[1] or image.shape[0] < min_size[0]:
break
yield image
def sliding_window(image, step_size, window_size):
for y in range(0, image.shape[0], step_size):
for x in range(0, image.shape[1], step_size):
yield (x, y, image[y:y + window_size[1], x:x + window_size[0]])
|
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 30 00:43:54 2020
@author: 융
"""
def solution(N,road,K):
#visited = [False for _ in range(N+1)]
#pdb.set_trace()
costs = [float('inf') for _ in range(N+1)]
costs[1] = 0
parents = [1]
while(parents):
parent = parents.pop(0)
#visited[parent] = True
for a,b,cost in road:
if a == parent or b == parent :
target = b if a == parent else a
if costs[target] > costs[parent] + cost:
costs[target] = costs[parent] + cost
parents.append(target)
return sum(1 for c in costs if c <= K)#모든 정점까지의 최단경로의 비용을 다 담아서 기준 안넘기는 애들 카운트 |
# ##############################################################################
# *** SETUP ***
# ##############################################################################
# -----------------------------------
# MayAi bot Version 0.9 By Moz4r
#
# Wikidatafetcher By Beetlejuice
# -----------------------------------
#Your language ( FR/EN )
lang="FR"
BotURL="http://myai.cloud/bot1.php"
#jokeBOT:
JokeType="RANDOM" # JokeType=RANDOM / BLONDES / CUL / CARAMBAR
#WeatherBOT -> Your city :
CITY="paris"
units="metric" # or : imperial
# ##
#LONK AT http://www.myai.cloud/
#FOR SERVER NAME AND BOT STATUS
#
#IF YOU WANT INMOOV MOUTH CONTROL ( inmoov ) set inmoov=1
#IF YOU DIDNT HAVE MOTORS set inmoov=0
IsInmoov=0
leftPort = "COM3"
rightPort = "COM4"
jawMin = 55
jawMax = 60
# Ligh if you have
IhaveLights = 0
MASSE=27
ROUGE=29
VERT=28
BLEU=30
# ###
#
# ##############################################################################
# *** END SETUP ***
# ##############################################################################
IdontWant=""
import urllib2
from java.lang import String
import random
import threading
import itertools
import random
import time
import textwrap
import codecs
import socket
import os
BotURL=BotURL+"?lang="+lang+"&FixPhpCache="+str(time.time())
#voice emotions
laugh = [" #LAUGH01# ", " #LAUGH02# ", " #LAUGH03# ", " ", " "]
troat = [" #THROAT01# ", " #THROAT02# ", " #THROAT03# ", " ", " ", " "]
#phrases
phrase_pascomprisFR = ["Je ne comprend pas", "tu m as dis quoi la"," je comprends rien a ce que tu me dis"]
phrase_pascomprisEN = ["I don t understand","what did you say ?"]
phrase_jeRechercheFR = ["Je cherche sur le net", "je me renseigne, bouge pas"]
phrase_jeRechercheEN = ["I do a search on internet", "I m asking god"]
image=Runtime.createAndStart("ImageDisplay", "ImageDisplay")
sleep(1)
Runtime.createAndStart("chatBot", "ProgramAB")
Runtime.createAndStart("ear", "WebkitSpeechRecognition")
Runtime.createAndStart("webGui", "WebGui")
wdf=Runtime.createAndStart("wdf", "WikiDataFetcher")
if IsInmoov==0:
Runtime.createAndStart("mouth", "AcapelaSpeech")
sleep(2)
else:
i01 = Runtime.createAndStart("i01", "InMoov")
right = Runtime.start("i01.right", "Arduino")
right.setBoard("mega2560")
right.publishState()
right.connect(rightPort)
left = Runtime.start("i01.left", "Arduino")
left.setBoard("mega2560")
left.publishState()
left.connect(leftPort)
sleep(1)
i01.startRightHand(rightPort,"atmega2560")
i01.startHead(leftPort,"atmega2560")
i01.startMouth()
mouth = i01.mouth
i01.startMouthControl(leftPort)
i01.head.jaw.setMinMax(jawMin,jawMax)
i01.mouthControl.setmouth(jawMin,jawMax)
i01.head.jaw.setRest(jawMin)
i01.setHeadSpeed(0.5, 0.5)
i01.moveHead(80,86,40,78,76)
i01.head.jaw.rest()
i01.head.eyeX.setMinMax(0,180)
i01.head.eyeY.setMinMax(55,180)
i01.head.eyeX.setRest(90)
i01.head.eyeY.setRest(90)
i01.head.eyeY.rest()
i01.head.eyeX.rest()
Runtime.createAndStart("htmlFilter", "HtmlFilter")
if IhaveLights==1:
right.pinMode(MASSE, Arduino.OUTPUT)
right.pinMode(ROUGE, Arduino.OUTPUT)
right.pinMode(VERT, Arduino.OUTPUT)
right.pinMode(BLEU, Arduino.OUTPUT)
right.digitalWrite(MASSE,1)
right.digitalWrite(ROUGE,1)
right.digitalWrite(VERT,0)
right.digitalWrite(BLEU,1)
if lang=="FR":
LANGimage="Désolé, Je rencontre un problème pour te montrer cette image"
voiceType="MargauxSad"
WikiFile="prop.txt"
ear.setLanguage("fr-FR")
wdf.setLanguage("fr")
wdf.setWebSite("frwiki")
else:
voiceType="Ryan"
LANGimage="There is a problem to show the picture I am so sorry"
WikiFile="propEN.txt"
wdf.setLanguage("en")
wdf.setWebSite("enwiki")
# on cherche en français
# On fait des recherches sur le site français de wikidata
sleep(2)
mouth.setVoice(voiceType)
mouth.setLanguage(lang)
chatBot.startSession("ProgramAB", "default", "rachel")
ear.addTextListener(chatBot)
chatBot.addTextListener(htmlFilter)
htmlFilter.addListener("publishText", python.name, "talk")
def talk(data):
sleep(1);
if data!="":
mouth.speak(unicode(data,'utf-8'))
def Parse(utfdata):
Light(1,1,0)
utfdata = urllib2.urlopen(utfdata).read()
utfdata = utfdata.replace("'", "'").replace("http://fr.answers.yahoo.com/question/ind...", "")
try:
utfdata = utfdata.decode( "utf8" ).replace(" : ", random.choice(troat))
except:
pass
print utfdata
Light(1,1,1)
return utfdata;
def MoveHead():
if IsInmoov==1:
#i01.attach()
i01.setHeadSpeed(0.5, 0.5)
i01.moveHead(20,120,40,78,76)
time.sleep(2)
i01.moveHead(150,30,40,78,76)
time.sleep(2)
i01.moveHead(80,90,40,78,76)
#i01.detach()
def Light(ROUGE_V,VERT_V,BLEU_V):
if IhaveLights==1:
right.digitalWrite(ROUGE,ROUGE_V)
right.digitalWrite(VERT,VERT_V)
right.digitalWrite(BLEU,BLEU_V)
def askWiki(query): # retourne la description du sujet (query)
Light(1,0,0)
query = unicode(query,'utf-8')# on force le format de police UTF-8 pour prendre en charge les accents
if query[1]== "\'" : # Si le sujet contient un apostrophe , on efface tout ce qui est avant ! ( "l'été" -> "été")
query2 = query[2:len(query)]
query = query2
print query # petit affichage de contrôle dans la console python ..
word = wdf.cutStart(query) # on enlève le derminant ("le chat" -> "chat")
start = wdf.grabStart(query) # on garde que le déterminant ( je ne sais plus pourquoi j'ai eu besoin de ça, mais la fonction existe ...)
wikiAnswer = wdf.getDescription(word) # récupère la description su wikidata
answer = ( query + " est " + wikiAnswer)
if (wikiAnswer == "Not Found !") or (unicode(wikiAnswer[-9:],'utf-8') == u"Wikimédia") : # Si le document n'ai pas trouvé , on réponds "je ne sais pas"
answer=(question(query))
sleep(1);
talk(answer)
else:
talk(answer)
Light(1,1,1)
def getProperty(query, what): # retourne la valeur contenue dans la propriété demandée (what)
Light(1,0,0)
query = unicode(query,'utf-8')
what = unicode(what,'utf-8')
if query[1]== "\'" :
query2 = query[2:len(query)]
query = query2
if what[1]== "\'" :
what2 = what[2:len(what)]
what = what2
print "what = " + what + " - what2 = " + what2
ID = "error"
# le fichier propriété.txt contient les conversions propriété -> ID . wikidata n'utilise pas des mots mais des codes (monnaie -> P38) f = codecs.open(unicode('os.getcwd().replace("develop", "").replace("\", "/") + "/propriétés_ID.txt','r',"utf-8") #
f = codecs.open(os.getcwd().replace("develop", "").replace("\\", "/")+WikiFile,'r','utf-8') #os.getcwd().replace("develop", "").replace("\\", "/") set you propertiesID.txt path
for line in f:
line_textes=line.split(":")
if line_textes[0]== what:
ID= line_textes[1]
f.close()
#print "query = " + query + " - what = " + what + " - ID = " + ID
wikiAnswer= wdf.getData(query,ID) # récupère la valeur de la propriété si elle existe dans le document
answer = ( what +" de " + query + " est " + wikiAnswer)
if wikiAnswer == "Not Found !":
answer=(question(query+" "+what))
sleep(1);
talk(answer)
else:
talk(answer)
Light(1,1,1)
return answer
def getDate(query, ID):# Cette fonction permet d'afficher une date personnalisée (mardi, le 10 juin, 1975, 12h38 .....)
answer = ( wdf.getTime(query,ID,"day") +" " +wdf.getTime(query,ID,"month") + " " + wdf.getTime(query,ID,"year"))
print " La date est : " + answer
chatBot.getResponse("say Le " + answer)
def FindImage(image):
try:
image = image.decode( "utf8" )
except:
pass
mouth.speak(image)
#PLEASE USE REAL LANGUAGE PARAMETER :
#lang=XX ( FR/EN/RU/IT etc...)
#A FAKE LANGUAGE WORKS BUT DATABASE WILL BROKE
a = Parse(BotURL+"&type=pic&pic="+urllib2.quote(image).replace(" ", "%20"))
Light(1,1,0)
DisplayPic(a)
print BotURL+"&type=pic&pic="+urllib2.quote(image).replace(" ", "%20")
Light(1,1,1)
def Joke():
MoveHead()
a = Parse(BotURL+"&type=joke&genre="+JokeType).replace(" : ", random.choice(troat))
mouth.speakBlocking(a+' '+random.choice(laugh))
def No(data):
if data=="#NO#":
if lang=="FR":
data=random.choice(phrase_pascomprisFR).decode( "utf8" )
else:
data=random.choice(phrase_pascomprisEN).decode( "utf8" )
if IsInmoov==999:
#i01.attach()
i01.setHeadSpeed(1, 1)
i01.moveHead(80,90,0,80,40)
sleep(2)
i01.moveHead(80,90,180,80,40)
sleep(1)
i01.moveHead(80,90,90,80,40)
sleep(0.5)
Light(0,1,1)
if IsInmoov==1:
i01.moveHead(81,50,90,78,40)
sleep(0.5)
i01.moveHead(79,120,90,78,40)
mouth.speakBlocking(data.decode( "utf8" ))
if IsInmoov==1:
i01.moveHead(80,50,90,78,40)
sleep(0.5)
i01.moveHead(83,120,90,78,40)
sleep(0.5)
Light(1,1,1)
if IsInmoov==1:
i01.moveHead(80,90,90,78,40)
mouth.speakBlocking(random.choice(troat).decode( "utf8" ))
if IsInmoov==1:
i01.head.jaw.rest()
#i01.detach()
def Yes(data):
i01.attach()
i01.moveHead(80,90,90,180,40)
sleep(1)
Light(1,0,1)
i01.setHeadSpeed(1, 1)
i01.moveHead(120,88,90,78,40)
sleep(0.4)
i01.moveHead(40,92,90,78,40)
sleep(0.4)
mouth.speakBlocking(data.decode( "utf8" ))
sleep(0.4)
i01.moveHead(120,87,90,78,40)
sleep(0.4)
i01.moveHead(40,91,90,78,40)
sleep(0.4)
i01.moveHead(120,87,90,78,40)
sleep(0.3)
Light(1,1,1)
i01.moveHead(80,90,90,78,40)
mouth.speakBlocking(random.choice(troat))
i01.head.jaw.rest()
i01.detach()
def SaveMemory():
chatBot.savePredicates()
chatBot.writeAIMLIF()
talk("Je sauvegarde dans ma mémoire à long terme, je n'ai pas encore la science infuse")
def Meteo():
a = Parse(BotURL+"&type=meteo&units="+units+"&city="+CITY.replace(" ", "%20"))
mouth.speakBlocking(a)
MoveHead()
def question(data):
if lang=="FR":
LANGfind=random.choice(phrase_jeRechercheFR).decode( "utf8" )
else:
LANGfind=random.choice(phrase_jeRechercheEN).decode( "utf8" )
talk(LANGfind)
a = Parse(BotURL+"&type=question&question="+urllib2.quote(data).replace(" ", "%20"))
print BotURL+"&type=question&question="+urllib2.quote(data).replace(" ", "%20")
if a[0]=="0":
if lang=="FR":
return(random.choice(phrase_pascomprisFR).decode( "utf8" ))
else:
return(random.choice(phrase_pascomprisEN).decode( "utf8" ))
elif a[0:299]<>"":
return(a[0:299])
else:
if lang=="FR":
return(random.choice(phrase_pascomprisFR).decode( "utf8" ))
else:
return(random.choice(phrase_pascomprisEN).decode( "utf8" ))
if IsInmoov==1:
i01.detach()
Light(1,1,1)
def DisplayPic(pic):
r=0
try:
r=image.displayFullScreen(pic,1)
except:
talk(LANGimage)
pass
time.sleep(0.1)
try:
r=image.displayFullScreen(pic,1)
except:
pass
time.sleep(2)
image.exitFS()
image.closeAll()
|
# title: DataManager.py
# description:
# author: Roman Tochony
# date: 20.2.2019
# version: 1.0
# notes:
# python_version: Python 3.7.2
import json
class Container:
"""Object initiator function"""
def __init__(self, version='', date='', description='', link='', sha='', is_valid=True):
self.version = version
self.date = date
self.description = description
self.link = link
self.sha = sha
self.is_valid = is_valid
@staticmethod
def _obj_compare(data, html_element):
"""This function get two objects and compare between them by [Version,date,description,link,sha],
the function will return true in case two objects are equals else will return false"""
if(data.version != html_element.version or
data.date != html_element.date or
data.description != html_element.description or
data.link != html_element.link or
data.sha != html_element.sha or
data.is_valid != html_element.is_valid):
return False
return True
@staticmethod
def _sort_objects_list(obj_list):
"""This function will sort objects list by the link"""
sorted_list = sorted([x for x in obj_list], key=lambda x: x.sha) if len(obj_list) > 0 else []
return sorted_list
def get_object_lists_differences(self, data, html_doc):
"""This function will get two lists contains objects, will check if those lists are equals,greater or smaller
the differences will be returned by dictionary that contain html or/and file missing objects"""
missing_sw_versions = {}
data = self._sort_objects_list(data)
html_doc = self._sort_objects_list(html_doc)
extracted_sha = [x.sha for x in html_doc]
differences_file = [item for item in data if item.sha not in extracted_sha
and self._is_valid_obj(item)]
extracted_sha = [x.sha for x in data]
differences_html_doc = [item for item in html_doc if item.sha not in extracted_sha]
missing_sw_versions['from_html'] = differences_html_doc
missing_sw_versions['from_db'] = differences_file
return missing_sw_versions
@staticmethod
def objects_list_to_json(obj_list):
"""This function will get list of objects and write into file in JSON format"""
temp = []
try:
for obj in obj_list:
temp.append(json.dumps(obj.__dict__))
temp = [json.loads(x) for x in temp]
return temp
except Exception as e:
raise Exception("Something went wrong during converting object to json:{}".format(e))
@staticmethod
def json_collections_to_obj(collection_list):
"""This function will get list of collection and turned them out to list of objects"""
try:
temp = []
for x in collection_list:
temp.append(Container(
x['version'],
x['date'],
x['description'],
x['link'],
x['sha'],
x['is_valid']
))
return temp
except Exception as e:
raise Exception("Something went wrong during converting collection to object:{}".format(e))
@staticmethod
def _is_valid_obj(single_collection):
"""This helper function will check validation bit of object"""
if single_collection.is_valid:
return True
return False
@staticmethod
def is_valid_collection(single_collection):
"""This helper function will check collection validity"""
if single_collection['is_valid']:
return True
return False
@staticmethod
def turn_valid_collections(invalid_collections_list, html_valid_collections):
"""This function will check if there is collection that
should returned to valid bit and return list of those collections"""
extracted_sha = [x.sha for x in html_valid_collections]
true_change_collections = [item for item in invalid_collections_list if item['sha'] in extracted_sha]
return true_change_collections
|
import arcade
from fishy.menu import GameOverView
class PlayerSprite:
def __init__(self):
self.sprite = None
def set_image(self, image_source, scaling):
self.sprite = arcade.Sprite(image_source, scaling)
def set_position(self, x, y):
self.sprite.center_x = x
self.sprite.center_y = y |
'''
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
'''
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates = sorted(candidates)
def dfs(candidates, sublist, target, last):
if target == 0:
res.append(sublist[:])
if target < candidates[0]:
return
for n in candidates:
if n < last:
continue
if n > target:
return
sublist.append(n)
dfs(candidates, sublist, target - n, n)
sublist.pop()
dfs(candidates, [], target, candidates[0])
return res
|
from modules.bomb import Bomb
bomb = Bomb()
bomb.loadSettings()
bomb.initialAnalysis()
# detectVisibleFeatures(bomb)
# rotate bomb to the other side
# detectVisibleFeatures(bomb)
# for module in bomb.modules:
# # solve the module
# # execute the solution
# pass
|
import torch
import gym
from collections import defaultdict
from tqdm import tqdm
from pprint import pprint
# If this import does not work, add an MC. to it.
from blackjack_helper import plot_blackjack_values
def run_episode(env, hold_score):
state = env.reset()
rewards, states, is_done = [], [state], False
while not is_done:
action = 0 if state[0] >= hold_score else 1
state, reward, is_done, info = env.step(action)
states.append(state)
rewards.append(reward)
return states, rewards
def mc_prediction_first_visit(env, hold_score, gamma, num_episodes):
V, N = defaultdict(float), defaultdict(int)
for episode in range(num_episodes):
states, rewards = run_episode(env, hold_score)
return_prob = 0
G = {}
for state, reward in zip(states[1::-1], rewards[::-1]):
return_prob = gamma * return_prob + reward
G[state] = return_prob
for state, return_prob in G.items():
if state[0] <= 21:
V[state] += return_prob
N[state] += 1
for state in V:
V[state] /= N[state]
return V
if __name__ == "__main__":
env = gym.make("Blackjack-v0")
for hold_score in [15, 18, 20]:
gamma = 1
num_episodes = 500000
values = mc_prediction_first_visit(env, hold_score, gamma, num_episodes)
print("First visit MC calculated values:")
pprint(dict(values))
plot_blackjack_values(values)
|
import pickle
import strategy as ai
import Strategy2 as ai2
from Othello_Core import *
import time
#############################################################
# client.py
# a simple tic-tac-toe client
# plays 2 strategies against each other and keeps score
# imports strategies from "strategies.py" as ai
# rest of functionality is stored in core.py
#
# Patrick White: December 2016
############################################################
temp = ai.Strategy()
other = ai2.Strategy2()
BLACK_STRATEGY = temp.alpha_beta_strategy(3)
WHITE_STRATEGY = other.alpha_beta_strategy(3)
ROUNDS = 10
MAXD = 3
# see core.py for constants: MAX, MIN, TIE
def play(strategy_BLACK, strategy_WHITE):
board = temp.initial_board()
player = BLACK
current_strategy ={BLACK: strategy_BLACK, WHITE: strategy_WHITE}
while player is not None:
move = current_strategy[player](player, board)
board = temp.make_move(move, player, board)
#print(temp.print_board(board))
player = temp.next_player(board, player)
return board, temp.score(BLACK, board) # returns "X" "O" or "TIE"
def main(startTime):
j = []
totalwins = 0
for i in range(ROUNDS):
try:
game_result = play(BLACK_STRATEGY, WHITE_STRATEGY)
j.append(game_result)
#print("Winner: ", game_result)
except temp.IllegalMoveError as e:
print(e)
j.append("FORFEIT")
if game_result[1] > 0:
totalwins = totalwins+1
## print(temp.print_board(game_result[0]))
## print("Score: ", game_result[1])
## winner = "WHITE"
## if game_result[1] > 0:
## winner = "BLACK"
## print("Winner: ", winner)
print("Black: ",totalwins)
print("White: ", 10-totalwins)
print(time.time()-startTime, "ms")
if __name__ == "__main__":
main(time.time())
|
# -*- coding: utf-8 -*-
"""Family module for Speedydeletion.Wikia.com"""
__version__ = '$Id$'
from pywikibot import family
class Family(family.Family):
"""Family class for Wikia."""
def __init__(self):
"""Constructor."""
family.Family.__init__(self)
self.name = u'speedydeletion'
langs = [
'en', 'sv', 'nl', 'de', 'fr', 'ru', 'it', 'es',
'vi',
'war', 'ceb',
'pl', 'ja', 'pt',
#'pt-br', not supported yet
'zh',
'uk', 'ca',
'no',
'fa',
'fi',
'id',
'ar',
'cs',
'ko',
'ms',
'hu',
'ro',
'sr',
'tr',
'min',
'sh',
'kk',
'eo',
'sk',
'eu',
'da',
'lt',
#'bg',
#'he',
'hr',
'sl',
#'uz', 'hy', 'et',
#'vo', 'nn', 'gl', 'simple',
'hi',
#'la',
'el',
#'az', 'th', 'oc',
#'ka', 'mk', 'be',
'new',
#'tt', 'pms',
'tl',
#'ta', 'te', 'cy', 'lv',
#'be-x-old', 'ht',
'ur',
#'ce', 'bs',
'sq',
#'br',
'jv',
#'mg',
'lb',
#'mr', 'is',
'ml',
#'pnb', 'ba', 'af',
'my',
#'zh-yue',
'bn',
#'ga',
#'lmo',
'yo',
#'fy', 'an', 'cv',
'tg',
'ky',
'sw',
#'ne', 'io', 'gu',
#'bpy', 'sco',
'scn',
#'nds', 'ku', 'ast', 'qu', 'su', 'als',
'gd',
# 'kn', 'am', 'ckb', 'ia',
'nap',
#'bug', 'bat-smg',
'wa',
#'map-bms',
# 'mn',
'arz',
#'pa', 'mzn',
'si',
#'zh-min-nan',
'yi',
'sah',
'fo',
# 'vec',
'sa',
#'bar',
'nah',
#'os', 'roa-tara', 'pam', 'or', 'hsb',
# 'se', 'li', 'mrj', 'mi', 'ilo',
'co',
#'hif', 'bcl', 'gan', 'frr',
'bo',
#'rue', 'glk', 'mhr', 'nds-nl', 'fiu-vro', 'ps', 'tk', 'pag',
# 'vls', 'gv', 'xmf',
'diq',
#'km', 'kv', 'zea', 'csb', 'crh', 'hak',
# 'vep', 'sc', 'ay', 'dv',
'so',
#'zh-classical', 'nrm', 'rm', 'udm',
# 'koi', 'kw',
'ug',
#'stq', 'lad', 'wuu', 'lij', 'eml', 'fur', 'mt',
# 'bh', 'as',
'cbk-zam',
#'gn', 'pi', 'pcd', 'szl', 'gag', 'ksh',
# 'nov', 'ang', 'ie', 'nv', 'ace', 'ext', 'frp', 'mwl', 'ln', 'sn',
# 'lez', 'dsb', 'pfl', 'krc', 'haw', 'pdc', 'kab', 'xal', 'rw', 'myv',
# 'to', 'arc', 'kl',
'bjn',
#'kbd',
'lo',
#'ha', 'pap', 'tpi', 'av',
# 'lbe',
'mdf',
# 'jbo', 'na', 'wo', 'bxr', 'ty', 'srn', 'ig', 'nso',
# 'kaa', 'kg', 'tet', 'ab', 'ltg', 'zu', 'za', 'cdo', 'tyv', 'chy',
# 'tw', 'rmy', 'roa-rup', 'cu', 'tn', 'om', 'chr', 'got', 'bi', 'pih',
# 'rn', 'sm', 'bm', 'ss', 'iu',
'sd',
#'pnt', 'ki', 'xh', 'ts', 'ee',
# 'ak', 'ti', 'fj', 'lg', 'ks', 'ff', 'sg', 'ny', 've', 'cr', 'st',
# 'dz', 'ik', 'tum', 'ch',
]
self.langs = dict([(lang, '%s.speedydeletion.wikia.com' % lang)
for lang in langs])
def hostname(self, code):
"""Return the hostname for every site in this family."""
return u'%s.speedydeletion.wikia.com' % code
def version(self, code):
"""Return the version for this family."""
return "1.19.20"
def scriptpath(self, code):
"""Return the script path for this family."""
return ''
def apipath(self, code):
"""Return the path to api.php for this family."""
return '/api.php'
|
import redis
class RedisClient:
def __init__(self, host, port):
self.host = host
self.port = port
self.client = redis.Redis(host=host, port=port)
if __name__ == '__main__':
host = "localhost"
port = 6379
r = redis.Redis(host=host, port=port)
for i in range(100):
r.set(i+1000, i+1)
# name = r"D:\service\APP\test\{}.txt".format(int(r.get(i)) * 10+10)
# with open(name, "w")as f:
# f.write(str(i))
#
# print(r.get(i))
|
import json
import os
import pytest
import requests
import requests_mock as req_mock
from pipeline_tools.shared import http_requests
from pipeline_tools.shared.http_requests import HttpRequests
from pipeline_tools.tests.http_requests_manager import HttpRequestsManager
class TestHttpRequests(object):
def test_check_status_bad_codes(self):
with pytest.raises(requests.HTTPError):
response = requests.Response()
response.status_code = 404
HttpRequests.check_status(response)
with pytest.raises(requests.HTTPError):
response = requests.Response()
response.status_code = 409
HttpRequests.check_status(response)
with pytest.raises(requests.HTTPError):
response = requests.Response()
response.status_code = 500
HttpRequests.check_status(response)
with pytest.raises(requests.HTTPError):
response = requests.Response()
response.status_code = 301
HttpRequests.check_status(response)
def test_check_status_acceptable_codes(self):
try:
response = requests.Response()
response.status_code = 200
HttpRequests.check_status(response)
except requests.HTTPError as e:
pytest.fail(str(e))
try:
response = requests.Response()
response.status_code = 202
HttpRequests.check_status(response)
except requests.HTTPError as e:
pytest.fail(str(e))
def test_get_retries_then_raises_exception_on_500(self, requests_mock):
def callback(request, response):
response.status_code = 500
return {}
url = 'https://fake_url'
requests_mock.get(url, json=callback)
with pytest.raises(requests.HTTPError), HttpRequestsManager():
HttpRequests().get(url)
assert requests_mock.call_count == 3
def test_get_immediately_raises_exception_on_404(self, requests_mock):
def callback(request, response):
response.status_code = 404
return {}
url = 'https://fake_url'
requests_mock.get(url, json=callback)
with pytest.raises(requests.HTTPError), HttpRequestsManager():
HttpRequests().get(url)
assert requests_mock.call_count == 1
def test_get_succeeds_on_200(self, requests_mock):
def callback(request, response):
response.status_code = 200
return {}
url = 'https://fake_url'
requests_mock.get(url, json=callback)
try:
with HttpRequestsManager():
HttpRequests().get(url)
except requests.HTTPError as e:
pytest.fail(str(e))
# @mock.patch('requests.get', side_effect=requests.ConnectionError())
def test_get_retries_on_connection_error(self, requests_mock):
def callback(request, response):
raise requests.ConnectionError()
url = 'https://fake_url'
requests_mock.get(url, json=callback)
with pytest.raises(requests.ConnectionError), HttpRequestsManager():
HttpRequests().get(url)
assert requests_mock.call_count == 3
def test_get_records_details(self, requests_mock):
def callback(request):
response = requests.Response()
response.status_code = 200
return {}
url = 'https://fake_url'
adapter = req_mock.Adapter()
session = requests.Session()
session.mount('mock', adapter)
adapter.add_matcher(callback)
requests_mock.get(url)
with HttpRequestsManager() as temp_dir:
HttpRequests().get(url)
file_path = temp_dir + '/request_001.txt'
assert os.path.isfile(file_path) is True
assert os.stat(file_path).st_size > 0
with open(file_path) as f:
first_line = f.readline()
parts = first_line.strip().split(' ')
assert len(parts) == 2
assert parts[0] == 'GET'
assert parts[1] == 'https://fake_url'
def test_post_records_details(self, requests_mock):
def callback(request):
response = requests.Response()
response.status_code = 200
return {}
url = 'https://fake_url'
js = json.dumps({'foo': 'bar'})
adapter = req_mock.Adapter()
session = requests.Session()
session.mount('mock', adapter)
adapter.add_matcher(callback)
requests_mock.post(url, json=js)
with HttpRequestsManager() as temp_dir:
HttpRequests().post(url, json=js)
file_path = temp_dir + '/request_001.txt'
assert os.path.isfile(file_path) is True
assert os.stat(file_path).st_size > 0
with open(file_path) as f:
first_line = f.readline()
parts = first_line.strip().split(' ')
assert len(parts) == 2
assert parts[0] == 'POST'
assert parts[1] == 'https://fake_url'
rest_of_file = f.read()
response_js = json.loads(rest_of_file)
assert 'foo' in response_js
assert response_js['foo'] == 'bar'
def test_post_records_response_details(self, requests_mock):
def callback(request):
response = requests.Response()
response.status_code = 200
return response
url = 'https://fake_url'
adapter = req_mock.Adapter()
session = requests.Session()
session.mount('mock', adapter)
adapter.add_matcher(callback)
requests_mock.post(url, json={'foo': 'bar'})
with HttpRequestsManager() as temp_dir:
HttpRequests().post(url, json='{}')
file_path = temp_dir + '/response_001.txt'
assert os.path.isfile(file_path) is True
assert os.stat(file_path).st_size > 0
with open(file_path) as f:
first_line = f.readline().strip()
assert first_line == '200'
rest_of_file = f.read()
js = json.loads(rest_of_file)
assert 'foo' in js
assert js['foo'] == 'bar'
def test_does_not_record_when_var_not_set(self, requests_mock):
def callback(request):
response = requests.Response()
response.status_code = 200
return {}
url = 'https://fake_url'
adapter = req_mock.Adapter()
session = requests.Session()
session.mount('mock', adapter)
adapter.add_matcher(callback)
requests_mock.get(url)
with HttpRequestsManager(False) as temp_dir:
HttpRequests().get(url)
file_path = temp_dir + '/request_001.txt'
assert os.path.isfile(file_path) is False
def test_creates_dummy_files_even_when_record_not_on(self, requests_mock):
def callback(request):
response = requests.Response()
response.status_code = 200
return {}
url = 'https://fake_url'
adapter = req_mock.Adapter()
session = requests.Session()
session.mount('mock', adapter)
adapter.add_matcher(callback)
requests_mock.get(url)
with HttpRequestsManager(False) as temp_dir:
HttpRequests().get(url)
assert os.path.isfile(temp_dir + '/request_000.txt') is True
assert os.path.isfile(temp_dir + '/response_000.txt') is True
def test_get_next_file_suffix_empty(self):
assert HttpRequests._get_next_file_suffix([]) == '001'
def test_get_next_file_suffix_one_file(self):
assert HttpRequests._get_next_file_suffix(['/foo/bar/asdf_001.txt']) == '002'
def test_get_next_file_suffix_11(self):
assert HttpRequests._get_next_file_suffix(['a_002.txt', 'a_010.txt']) == '011'
def test_get_next_file_suffix_unsorted(self):
assert (
HttpRequests._get_next_file_suffix(['a_002.txt', 'a_004.txt', 'a_003.txt'])
== '005'
)
def test_attributes_initialized_for_empty_strings(self):
with HttpRequestsManager():
os.environ[http_requests.RECORD_HTTP_REQUESTS] = ''
os.environ[http_requests.HTTP_RECORD_DIR] = ''
os.environ[http_requests.RETRY_MAX_TRIES] = ''
os.environ[http_requests.RETRY_MAX_INTERVAL] = ''
os.environ[http_requests.RETRY_MULTIPLIER] = ''
os.environ[http_requests.RETRY_TIMEOUT] = ''
os.environ[http_requests.INDIVIDUAL_REQUEST_TIMEOUT] = ''
hr = HttpRequests(write_dummy_files=False)
assert hr.should_record is False
assert hr.record_dir == '.'
assert hr.retry_timeout == 7200
assert hr.individual_request_timeout == 60
assert hr.retry_max_tries == 1e4
assert hr.retry_multiplier == 1
assert hr.retry_max_interval == 60
assert hr.individual_request_timeout == 60
|
# Generated by Django 3.0.4 on 2020-05-18 07:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webpage', '0004_auto_20200506_2209'),
]
operations = [
migrations.AlterField(
model_name='package',
name='description1',
field=models.CharField(max_length=20000, null=True),
),
migrations.AlterField(
model_name='package',
name='image1',
field=models.ImageField(null=True, upload_to='pics'),
),
migrations.AlterField(
model_name='package',
name='name1',
field=models.CharField(max_length=40, null=True),
),
]
|
__author__ = 'marcus, fbahr'
import os
from ConfigParser import RawConfigParser
class Config(object): # ...RawConfigParser):
def __init__(self, path='giraffe.cfg'):
# RawConfigParser.__init__(self) # < RawConfigParser = 'old-style' class
if path == 'giraffe.cfg':
path = os.sep.join(__file__.split(os.sep)[0:-3] + ['bin', path])
self._config = RawConfigParser()
self._config.read(path)
def __getattr__(self, name):
if hasattr(self._config, name):
return getattr(self._config, name)
else:
raise AttributeError('\'Config\' object has no attribute \'%s\'' % name)
def get(self, section, option, **kwargs):
try:
return self._config.get(section, option)
except:
return kwargs['default']
|
import json
from flask import Flask,render_template,request
from flaskext.mysql import MySQL
app=Flask(__name__)
mysql=MySQL()
app.config['MYSQL_DATABASE_HOST']="127.0.0.1"
app.config['MYSQL_DATABASE_USER']="root"
app.config['MYSQL_DATABASE_PASSWORD']=""
app.config['MYSQL_DATABASE_DB']="student_database"
mysql.init_app(app)
conn=mysql.connect
@app.route('/getall')
def get_all():
conn=mysql.connect()
cursor=conn.cursor()
try:
sql="SELECT * FROM `student` ORDER BY `lastname`";
conn=mysql.connect()
cursor=conn.cursor()
cursor.execute(sql)
rows=cursor.fetchall()
return json.dumps({"list":rows})
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route("/login",methods=['POST'])
def login():
if request.form['username'] =='admin' and request.form['password'] =='admin':
return render_template("/admin.html")
else:
msg = 'Incorrect username / password !'
return render_template('index.html', msg=msg)
@app.route('/')
def main():
return render_template('index.html')
@app.route('/logout')
def logout():
return render_template('index.html')
@app.route('/register',methods=['POST'])
def add_student():
idno=request.form['idno']
lastname=request.form['lastname']
firstname=request.form['firstname']
course=request.form['course']
level=request.form['level']
msg = 'You have successfully registered !'
conn=mysql.connect()
cursor=conn.cursor()
conn = conn.cursor()
cursor.execute('SELECT * FROM student WHERE idno = % s', (idno,))
student = cursor.fetchone()
if student:
msg = 'Student already exists !'
else:
try:
sql="INSERT INTO `student`(idno,lastname,firstname,course,level) VALUES(%s,%s,%s,%s,%s)"
conn=mysql.connect()
cursor=conn.cursor()
cursor.execute(sql,(idno,lastname,firstname,course,level))
conn.commit()
except Exception as e:
msg = 'Error! Please try again.'
finally:
cursor.close()
conn.close()
return render_template('admin.html',msg=msg)
@app.route('/deletestudent', methods=['POST'])
def delete_student():
idno = request.form['myText']
conn=None
cursor=None
try:
sql="DELETE FROM `student` WHERE `idno`=%s"
conn=mysql.connect()
cursor=conn.cursor()
fld=(idno)
cursor.execute(sql,fld)
conn.commit()
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
return render_template('admin.html')
@app.route('/editstudent', methods=['POST'])
def edit_student():
idno = request.form['myText0']
lastname = request.form['myText01']
firstname = request.form['myText02']
course = request.form['myText03']
level = request.form['myText04']
conn=None
cursor=None
try:
sql="UPDATE `student` SET lastname=%s,firstname=%s,course=%s,level=%s WHERE `idno`=%s"
val1 = (lastname,firstname,course,level,idno)
conn=mysql.connect()
cursor=conn.cursor()
cursor.execute(sql,val1)
conn.commit()
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
return render_template('admin.html')
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response
if __name__ == '__main__':
app.debug = True
app.run()
|
def get_formatted_name(first,middle,last):
"""Generates a neatly formatted full name."""
full_name = f"{first} {middle} {last}"
return full_name.title()
# This version should work for people with middle names, but when we test
# it, we see that we’ve broken the function for people with just a first and last
# name. This time, running the file test_name_function.py gives an error...
# Assuming you’re checking the right
# conditions, a passing test means the function is behaving correctly and a
# failing test means there’s an error in the new code you wrote. So when a test
# fails, don’t change the test. Instead, fix the code that caused the test to fail.
# Examine the changes you just made to the function, and figure out how
# those changes broke the desired behavior. |
import pymysql
import timeit
import requests
import urllib
import numpy
start = timeit.default_timer()
connection = pymysql.connect(host='localhost',user='root',db='benchmark',cursorclass=pymysql.cursors.DictCursor)
c = connection.cursor()
c.execute('select id from class')
results = []
rets = c.fetchall()
for c, i in enumerate(rets[0:3000:3]):
t = timeit.default_timer()
url = urllib.quote_plus(i['id'].lower())
r = requests.get('http://localhost:5000/class/{}'.format(url))
if c % 50 == 0:
print(c)
print(r.json())
results.append(timeit.default_timer() - t)
print(timeit.default_timer() - start)
a = numpy.array(results)
print(a.mean())
|
import PC
import configme
import sys
import Commander_normal
import PipCommander
import Commander
import executed_information
import register_file
from PyQt5 import QtCore, QtGui, QtWidgets
import time
import BASIC_code
#import breeze_resources
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QKeySequence, QPalette, QColor
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QPalette
from PyQt5 import QtCore, QtGui, QtWidgets
import error_detector_unit
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
configme.breakflag=0
self.mcgenflag=0
self.runflag=0
self.steppointer=int((PC.PC)/4)
self.inst_num=0
self.breakpoint=-1
self.breakpc=-1
self.endpc=-1
FONT = QtGui.QFont()
FONT.setPointSize(12)
FONT3 = QtGui.QFont()
FONT3.setPointSize(10)
font2 = QtGui.QFont()
font2.setPointSize(12)
font4 = QtGui.QFont()
font4.setPointSize(11)
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1284, 858)
MainWindow.setAutoFillBackground(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
#self.centralwidget.setStyleSheet("background-color:black;")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.panes = QtWidgets.QTabWidget(self.centralwidget)
self.panes.setEnabled(True)
self.panes.setDocumentMode(False)
self.panes.setMovable(False)
self.panes.setTabBarAutoHide(True)
self.panes.setObjectName("panes")
self.tab_8 = QtWidgets.QWidget()
self.tab_8.setObjectName("tab_8")
self.gridLayout_3 = QtWidgets.QGridLayout(self.tab_8)
self.gridLayout_3.setObjectName("gridLayout_3")
self.label_44 = QtWidgets.QLabel(self.tab_8)
self.label_44.setObjectName("label_44")
self.gridLayout_3.addWidget(self.label_44, 3, 0, 1, 1)
spacerItem = QtWidgets.QSpacerItem(350, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_3.addItem(spacerItem, 1, 0, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(500, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_3.addItem(spacerItem1, 1, 4, 1, 1)
self.label_42 = QtWidgets.QLabel(self.tab_8)
self.label_42.setObjectName("label_42")
self.gridLayout_3.addWidget(self.label_42, 0, 1, 1, 1)
self.label_43 = QtWidgets.QLabel(self.tab_8)
self.label_43.setText("")
self.label_43.setPixmap(QtGui.QPixmap("../../Pictures/fall-autumn-red-season.jpg"))
self.label_43.setObjectName("label_43")
self.gridLayout_3.addWidget(self.label_43, 1, 1, 1, 1)
self.panes.addTab(self.tab_8, "")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.gridLayout_2 = QtWidgets.QGridLayout(self.tab)
self.gridLayout_2.setObjectName("gridLayout_2")
self.openfilebutton = QtWidgets.QPushButton(self.tab)
self.openfilebutton.setObjectName("openfilebutton")
self.openfilebutton.clicked.connect(self.dialogopener)
self.gridLayout_2.addWidget(self.openfilebutton, 0, 0, 1, 1)
self.editor_code = QtWidgets.QTextEdit(self.tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.editor_code.sizePolicy().hasHeightForWidth())
self.editor_code.setSizePolicy(sizePolicy)
self.editor_code.setObjectName("editor_code")
self.editor_code.setFont(FONT)
self.gridLayout_2.addWidget(self.editor_code, 1, 0, 1, 1)
self.panes.addTab(self.tab, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.gridLayout_9 = QtWidgets.QGridLayout(self.tab_2)
self.gridLayout_9.setObjectName("gridLayout_9")
self.label = QtWidgets.QLabel(self.tab_2)
self.label.setObjectName("label")
self.gridLayout_9.addWidget(self.label, 0, 0, 1, 1)
self.previous = QtWidgets.QPushButton(self.tab_2)
self.previous.setObjectName("previous")
self.gridLayout_9.addWidget(self.previous, 0, 7, 1, 1)
self.label_39 = QtWidgets.QLabel(self.tab_2)
self.label_39.setObjectName("label_39")
self.gridLayout_9.addWidget(self.label_39, 3, 0, 1, 1)
self.run = QtWidgets.QPushButton(self.tab_2)
self.run.setObjectName("run")
self.gridLayout_9.addWidget(self.run, 0, 5, 1, 1)
self.pc_edit = QtWidgets.QLineEdit(self.tab_2)
self.pc_edit.setObjectName("pc_edit")
self.pc_edit.setFont(FONT)
self.gridLayout_9.addWidget(self.pc_edit, 0, 2, 1, 1)
# self.asciiradiobutton = QtWidgets.QRadioButton(self.tab_2)
# self.asciiradiobutton.setObjectName("asciiradiobutton")
# self.gridLayout_9.addWidget(self.asciiradiobutton, 5, 12, 1, 1)
# self.decimalradiobutton = QtWidgets.QRadioButton(self.tab_2)
# self.decimalradiobutton.setObjectName("decimalradiobutton")
# self.gridLayout_9.addWidget(self.decimalradiobutton, 5, 11, 1, 1)
self.label_41 = QtWidgets.QLabel(self.tab_2)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_41.sizePolicy().hasHeightForWidth())
self.label_41.setSizePolicy(sizePolicy)
self.label_41.setObjectName("label_41")
self.gridLayout_9.addWidget(self.label_41, 3, 6, 1, 1)
self.label_40 = QtWidgets.QLabel(self.tab_2)
self.label_40.setObjectName("label_40")
self.gridLayout_9.addWidget(self.label_40, 3, 2, 1, 1)
self.tabWidget_5 = QtWidgets.QTabWidget(self.tab_2)
self.tabWidget_5.setObjectName("tabWidget_5")
self.tab_7 = QtWidgets.QWidget()
self.tab_7.setObjectName("tab_7")
self.gridLayout_6 = QtWidgets.QGridLayout(self.tab_7)
self.gridLayout_6.setObjectName("gridLayout_6")
self.console = QtWidgets.QTextEdit(self.tab_7)
self.console.setObjectName("console")
self.console.setFont(FONT)
self.gridLayout_6.addWidget(self.console, 0, 0, 1, 1)
self.tabWidget_5.addTab(self.tab_7, "")
self.gridLayout_9.addWidget(self.tabWidget_5, 4, 9, 1, 4)
self.basic_code = QtWidgets.QTextEdit(self.tab_2)
self.basic_code.setObjectName("basic_code")
self.basic_code.setFont(FONT)
self.gridLayout_9.addWidget(self.basic_code, 4, 0, 1, 8)
self.reset = QtWidgets.QPushButton(self.tab_2)
self.reset.setObjectName("reset")
self.gridLayout_9.addWidget(self.reset, 0, 8, 1, 1)
self.step = QtWidgets.QPushButton(self.tab_2)
self.step.setObjectName("step")
self.gridLayout_9.addWidget(self.step, 0, 6, 1, 1)
# self.hexradiobutton = QtWidgets.QRadioButton(self.tab_2)
# self.hexradiobutton.setChecked(True)
# self.hexradiobutton.setObjectName("hexradiobutton")
# self.gridLayout_9.addWidget(self.hexradiobutton, 5, 13, 1, 1)
self.tabWidget_2 = QtWidgets.QTabWidget(self.tab_2)
self.tabWidget_2.setUsesScrollButtons(True)
self.tabWidget_2.setObjectName("tabWidget_2")
self.tabWidget_2.setFixedWidth(515)
self.tab_3 = QtWidgets.QWidget()
self.tab_3.setObjectName("tab_3")
self.gridLayout_4 = QtWidgets.QGridLayout(self.tab_3)
self.gridLayout_4.setObjectName("gridLayout_4")
self.scrollArea = QtWidgets.QScrollArea(self.tab_3)
self.scrollArea.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, -321, 239, 1478))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.gridLayout_5 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
self.gridLayout_5.setObjectName("gridLayout_5")
self.label_3 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_3.setObjectName("label_3")
self.gridLayout_5.addWidget(self.label_3, 2, 0, 1, 1)
self.label_2 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_2.setTextFormat(QtCore.Qt.AutoText)
self.label_2.setObjectName("label_2")
self.gridLayout_5.addWidget(self.label_2, 0, 0, 1, 1)
self.x0 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x0.setObjectName("x0")
self.x0.setFont(font2)
self.gridLayout_5.addWidget(self.x0, 0, 1, 1, 1)
self.label_21 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_21.setObjectName("label_21")
self.gridLayout_5.addWidget(self.label_21, 1, 0, 1, 1)
self.x1 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x1.setObjectName("x1")
self.x1.setFont(font2)
self.gridLayout_5.addWidget(self.x1, 1, 1, 1, 1)
self.x9 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x9.setObjectName("x9")
self.x9.setFont(font2)
self.gridLayout_5.addWidget(self.x9, 9, 1, 1, 1)
self.label_23 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_23.setObjectName("label_23")
self.gridLayout_5.addWidget(self.label_23, 10, 0, 1, 1)
self.x10 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x10.setObjectName("x10")
self.x10.setFont(font2)
self.gridLayout_5.addWidget(self.x10, 10, 1, 1, 1)
self.x4 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x4.setObjectName("x4")
self.x4.setFont(font2)
self.gridLayout_5.addWidget(self.x4, 4, 1, 1, 1)
self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_5.setObjectName("label_5")
self.gridLayout_5.addWidget(self.label_5, 7, 0, 1, 1)
self.label_20 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_20.setObjectName("label_20")
self.gridLayout_5.addWidget(self.label_20, 4, 0, 1, 1)
self.x6 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x6.setObjectName("x6")
self.x6.setFont(font2)
self.gridLayout_5.addWidget(self.x6, 6, 1, 1, 1)
self.label_26 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_26.setObjectName("label_26")
self.gridLayout_5.addWidget(self.label_26, 6, 0, 1, 1)
self.x2 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x2.setObjectName("x2")
self.x2.setFont(font2)
self.gridLayout_5.addWidget(self.x2, 2, 1, 1, 1)
self.x5 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x5.setObjectName("x5")
self.x5.setFont(font2)
self.gridLayout_5.addWidget(self.x5, 5, 1, 1, 1)
self.label_27 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_27.setObjectName("label_27")
self.gridLayout_5.addWidget(self.label_27, 3, 0, 1, 1)
self.x3 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x3.setObjectName("x3")
self.x3.setFont(font2)
self.gridLayout_5.addWidget(self.x3, 3, 1, 1, 1)
self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_4.setObjectName("label_4")
self.gridLayout_5.addWidget(self.label_4, 5, 0, 1, 1)
self.x7 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x7.setText("")
self.x7.setObjectName("x7")
self.x7.setFont(font2)
self.gridLayout_5.addWidget(self.x7, 7, 1, 1, 1)
self.label_7 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_7.setObjectName("label_7")
self.gridLayout_5.addWidget(self.label_7, 8, 0, 1, 1)
self.x8 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x8.setObjectName("x8")
self.x8.setFont(font2)
self.gridLayout_5.addWidget(self.x8, 8, 1, 1, 1)
self.label_6 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_6.setObjectName("label_6")
self.gridLayout_5.addWidget(self.label_6, 9, 0, 1, 1)
self.label_8 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_8.setObjectName("label_8")
self.gridLayout_5.addWidget(self.label_8, 11, 0, 1, 1)
self.x11 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x11.setObjectName("x11")
self.x11.setFont(font2)
self.gridLayout_5.addWidget(self.x11, 11, 1, 1, 1)
self.x12 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x12.setObjectName("x12")
self.x12.setFont(font2)
self.gridLayout_5.addWidget(self.x12, 12, 1, 1, 1)
self.label_10 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_10.setObjectName("label_10")
self.gridLayout_5.addWidget(self.label_10, 13, 0, 1, 1)
self.x13 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x13.setObjectName("x13")
self.x13.setFont(font2)
self.gridLayout_5.addWidget(self.x13, 13, 1, 1, 1)
self.label_22 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_22.setObjectName("label_22")
self.gridLayout_5.addWidget(self.label_22, 12, 0, 1, 1)
self.label_28 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_28.setObjectName("label_28")
self.gridLayout_5.addWidget(self.label_28, 14, 0, 1, 1)
self.label_17 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_17.setObjectName("label_17")
self.gridLayout_5.addWidget(self.label_17, 22, 0, 1, 1)
self.x17 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x17.setObjectName("x17")
self.x17.setFont(font2)
self.gridLayout_5.addWidget(self.x17, 17, 1, 1, 1)
self.x22 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x22.setObjectName("x22")
self.x22.setFont(font2)
self.gridLayout_5.addWidget(self.x22, 22, 1, 1, 1)
self.label_18 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_18.setObjectName("label_18")
self.gridLayout_5.addWidget(self.label_18, 23, 0, 1, 1)
self.x24 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x24.setObjectName("x24")
self.x24.setFont(font2)
self.gridLayout_5.addWidget(self.x24, 24, 1, 1, 1)
self.label_24 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_24.setObjectName("label_24")
self.gridLayout_5.addWidget(self.label_24, 25, 0, 1, 1)
self.x25 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x25.setObjectName("x25")
self.x25.setFont(font2)
self.gridLayout_5.addWidget(self.x25, 25, 1, 1, 1)
self.x15 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x15.setObjectName("x15")
self.x15.setFont(font2)
self.gridLayout_5.addWidget(self.x15, 15, 1, 1, 1)
self.label_19 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_19.setObjectName("label_19")
self.gridLayout_5.addWidget(self.label_19, 24, 0, 1, 1)
self.label_13 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_13.setObjectName("label_13")
self.gridLayout_5.addWidget(self.label_13, 18, 0, 1, 1)
self.x23 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x23.setObjectName("x23")
self.x23.setFont(font2)
self.gridLayout_5.addWidget(self.x23, 23, 1, 1, 1)
self.label_25 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_25.setObjectName("label_25")
self.gridLayout_5.addWidget(self.label_25, 26, 0, 1, 1)
self.x18 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x18.setObjectName("x18")
self.x18.setFont(font2)
self.gridLayout_5.addWidget(self.x18, 18, 1, 1, 1)
self.x20 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x20.setObjectName("x20")
self.x20.setFont(font2)
self.gridLayout_5.addWidget(self.x20, 20, 1, 1, 1)
self.x19 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x19.setObjectName("x19")
self.x19.setFont(font2)
self.gridLayout_5.addWidget(self.x19, 19, 1, 1, 1)
self.x26 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x26.setObjectName("x26")
self.x26.setFont(font2)
self.gridLayout_5.addWidget(self.x26, 26, 1, 1, 1)
self.label_32 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_32.setObjectName("label_32")
self.gridLayout_5.addWidget(self.label_32, 17, 0, 1, 1)
self.label_11 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_11.setObjectName("label_11")
self.gridLayout_5.addWidget(self.label_11, 15, 0, 1, 1)
self.label_12 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_12.setObjectName("label_12")
self.gridLayout_5.addWidget(self.label_12, 16, 0, 1, 1)
self.x16 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x16.setObjectName("x16")
self.x16.setFont(font2)
self.gridLayout_5.addWidget(self.x16, 16, 1, 1, 1)
self.x14 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x14.setObjectName("x14")
self.x14.setFont(font2)
self.gridLayout_5.addWidget(self.x14, 14, 1, 1, 1)
self.label_15 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_15.setObjectName("label_15")
self.gridLayout_5.addWidget(self.label_15, 20, 0, 1, 1)
self.label_16 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_16.setObjectName("label_16")
self.gridLayout_5.addWidget(self.label_16, 21, 0, 1, 1)
self.x21 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x21.setObjectName("x21")
self.x21.setFont(font2)
self.gridLayout_5.addWidget(self.x21, 21, 1, 1, 1)
self.label_14 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_14.setObjectName("label_14")
self.gridLayout_5.addWidget(self.label_14, 19, 0, 1, 1)
self.label_33 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_33.setObjectName("label_33")
self.gridLayout_5.addWidget(self.label_33, 30, 0, 1, 1)
self.label_30 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_30.setObjectName("label_30")
self.gridLayout_5.addWidget(self.label_30, 28, 0, 1, 1)
self.label_34 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_34.setObjectName("label_34")
self.gridLayout_5.addWidget(self.label_34, 31, 0, 1, 1)
self.x30 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x30.setObjectName("x30")
self.x30.setFont(font2)
self.gridLayout_5.addWidget(self.x30, 30, 1, 1, 1)
self.x29 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x29.setObjectName("x29")
self.x29.setFont(font2)
self.gridLayout_5.addWidget(self.x29, 29, 1, 1, 1)
self.x28 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x28.setObjectName("x28")
self.x28.setFont(font2)
self.gridLayout_5.addWidget(self.x28, 28, 1, 1, 1)
self.label_29 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_29.setObjectName("label_29")
self.gridLayout_5.addWidget(self.label_29, 27, 0, 1, 1)
self.x27 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x27.setObjectName("x27")
self.x27.setFont(font2)
self.gridLayout_5.addWidget(self.x27, 27, 1, 1, 1)
self.label_31 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_31.setObjectName("label_31")
self.gridLayout_5.addWidget(self.label_31, 29, 0, 1, 1)
self.x31 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
self.x31.setObjectName("x31")
self.x31.setFont(font2)
self.gridLayout_5.addWidget(self.x31, 31, 1, 1, 1)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.gridLayout_4.addWidget(self.scrollArea, 0, 0, 1, 1)
self.tabWidget_2.addTab(self.tab_3, "")
self.tab_4 = QtWidgets.QWidget()
self.tab_4.setObjectName("tab_4")
self.gridLayout_7 = QtWidgets.QGridLayout(self.tab_4)
self.gridLayout_7.setObjectName("gridLayout_7")
self.scrollArea_2 = QtWidgets.QScrollArea(self.tab_4)
self.scrollArea_2.setWidgetResizable(True)
self.scrollArea_2.setObjectName("scrollArea_2")
self.scrollAreaWidgetContents_2 = QtWidgets.QWidget()
self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 152, 115))
self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2")
self.gridLayout_8 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents_2)
self.gridLayout_8.setObjectName("gridLayout_8")
self.line = QtWidgets.QFrame(self.scrollAreaWidgetContents_2)
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.gridLayout_8.addWidget(self.line, 1, 0, 1, 6)
self.label_38 = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)
self.label_38.setObjectName("label_38")
self.gridLayout_8.addWidget(self.label_38, 0, 5, 1, 1)
self.label_37 = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)
self.label_37.setObjectName("label_37")
self.gridLayout_8.addWidget(self.label_37, 0, 4, 1, 1)
self.address_code = QtWidgets.QTextEdit(self.scrollAreaWidgetContents_2)
self.address_code.setObjectName("address_code")
self.address_code.setFont(FONT3)
self.gridLayout_8.addWidget(self.address_code, 2, 0, 1, 6)
self.label_9 = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)
self.label_9.setObjectName("label_9")
self.gridLayout_8.addWidget(self.label_9, 0, 0, 1, 1)
self.label_36 = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)
self.label_36.setObjectName("label_36")
self.gridLayout_8.addWidget(self.label_36, 0, 3, 1, 1)
self.label_35 = QtWidgets.QLabel(self.scrollAreaWidgetContents_2)
self.label_35.setObjectName("label_35")
self.gridLayout_8.addWidget(self.label_35, 0, 2, 1, 1)
self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)
self.gridLayout_7.addWidget(self.scrollArea_2, 0, 1, 1, 1)
self.tabWidget_2.addTab(self.tab_4, "")
self.gridLayout_9.addWidget(self.tabWidget_2, 0, 13, 5, 1)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_9.addItem(spacerItem2, 3, 1, 1, 1)
self.stopbutton = QtWidgets.QPushButton(self.tab_2)
self.stopbutton.setObjectName("stopbutton")
self.gridLayout_9.addWidget(self.stopbutton, 0, 9, 1, 1)
self.dumpbutton = QtWidgets.QPushButton(self.tab_2)
self.dumpbutton.setObjectName("dumpbutton")
self.gridLayout_9.addWidget(self.dumpbutton, 0, 11, 1, 1)
self.stopbutton.setText("Stop")
self.stopbutton.clicked.connect(self.stop)
self.dumpbutton.setText("Dump")
self.dumpbutton.clicked.connect(self.dump)
#self.normalExecution = QtWidgets.QRadioButton(self.tab_2)
#self.normalExecution.setObjectName("normalExecution")
#self.gridLayout_9.addWidget(self.normalExecution, 5, 3, 1, 1)
#self.normalExecution.setChecked(True)
#self.pipeLined = QtWidgets.QRadioButton(self.tab_2)
#self.pipeLined.setObjectName("pipeLined")
#self.gridLayout_9.addWidget(self.pipeLined, 5, 4, 1, 1)
self.panes.addTab(self.tab_2, "")
self.comboBox = QtWidgets.QComboBox(self.tab_2)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("HEXADECIMAL")
self.comboBox.addItem("DECIMAL")
self.comboBox.addItem("ASCII")
self.gridLayout_9.addWidget(self.comboBox, 5, 13 , 1, 1)
self.pipelined_tab = QtWidgets.QWidget()
self.pipelined_tab.setObjectName("pipelined_tab")
self.cycle = QtWidgets.QLabel(self.pipelined_tab)
self.cycle.setGeometry(QtCore.QRect(30, 60, 250, 17))
self.cycle.setObjectName("cycle")
self.cycle.setFont(font4)
self.inst = QtWidgets.QLabel(self.pipelined_tab)
self.inst.setGeometry(QtCore.QRect(30, 30, 250, 17))
self.inst.setObjectName("inst")
self.inst.setFont(font4)
self.cpi = QtWidgets.QLabel(self.pipelined_tab)
self.cpi.setGeometry(QtCore.QRect(30, 90, 250, 17))
self.cpi.setObjectName("cpi")
self.cpi.setFont(font4)
self.data_transfer = QtWidgets.QLabel(self.pipelined_tab)
self.data_transfer.setGeometry(QtCore.QRect(30, 120, 291, 17))
self.data_transfer.setObjectName("data_transfer")
self.data_transfer.setFont(font4)
self.alu = QtWidgets.QLabel(self.pipelined_tab)
self.alu.setGeometry(QtCore.QRect(30, 150, 250, 17))
self.alu.setObjectName("alu")
self.alu.setFont(font4)
self.label_45 = QtWidgets.QLabel(self.pipelined_tab)
self.label_45.setGeometry(QtCore.QRect(30, 180, 250, 17))
self.label_45.setObjectName("label_45")
self.label_45.setFont(font4)
self.label_46 = QtWidgets.QLabel(self.pipelined_tab)
self.label_46.setGeometry(QtCore.QRect(30, 210, 250, 17))
self.label_46.setObjectName("label_46")
self.label_46.setFont(font4)
self.label_47 = QtWidgets.QLabel(self.pipelined_tab)
self.label_47.setGeometry(QtCore.QRect(30, 240, 250, 17))
self.label_47.setObjectName("label_47")
self.label_47.setFont(font4)
self.label_48 = QtWidgets.QLabel(self.pipelined_tab)
self.label_48.setGeometry(QtCore.QRect(30, 270, 250, 17))
self.label_48.setObjectName("label_48")
self.label_48.setFont(font4)
self.label_49 = QtWidgets.QLabel(self.pipelined_tab)
self.label_49.setGeometry(QtCore.QRect(30, 300, 250, 17))
self.label_49.setObjectName("label_49")
self.label_49.setFont(font4)
self.label_50 = QtWidgets.QLabel(self.pipelined_tab)
self.label_50.setGeometry(QtCore.QRect(30, 330, 250, 17))
self.label_50.setObjectName("label_50")
self.label_50.setFont(font4)
self.label_51 = QtWidgets.QLabel(self.pipelined_tab)
self.label_51.setGeometry(QtCore.QRect(30, 360, 291, 17))
self.label_51.setObjectName("label_51")
self.label_51.setFont(font4)
self.lineEdit = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit.setGeometry(QtCore.QRect(350, 20, 113, 25))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setFont(FONT)
self.lineEdit_2 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_2.setGeometry(QtCore.QRect(350, 50, 113, 25))
self.lineEdit_2.setObjectName("lineEdit_2")
self.lineEdit_2.setFont(FONT)
self.lineEdit_3 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_3.setGeometry(QtCore.QRect(350, 80, 113, 25))
self.lineEdit_3.setObjectName("lineEdit_3")
self.lineEdit_3.setFont(FONT)
self.lineEdit_4 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_4.setGeometry(QtCore.QRect(350, 110, 113, 25))
self.lineEdit_4.setObjectName("lineEdit_4")
self.lineEdit_4.setFont(FONT)
self.lineEdit_5 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_5.setGeometry(QtCore.QRect(350, 140, 113, 25))
self.lineEdit_5.setObjectName("lineEdit_5")
self.lineEdit_5.setFont(FONT)
self.lineEdit_6 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_6.setGeometry(QtCore.QRect(350, 170, 113, 25))
self.lineEdit_6.setObjectName("lineEdit_6")
self.lineEdit_6.setFont(FONT)
self.lineEdit_7 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_7.setGeometry(QtCore.QRect(350, 200, 113, 25))
self.lineEdit_7.setObjectName("lineEdit_7")
self.lineEdit_7.setFont(FONT)
self.lineEdit_8 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_8.setGeometry(QtCore.QRect(350, 230, 113, 25))
self.lineEdit_8.setObjectName("lineEdit_8")
self.lineEdit_8.setFont(FONT)
self.lineEdit_13 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_13.setGeometry(QtCore.QRect(350, 350, 113, 25))
self.lineEdit_13.setObjectName("lineEdit_13")
self.lineEdit_13.setFont(FONT)
self.lineEdit_14 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_14.setGeometry(QtCore.QRect(350, 320, 113, 25))
self.lineEdit_14.setObjectName("lineEdit_14")
self.lineEdit_14.setFont(FONT)
self.lineEdit_15 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_15.setGeometry(QtCore.QRect(350, 290, 113, 25))
self.lineEdit_15.setObjectName("lineEdit_15")
self.lineEdit_15.setFont(FONT)
self.lineEdit_16 = QtWidgets.QLineEdit(self.pipelined_tab)
self.lineEdit_16.setGeometry(QtCore.QRect(350, 260, 113, 25))
self.lineEdit_16.setObjectName("lineEdit_16")
self.lineEdit_16.setFont(FONT)
self.piptabwidget = QtWidgets.QTabWidget(self.pipelined_tab)
self.piptabwidget.setGeometry(QtCore.QRect(480, 0,1400, 960))
self.piptabwidget.setObjectName("piptabwidget")
self.executed_info_tab = QtWidgets.QWidget()
self.executed_info_tab.setObjectName("executed_info_tab")
self.textEdit_2 = QtWidgets.QTextEdit(self.executed_info_tab)
self.textEdit_2.setGeometry(QtCore.QRect(3, 9, 1375, 850))
self.textEdit_2.setObjectName("textEdit_2")
self.textEdit_2.setFont(FONT)
# self.textEdit_2.append(f"Cycle number\t\tFetch\t\tDecode\t\tExecute\t\tMemAccess\t\tWriteBack")
self.piptabwidget.addTab(self.executed_info_tab, "")
self.child_tab = QtWidgets.QWidget()
self.child_tab.setObjectName("child_tab")
self.textEdit = QtWidgets.QTextEdit(self.child_tab)
self.textEdit.setGeometry(QtCore.QRect(3, 9, 1375, 850))
self.textEdit.setObjectName("textEdit")
self.textEdit.setFont(FONT)
self.piptabwidget.addTab(self.child_tab, "")
self.panes.addTab(self.pipelined_tab, "")
self.gridLayout.addWidget(self.panes, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1284, 32))
self.menubar.setObjectName("menubar")
self.menu_File = QtWidgets.QMenu(self.menubar)
self.menu_File.setObjectName("menu_File")
self.menu_Edit = QtWidgets.QMenu(self.menubar)
self.menu_Edit.setObjectName("menu_Edit")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.action_New_Project = QtWidgets.QAction(MainWindow)
self.action_New_Project.setObjectName("action_New_Project")
self.action_Open_Project = QtWidgets.QAction(MainWindow)
self.action_Open_Project.setObjectName("action_Open_Project")
self.action_Save_Project = QtWidgets.QAction(MainWindow)
self.action_Save_Project.setObjectName("action_Save_Project")
self.action_Close_Project = QtWidgets.QAction(MainWindow)
self.action_Close_Project.setObjectName("action_Close_Project")
self.action_Undo = QtWidgets.QAction(MainWindow)
self.action_Undo.setObjectName("action_Undo")
self.action_Redo = QtWidgets.QAction(MainWindow)
self.action_Redo.setObjectName("action_Redo")
self.action_Cut = QtWidgets.QAction(MainWindow)
self.action_Cut.setObjectName("action_Cut")
self.action_Copy = QtWidgets.QAction(MainWindow)
self.action_Copy.setObjectName("action_Copy")
self.action_Paste = QtWidgets.QAction(MainWindow)
self.action_Paste.setObjectName("action_Paste")
self.action_Select_All = QtWidgets.QAction(MainWindow)
self.action_Select_All.setObjectName("action_Select_All")
self.action_Save_Project_2 = QtWidgets.QAction(MainWindow)
self.action_Save_Project_2.setObjectName("action_Save_Project_2")
self.menu_File.addAction(self.action_New_Project)
self.menu_File.addAction(self.action_Close_Project)
self.menu_File.addAction(self.action_Save_Project_2)
self.menu_Edit.addAction(self.action_Undo)
self.menu_Edit.addAction(self.action_Redo)
self.menu_Edit.addAction(self.action_Cut)
self.menu_Edit.addAction(self.action_Copy)
self.menu_Edit.addAction(self.action_Paste)
self.menu_Edit.addAction(self.action_Select_All)
self.menubar.addAction(self.menu_File.menuAction())
self.menubar.addAction(self.menu_Edit.menuAction())
self.retranslateUi(MainWindow)
self.panes.setCurrentIndex(0)
self.tabWidget_5.setCurrentIndex(0)
self.tabWidget_2.setCurrentIndex(0)
self.action_Close_Project.triggered.connect(MainWindow.close)
self.action_Select_All.triggered.connect(self.editor_code.selectAll)
self.action_Paste.triggered.connect(self.editor_code.paste)
self.action_Undo.triggered.connect(self.basic_code.undo)
self.action_Cut.triggered.connect(self.basic_code.cut)
self.action_Redo.triggered.connect(self.basic_code.redo)
self.action_Paste.triggered.connect(self.basic_code.paste)
self.action_Select_All.triggered.connect(self.basic_code.selectAll)
self.action_Copy.triggered.connect(self.basic_code.copy)
self.action_Copy.triggered.connect(self.editor_code.copy)
self.action_Undo.triggered.connect(self.editor_code.undo)
self.action_Redo.triggered.connect(self.editor_code.redo)
self.action_Cut.triggered.connect(self.editor_code.cut)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.run.clicked.connect(self.run_buttonclicked)
self.reset.clicked.connect(self.RESET_IT)
self.step.clicked.connect(self.step_buttonclicked)
self.previous.clicked.connect(self.prev_buttonclicked)
#self.asciiradiobutton.clicked.connect(self.ascii_clicked)
#self.hexradiobutton.clicked.connect(self.hex_clicked)
#self.decimalradiobutton.clicked.connect(self.dec_clicked)
self.comboBox.activated[str].connect(self.On_activated)
# self.normalExecution.clicked.connect(self.NORM_EXEC)
# self.pipeLined.clicked.connect(self.PIP_EXEC)
self.panes.currentChanged.connect(self.tabchanged)
self.basic_code.mouseReleaseEvent = self.basiccode_clicked
self.basiccodecursor=self.basic_code.textCursor()
self.gif = QtGui.QMovie("test.gif", QtCore.QByteArray())
self.gif.setCacheMode(QtGui.QMovie.CacheAll)
self.gif.setSpeed(100)
self.label_43.setMovie(self.gif)
self.gif.start()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Apache 2.0"))
self.label_44.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:14pt; color:#f57900;\">DEVELOPERS:</span></p><p><span style=\" font-size:12pt; color:#f57900;\">SACSHAM GUPTA, ABHISHEK KUMAR GUPTA, VUSIRIKALA ABHISHEK,</span></p><p><span style=\" font-size:12pt; color:#f57900;\">STEPHEN SUGUN, TANEESH KAUSHIK</span></p></body></html>"))
self.label_42.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:18pt; font-weight:600; color:#ce5c00;\">APACHE 2.0</span></p><p align=\"center\"><span style=\" font-size:18pt; font-weight:600; color:#ce5c00;\">RISC-V PIPELINED SIMULATOR</span></p></body></html>"))
self.panes.setTabText(self.panes.indexOf(self.tab_8), _translate("MainWindow", "Home"))
self.openfilebutton.setText(_translate("MainWindow", "OPEN FILE FROM COMPUTER"))
self.panes.setTabText(self.panes.indexOf(self.tab), _translate("MainWindow", "Editor"))
self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">PC VALUE:</span></p></body></html>"))
self.previous.setText(_translate("MainWindow", "Previous"))
self.label_39.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600; color:#ce5c00;\"> PC</span></p></body></html>"))
self.run.setText(_translate("MainWindow", "Run"))
self.pc_edit.setText(_translate("MainWindow", "(Current PC value)"))
# self.asciiradiobutton.setText(_translate("MainWindow", "ASCII"))
# self.decimalradiobutton.setText(_translate("MainWindow", "Decimal"))
self.label_41.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600; color:#ce5c00;\">MACHINE CODE</span></p></body></html>"))
self.label_40.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600; color:#ce5c00;\">BASIC CODE</span></p></body></html>"))
self.tabWidget_5.setTabText(self.tabWidget_5.indexOf(self.tab_7), _translate("MainWindow", "Console"))
self.reset.setText(_translate("MainWindow", "Reset"))
self.step.setText(_translate("MainWindow", "Step"))
# self.hexradiobutton.setText(_translate("MainWindow", "Hexadecimal"))
self.label_3.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">sp(x2)</span></p></body></html>"))
self.label_2.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">zero</span></p></body></html>"))
self.label_21.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">ra(x1)</span></p></body></html>"))
self.label_23.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a0(x10)</span></p></body></html>"))
self.label_5.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">t2(x7)</span></p></body></html>"))
self.label_20.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">tp(x4)</span></p></body></html>"))
self.label_26.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">t1(x6)</span></p></body></html>"))
self.label_27.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">gp(x3)</span></p></body></html>"))
self.label_4.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">t0(x5)</span></p></body></html>"))
self.label_7.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s0(x8)</span></p></body></html>"))
self.label_6.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s1(x9)</span></p></body></html>"))
self.label_8.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a1(x11)</span></p></body></html>"))
self.label_10.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a3(x13)</span></p></body></html>"))
self.label_22.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a2(x12)</span></p></body></html>"))
self.label_28.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a4(x14)</span></p></body></html>"))
self.label_17.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s6(x22)</span></p></body></html>"))
self.label_18.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s7(x23)</span></p></body></html>"))
self.label_24.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s9(x25)</span></p></body></html>"))
self.label_19.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s8(x24)</span></p></body></html>"))
self.label_13.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s2(x18)</span></p></body></html>"))
self.label_25.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:12pt;\">s10(x26)</span></p></body></html>"))
self.label_32.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a7(x17)</span></p></body></html>"))
self.label_11.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a5(x15)</span></p></body></html>"))
self.label_12.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">a6(x16)</span></p></body></html>"))
self.label_15.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s4(x20)</span></p></body></html>"))
self.label_16.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s5(x21)</span></p></body></html>"))
self.label_14.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">s3(x19)</span></p></body></html>"))
self.label_33.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">t5(x30)</span></p></body></html>"))
self.label_30.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">t3(x28)</span></p></body></html>"))
self.label_34.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">t6(x31)</span></p></body></html>"))
self.label_29.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:12pt;\">s11(x27)</span></p></body></html>"))
self.label_31.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt;\">t4(x29)</span></p></body></html>"))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_3), _translate("MainWindow", "REGISTERS"))
self.label_38.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:10pt;\">+3</span></p></body></html>"))
self.label_37.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:10pt;\">+2</span></p></body></html>"))
self.label_9.setText(_translate("MainWindow", "<html><head/><body><p align=\"justify\"><span style=\" font-size:10pt;\">Address</span></p></body></html>"))
self.label_36.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:10pt;\">+1</span></p></body></html>"))
self.label_35.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:10pt;\">+0</span></p></body></html>"))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_4), _translate("MainWindow", "MEMORY"))
# self.normalExecution.setText(_translate("MainWindow", "Normal Execution"))
# self.pipeLined.setText(_translate("MainWindow", "Pipelined Execution"))
self.panes.setTabText(self.panes.indexOf(self.tab_2), _translate("MainWindow", "StepByStep-Execution"))
self.cycle.setText(_translate("MainWindow", "Total number of cycles"))
self.inst.setText(_translate("MainWindow", "Total instructions executed"))
self.cpi.setText(_translate("MainWindow", "CPI"))
self.data_transfer.setText(_translate("MainWindow", "Data-transfer instructions executed"))
self.alu.setText(_translate("MainWindow", "ALU instructions executed"))
self.label_45.setText(_translate("MainWindow", "Control instructions executed"))
self.label_46.setText(_translate("MainWindow", "Number of data hazards"))
self.label_47.setText(_translate("MainWindow", "Number of control hazards"))
self.label_48.setText(_translate("MainWindow", "Total Stalls in pipeline"))
self.label_49.setText(_translate("MainWindow", "Stalls due to data hazards"))
self.label_50.setText(_translate("MainWindow", "Stalls due to control hazards"))
self.label_51.setText(_translate("MainWindow", "Branch mispredictions"))
self.piptabwidget.setTabText(self.piptabwidget.indexOf(self.child_tab), _translate("MainWindow", "Branch Info"))
self.piptabwidget.setTabText(self.piptabwidget.indexOf(self.executed_info_tab), _translate("MainWindow", "Executed Info"))
self.panes.setTabText(self.panes.indexOf(self.pipelined_tab), _translate("MainWindow", "PipelinedOutput"))
self.menu_File.setTitle(_translate("MainWindow", "&File"))
self.menu_Edit.setTitle(_translate("MainWindow", "&Edit"))
self.action_New_Project.setText(_translate("MainWindow", "&New Project"))
self.action_New_Project.setShortcut(_translate("MainWindow", "Ctrl+N"))
self.action_Open_Project.setText(_translate("MainWindow", "&Open Project"))
self.action_Save_Project.setText(_translate("MainWindow", "&Save Project"))
self.action_Save_Project.setShortcut(_translate("MainWindow", "Ctrl+S"))
self.action_Close_Project.setText(_translate("MainWindow", "&Close Project"))
self.action_Undo.setText(_translate("MainWindow", "&Undo"))
self.action_Undo.setShortcut(_translate("MainWindow", "Ctrl+Z"))
self.action_Redo.setText(_translate("MainWindow", "&Redo"))
self.action_Redo.setShortcut(_translate("MainWindow", "Ctrl+Shift+Z"))
self.action_Cut.setText(_translate("MainWindow", "&Cut"))
self.action_Cut.setShortcut(_translate("MainWindow", "Ctrl+X"))
self.action_Copy.setText(_translate("MainWindow", "&Copy"))
self.action_Copy.setShortcut(_translate("MainWindow", "Ctrl+C"))
self.action_Paste.setText(_translate("MainWindow", "&Paste"))
self.action_Paste.setShortcut(_translate("MainWindow", "Ctrl+V"))
self.action_Select_All.setText(_translate("MainWindow", "&Select All"))
self.action_Select_All.setShortcut(_translate("MainWindow", "Ctrl+A"))
self.action_Save_Project_2.setText(_translate("MainWindow", "&Save Project"))
def basiccode_clicked(self, event):
#self.basic_code.setTextBackgroundColor(QtCore.Qt.red)
#self.basic_code.setTextBackground(QtCore.Qt.white)
#self.basic_code.setStyleSheet("background-color:rgb(255, 250, 250);")
#num_lines=self.basic_code.document().blockCount()-1
if(self.runflag==1):
return
visiblecursorpos= event.pos()
basiccodecursor = self.editor_code.cursorForPosition (visiblecursorpos)
line= basiccodecursor.blockNumber()
#print(type(line))
if(line == int(PC.PC/4)):
msg=QtWidgets.QMessageBox()
msg.setWindowTitle("Please Refrain")
msg.setText("Please do not set the current instruction"+
"to be executed to be the breakpoint")
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.exec_()
return
if(line == int(self.breakpc/4)):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(line))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25, 25, 25))
cursor.setBlockFormat(format)
self.breakpc=-1
return
for i in range( self.inst_num):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(i))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25, 25, 25))
cursor.setBlockFormat(format)
self.breakpc=line*4
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(line))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(255,204,204))
cursor.setBlockFormat(format)
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(0,255,0))
cursor.setBlockFormat(format)
#lineblock =basiccodecursor.blockFormat()
#lineblock.setBackground(QtGui.QBrush(QtCore.Qt.yellow))
#basiccodecursor.setBlockFormat(lineblock)
#selection= self.basic_code.ExtraSelection()
#lineColor = QtGui.QColor(QtCore.Qt.yellow).lighter(160)
#selection.format.setBackground(lineColor)
#self.basic_code.setStyleSheet("background-color: rgb(255, 255, 255)")
return
# knob=0
choice=0
#def NORM_EXEC(self):
# self.knob =0
#def PIP_EXEC(self):
# self.knob =1
# def hex_clicked(self):
# if(self.runflag==1):
# return
# self.choice=0
# self.CURRENT_VAL()
# #print(self.choice)
# def dec_clicked(self):
# if(self.runflag==1):
# return
# self.choice=1
# self.CURRENT_VAL()
# #print(self.choice)
# def ascii_clicked(self):
# if(self.runflag==1):
# return
# self.choice=2
# self.CURRENT_VAL()
# #print(self.choice)
def On_activated(self,text):
if(self.runflag ==1):
return
if text == "HEXADECIMAL":
self.choice=0
elif text == "DECIMAL":
self.choice=1
else:
self.choice=2
self.CURRENT_VAL()
def tabchanged(self):
configme.breakflag=1
self.runflag=0
currindex=self.panes.currentIndex()
if(currindex==2):
editorcodefile=open("codefromeditor.txt", 'w+')
editorcode=self.editor_code.toPlainText()
editorcodefile.write(editorcode)
editorcodefile.close()
#errormessage, errorline= error_detection.main()
error, errorline = error_detector_unit.main() # number of line to be colored : errorline, error: msg
error=error.strip()
num=self.editor_code.document().blockCount()
if(error!="noerror"):
self.panes.setCurrentIndex(1)
# for i in range(num):
# cursor=QtGui.QTextCursor(self.editor_code.document().findBlockByNumber(i))
# format=QtGui.QTextBlockFormat()
# format.setBackground(QColor(25,25,25))
# cursor.setBlockFormat(format)
# cursor=QtGui.QTextCursor(self.editor_code.document().findBlockByNumber(errorline))
# format=QtGui.QTextBlockFormat()
# format.setBackground(QColor(255,255,204))
# cursor.setBlockFormat(format)
msg=QtWidgets.QMessageBox()
msg.setWindowTitle(f"Error in command {errorline}")
msg.setText(error)
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.exec_()
return
if(error=="noerror"):
for i in range(num):
cursor=QtGui.QTextCursor(self.editor_code.document().findBlockByNumber(i))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25,25,25))
cursor.setBlockFormat(format)
BASIC_code.main()
parsedfile = open("BasicCode.txt",'r')
parsedcodelines = parsedfile.readlines()
#print(parsedcodelines)
parsedfile.close()
self.GEN_MC()
mcfile= open("MachineCode.txt", 'r')
mc_codelines=mcfile.readlines()
mcfile.close()
#print(mc_codelines)
#print(len(mc_codelines))
#print("len")
#print(len(mc_codelines))
if self.basic_code.toPlainText()=="":
fg=""
for idf in range(len(mc_codelines)):
if mc_codelines[idf] == '\n':
fg = mc_codelines[idf + 2:]
break
for i in range(len(parsedcodelines)):
x=hex(i*4)
y = fg[i].find(' ')
y = fg[i][y+1:].rstrip()
#z=(str(x)+" "+parsedcodelines[i].rstrip()+" "+mc_codelines[i+2].rstrip())
#if len()>12
z = " "+x+"\t\t\t\t"+parsedcodelines[i].rstrip()+"\t\t\t\t"+y
self.basic_code.append(z)
num_lines=self.basic_code.document().blockCount()
self.inst_num=num_lines
self.endpc=self.inst_num*4
self.steppointer=0
self.breakpoint=-1
self.breakpc=-1
for i in range(num_lines):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(i))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25, 25, 25))
cursor.setBlockFormat(format)
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int((PC.PC)/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(204,255,153))
cursor.setBlockFormat(format)
#if self.knob==0:
Commander_normal.initializereg()
#elif self.knob==1:
# PipCommander.initializereg()
self.CURRENT_VAL()
file = QtCore.QFile('Memory_file.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.address_code.setText(stream.readAll())
file.close()
return
if currindex == 3:
configme.breakflag = 0
editorcodefile=open("codefromeditor.txt", 'w+')
editorcode=self.editor_code.toPlainText()
editorcodefile.write(editorcode)
editorcodefile.close()
#errormessage, errorline= error_detection.main()
error, errorline = error_detector_unit.main() # number of line to be colored : errorline, error: msg
error=error.strip()
num=self.editor_code.document().blockCount()
if(error!="noerror"):
self.panes.setCurrentIndex(1)
msg=QtWidgets.QMessageBox()
msg.setWindowTitle(f"Error in command {errorline}")
msg.setText(error)
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.exec_()
return
if(error=="noerror"):
for i in range(num):
cursor=QtGui.QTextCursor(self.editor_code.document().findBlockByNumber(i))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25,25,25))
cursor.setBlockFormat(format)
# exec(open(r"mcgenerator.py").read()) # generate the machine code into mc file
BASIC_code.main()
self.GEN_MC()
PipCommander.run_button()
self.PIP_OUT()
return
if(currindex==1 or currindex==0):
configme.breakflag=1
self.runflag=0
self.console.clear()
self.basic_code.clear()
self.mcgenflag=0
self.runflag=0
self.inst_num=0
self.steppointer=0
self.breakpoint=-1
self.RESET_IT()
#palle= self.basic_code.palette();
#color= QtCore.Qt.green
#palle.setColor(QtGui.QPalette.base, color)
#self.basic_code.setPalette(palle);
return
def dialogopener(self):
filename=QtWidgets.QFileDialog.getOpenFileName(None, 'Open File' '/home/COAProject')
if(filename[0]):
file= open(filename[0], 'r')
text=file.read()
self. editor_code.setText(text)
file.close()
return
########################
def GEN_MC(self):
# Click Generate Machine Code Button
file= open(r"mcgenerator.py",'r')
mcgen_code=file.read()
exec(mcgen_code)
file.close()
file = QtCore.QFile('Memory_file.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.address_code.setText(stream.readAll())
file.close()
#file = QtCore.QFile('MachineCode.txt')
#file.open(QtCore.QIODevice.ReadOnly)
#stream = QtCore.QTextStream(file)
#self.machine_code.setText(stream.readAll())
#file.close()
#file2 = QtCore.QFile('BasicCode.txt')
#file2.open(QtCore.QIODevice.ReadOnly)
#stream2 = QtCore.QTextStream(file2)
#self.basic_code.setText(stream2.readAll())
#file2.close()
#if self.knob==0:
Commander_normal.initializereg()
#elif self.knob==1:
#PipCommander.initializereg()
self.CURRENT_VAL()
def run_buttonclicked(self):
if(self.runflag==1):
return
configme.breakflag=0
if(PC.PC==self.endpc):
msg=QtWidgets.QMessageBox()
msg.setWindowTitle("Please Refrain")
msg.setText("ALL INSTRUCTIONS HAVE BEEN RUN")
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.exec_()
return
if(self.breakpc==-1):
self.runflag=1
#runthread=threading.Thread(target=self.RUN_IT)
#runthread.start()
self.RUN_IT()
#print("hskfh")
#print("aslkfjflsajfaslkfjaslk;fjsalkfjlskfjlskdaf")
for i in range(self.inst_num):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(i))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25, 25, 25))
cursor.setBlockFormat(format)
self.breakpc=-1
if(PC.PC<self.endpc):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(204,255,153))
cursor.setBlockFormat(format)
self.runflag=0
#return
elif(self.breakpc!=-1):
#print("hello")
self.runflag=1
while(PC.PC!=self.breakpc and PC.PC!=self.endpc and configme.breakflag==0):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25, 25, 25))
cursor.setBlockFormat(format)
self.STEP_IT()
QApplication.processEvents()
if(PC.PC==self.endpc):
break
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(204,255,153))
cursor.setBlockFormat(format)
QApplication.processEvents()
self.breakpc=-1
self.runflag=0
file = QtCore.QFile('Console.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.console.setText(stream.readAll())
file.close()
def stop(self):
configme.breakflag=1
self.runflag=0
if(PC.PC<self.endpc):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(204,255,153))
cursor.setBlockFormat(format)
return
def dump(self):
if(self.runflag==1):
return
#print("helo")
mcfile=open("MachineCode.txt",'r')
mclines=mcfile.readlines()
mcfile.close()
self.console.clear()
# self.console.append("\n")
for idf in range(len(mclines)):
if mclines[idf] == '\n':
fg = mclines[idf+2:]
break
for i in range(self.inst_num):
self.console.append(fg[i].rstrip())
return
def step_buttonclicked(self):
#if self.knob==1:
# return
if(self.runflag==1):
return
# if(self.runflag==1):
# msg=QtWidgets.QMessageBox()
# msg.setWindowTitle("Jyada Tez Mat chal")
# msg.setText("Beta pehle hi saara run kar chuka hoon")
# msg.setIcon(QtWidgets.QMessageBox.Critical)
# msg.exec_()
# return
if(PC.PC<self.endpc):
#print(PC.PC)
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25, 25, 25))
cursor.setBlockFormat(format)
self.STEP_IT()
if(PC.PC<self.endpc):
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(204,255,153))
cursor.setBlockFormat(format)
else:
msg=QtWidgets.QMessageBox()
msg.setWindowTitle("PLEASE REFRAIN!")
msg.setText("All instructions have been executed")
msg.setIcon(QtWidgets.QMessageBox.Critical)
msg.exec_()
file = QtCore.QFile('Console.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.console.setText(stream.readAll())
file.close()
def prev_buttonclicked(self):
#if self.knob ==1:
# return
if(self.runflag==1):
return
if(PC.PC==0):
return
else:
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(25, 25, 25))
cursor.setBlockFormat(format)
self.PREV_IT()
cursor=QtGui.QTextCursor(self.basic_code.document().findBlockByNumber(int(PC.PC/4)))
format=QtGui.QTextBlockFormat()
format.setBackground(QColor(255,204,255))
cursor.setBlockFormat(format)
file = QtCore.QFile('Console.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.console.setText(stream.readAll())
file.close()
def RUN_IT(self): # Click Run Button
#print("in runit")
#if self.knob==0:
Commander_normal.run_button()
#elif self.knob==1:
# PipCommander.run_button()
# self.PIP_OUT()
self.CURRENT_VAL()
file = QtCore.QFile('Memory_file.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.address_code.setText(stream.readAll())
file.close()
self.runflag=0
return
def PIP_OUT(self):
if self.editor_code.toPlainText() != "":
self.lineEdit.setText(str(PipCommander.instructions_executed))
self.lineEdit_2.setText(str(PipCommander.cycles))
if PipCommander.instructions_executed==0: ghf=0.0
elif PipCommander.instructions_executed>0: ghf="{:.2f}".format(PipCommander.cycles/PipCommander.instructions_executed)
self.lineEdit_3.setText(str(ghf))
self.lineEdit_4.setText(str(PipCommander.executed_information.data_transfer_instructs))
self.lineEdit_5.setText(str(PipCommander.executed_information.alu_instructs))
self.lineEdit_6.setText(str(PipCommander.executed_information.control_instructs))
self.lineEdit_7.setText(str(PipCommander.executed_information.data_hazards))
self.lineEdit_8.setText(str(PipCommander.executed_information.control_hazards))
self.lineEdit_13.setText(str(PipCommander.executed_information.branch_mispredicts))
self.lineEdit_14.setText(str(PipCommander.executed_information.stalls_control_hzs))
self.lineEdit_15.setText(str(PipCommander.executed_information.stalls_data_hazs))
self.lineEdit_16.setText(str(PipCommander.stalls))
self.textEdit.setText("We have stored Branch-To Address for conditional as well as unconditional jump\n")
self.textEdit.append("Branch To Address")
self.textEdit.append(str(PipCommander.executed_information.branch_child))
self.textEdit.append("\nBranch Taken (Final value of 1-bit Branch predictor)")
self.textEdit.append(str(PipCommander.executed_information.branch_taken))
self.textEdit.append(f"\n\nRegisters having non-zero value finally:\n")
for dfhj in range(32):
if register_file.reg_address_to_value[dfhj]: self.textEdit.append(f"x{dfhj}: {hex(register_file.reg_address_to_value[dfhj])}")
self.textEdit.append(f'\n\n')
file = QtCore.QFile('Memory_file.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.textEdit.append(stream.readAll())
file.close()
self.textEdit_2.setText(f"Numbers represent: instruction number\n\nCycle number\t\tFetch\t\tDecode\t\tExecute\t\tMemAccess\tWriteBack")
xf = 0
xd = -1
xe = -2
xm = -3
xw = -4
x=0
for i in executed_information.executed_info:
x += 1
if i[0]<0 and x>2: self.textEdit_2.append(f"{x}\t\t\t--------------------------STALL----------------------------(M-E stall)")
elif i[1]==-3 and not(23<=i[0]<=26): self.textEdit_2.append(f"{x}\t\t\t--------------------------STALL----------------------------(E-D/M-D stall)")
elif i[1]==-3 and 23<=i[0]<=26 and i[3]==-1: self.textEdit_2.append(f"{x}\t\t\t--------------------------STALL----------------------------(E-D/M-D stall)")
elif i[1]==-47: self.textEdit_2.append(f"{x}\t\t\t--------------------------STALL----------------------------(branch-mispredict/cond jump)")
else:
xf += 1
xd += 1
xe += 1
xm += 1
xw += 1
if xf==1: self.textEdit_2.append(f"{x}\t\t\t1")
elif xd==1: self.textEdit_2.append(f"{x}\t\t\t2\t\t1")
elif xe==1: self.textEdit_2.append(f"{x}\t\t\t3\t\t2\t\t1")
elif xm==1: self.textEdit_2.append(f"{x}\t\t\t4\t\t3\t\t2\t\t1")
elif xw==1: self.textEdit_2.append(f"{x}\t\t\t5\t\t4\t\t3\t\t2\t\t1")
elif xw==PipCommander.instructions_executed: self.textEdit_2.append(f"{x}\t\t\t\t\t\t\t\t\t\t\t{xw}")
elif xm==PipCommander.instructions_executed: self.textEdit_2.append(f"{x}\t\t\t\t\t\t\t\t\t{xm}\t\t{xw}")
elif xe==PipCommander.instructions_executed: self.textEdit_2.append(f"{x}\t\t\t\t\t\t\t{xe}\t\t{xm}\t\t{xw}")
elif xd==PipCommander.instructions_executed: self.textEdit_2.append(f"{x}\t\t\t\t\t{xd}\t\t{xe}\t\t{xm}\t\t{xw}")
else: self.textEdit_2.append(f"{x}\t\t\t{xf}\t\t{xd}\t\t{xe}\t\t{xm}\t\t{xw}")
else:
self.textEdit.clear()
self.textEdit_2.clear()
self.textEdit_2.setText(f"Numbers represent: instruction number\n\nCycle number\t\tFetch\t\tDecode\t\tExecute\t\tMemAccess\tWriteBack")
self.textEdit.setText("We have stored Branch-To Address for conditional as well as unconditional jump\n")
self.lineEdit.setText("0")
self.lineEdit_2.setText("0")
self.lineEdit_3.setText("0.0")
self.lineEdit_4.setText("0")
self.lineEdit_5.setText("0")
self.lineEdit_6.setText("0")
self.lineEdit_7.setText("0")
self.lineEdit_8.setText("0")
self.lineEdit_13.setText("0")
self.lineEdit_14.setText("0")
self.lineEdit_15.setText("0")
self.lineEdit_16.setText("0")
def CURRENT_VAL(self):
if self.choice==0:
self.x0.setText(hex(register_file.load_from_register(0)))
self.x1.setText(hex(register_file.load_from_register(1)))
self.x2.setText(hex(register_file.load_from_register(2)))
self.x3.setText(hex(register_file.load_from_register(3)))
self.x4.setText(hex(register_file.load_from_register(4)))
self.x5.setText(hex(register_file.load_from_register(5)))
self.x6.setText(hex(register_file.load_from_register(6)))
self.x7.setText(hex(register_file.load_from_register(7)))
self.x8.setText(hex(register_file.load_from_register(8)))
self.x9.setText(hex(register_file.load_from_register(9)))
self.x10.setText(hex(register_file.load_from_register(10)))
self.x11.setText(hex(register_file.load_from_register(11)))
self.x12.setText(hex(register_file.load_from_register(12)))
self.x13.setText(hex(register_file.load_from_register(13)))
self.x14.setText(hex(register_file.load_from_register(14)))
self.x15.setText(hex(register_file.load_from_register(15)))
self.x16.setText(hex(register_file.load_from_register(16)))
self.x17.setText(hex(register_file.load_from_register(17)))
self.x18.setText(hex(register_file.load_from_register(18)))
self.x19.setText(hex(register_file.load_from_register(19)))
self.x20.setText(hex(register_file.load_from_register(20)))
self.x21.setText(hex(register_file.load_from_register(21)))
self.x22.setText(hex(register_file.load_from_register(22)))
self.x23.setText(hex(register_file.load_from_register(23)))
self.x24.setText(hex(register_file.load_from_register(24)))
self.x25.setText(hex(register_file.load_from_register(25)))
self.x26.setText(hex(register_file.load_from_register(26)))
self.x27.setText(hex(register_file.load_from_register(27)))
self.x28.setText(hex(register_file.load_from_register(28)))
self.x29.setText(hex(register_file.load_from_register(29)))
self.x30.setText(hex(register_file.load_from_register(30)))
self.x31.setText(hex(register_file.load_from_register(31)))
self.pc_edit.setText(hex(PC.PC))
elif self.choice==1:
self.x0.setText(str(int (register_file.load_from_register(0))))
self.x1.setText(str(int (register_file.load_from_register(1))))
self.x2.setText(str(int (register_file.load_from_register(2))))
self.x3.setText(str(int (register_file.load_from_register(3))))
self.x4.setText(str(int (register_file.load_from_register(4))))
self.x5.setText(str(int (register_file.load_from_register(5))))
self.x6.setText(str(int (register_file.load_from_register(6))))
self.x7.setText(str(int (register_file.load_from_register(7))))
self.x8.setText(str(int (register_file.load_from_register(8))))
self.x9.setText(str(int (register_file.load_from_register(9))))
self.x10.setText(str(int (register_file.load_from_register(10))))
self.x11.setText(str(int (register_file.load_from_register(11))))
self.x12.setText(str(int (register_file.load_from_register(12))))
self.x13.setText(str(int (register_file.load_from_register(13))))
self.x14.setText(str(int (register_file.load_from_register(14))))
self.x15.setText(str(int (register_file.load_from_register(15))))
self.x16.setText(str(int (register_file.load_from_register(16))))
self.x17.setText(str(int (register_file.load_from_register(17))))
self.x18.setText(str(int (register_file.load_from_register(18))))
self.x19.setText(str(int (register_file.load_from_register(19))))
self.x20.setText(str(int (register_file.load_from_register(20))))
self.x21.setText(str(int (register_file.load_from_register(21))))
self.x22.setText(str(int (register_file.load_from_register(22))))
self.x23.setText(str(int (register_file.load_from_register(23))))
self.x24.setText(str(int (register_file.load_from_register(24))))
self.x25.setText(str(int (register_file.load_from_register(25))))
self.x26.setText(str(int (register_file.load_from_register(26))))
self.x27.setText(str(int (register_file.load_from_register(27))))
self.x28.setText(str(int (register_file.load_from_register(28))))
self.x29.setText(str(int (register_file.load_from_register(29))))
self.x30.setText(str(int (register_file.load_from_register(30))))
self.x31.setText(str(int (register_file.load_from_register(31))))
self.pc_edit.setText(str(int (PC.PC)))
elif self.choice ==2:
if register_file.load_from_register(0)in range(32,127):
self.x0.setText(chr(register_file.load_from_register(0)))
else: self.x0.setText(hex(register_file.load_from_register(0)))
if register_file.load_from_register(1)in range(32,127):
self.x1.setText(chr(register_file.load_from_register(1)))
else: self.x1.setText(hex(register_file.load_from_register(1)))
if register_file.load_from_register(2)in range(32,127):
self.x2.setText(chr(register_file.load_from_register(2)))
else: self.x2.setText(hex(register_file.load_from_register(2)))
if register_file.load_from_register(3)in range(32,127):
self.x3.setText(chr(register_file.load_from_register(3)))
else: self.x3.setText(hex(register_file.load_from_register(3)))
if register_file.load_from_register(4)in range(32,127):
self.x4.setText(chr(register_file.load_from_register(4)))
else: self.x4.setText(hex(register_file.load_from_register(4)))
if register_file.load_from_register(5)in range(32,127):
self.x5.setText(chr(register_file.load_from_register(5)))
else: self.x5.setText(hex(register_file.load_from_register(5)))
if register_file.load_from_register(6)in range(32,127):
self.x6.setText(chr(register_file.load_from_register(6)))
else: self.x6.setText(hex(register_file.load_from_register(6)))
if register_file.load_from_register(7)in range(32,127):
self.x7.setText(chr(register_file.load_from_register(7)))
else: self.x7.setText(hex(register_file.load_from_register(7)))
if register_file.load_from_register(8)in range(32,127):
self.x8.setText(chr(register_file.load_from_register(8)))
else: self.x8.setText(hex(register_file.load_from_register(8)))
if register_file.load_from_register(9)in range(32,127):
self.x9.setText(chr(register_file.load_from_register(9)))
else: self.x9.setText(hex(register_file.load_from_register(9)))
if register_file.load_from_register(10)in range(32,127):
self.x10.setText(chr(register_file.load_from_register(10)))
else: self.x10.setText(hex(register_file.load_from_register(10)))
if register_file.load_from_register(11)in range(32,127):
self.x11.setText(chr(register_file.load_from_register(11)))
else: self.x11.setText(hex(register_file.load_from_register(11)))
if register_file.load_from_register(12)in range(32,127):
self.x12.setText(chr(register_file.load_from_register(12)))
else: self.x12.setText(hex(register_file.load_from_register(12)))
if register_file.load_from_register(13)in range(32,127):
self.x13.setText(chr(register_file.load_from_register(13)))
else: self.x13.setText(hex(register_file.load_from_register(13)))
if register_file.load_from_register(14)in range(32,127):
self.x14.setText(chr(register_file.load_from_register(14)))
else: self.x14.setText(hex(register_file.load_from_register(14)))
if register_file.load_from_register(15)in range(32,127):
self.x15.setText(chr(register_file.load_from_register(15)))
else: self.x15.setText(hex(register_file.load_from_register(15)))
if register_file.load_from_register(16)in range(32,127):
self.x16.setText(chr(register_file.load_from_register(16)))
else: self.x16.setText(hex(register_file.load_from_register(16)))
if register_file.load_from_register(17)in range(32,127):
self.x17.setText(chr(register_file.load_from_register(17)))
else: self.x17.setText(hex(register_file.load_from_register(17)))
if register_file.load_from_register(18)in range(32,127):
self.x18.setText(chr(register_file.load_from_register(18)))
else: self.x18.setText(hex(register_file.load_from_register(18)))
if register_file.load_from_register(19)in range(32,127):
self.x19.setText(chr(register_file.load_from_register(19)))
else: self.x19.setText(hex(register_file.load_from_register(19)))
if register_file.load_from_register(20)in range(32,127):
self.x20.setText(chr(register_file.load_from_register(20)))
else: self.x20.setText(hex(register_file.load_from_register(20)))
if register_file.load_from_register(21)in range(32,127):
self.x21.setText(chr(register_file.load_from_register(21)))
else: self.x21.setText(hex(register_file.load_from_register(21)))
if register_file.load_from_register(22)in range(32,127):
self.x22.setText(chr(register_file.load_from_register(22)))
else: self.x22.setText(hex(register_file.load_from_register(22)))
if register_file.load_from_register(23)in range(32,127):
self.x23.setText(chr(register_file.load_from_register(23)))
else: self.x23.setText(hex(register_file.load_from_register(23)))
if register_file.load_from_register(24)in range(32,127):
self.x24.setText(chr(register_file.load_from_register(24)))
else: self.x24.setText(hex(register_file.load_from_register(24)))
if register_file.load_from_register(25)in range(32,127):
self.x25.setText(chr(register_file.load_from_register(25)))
else: self.x25.setText(hex(register_file.load_from_register(25)))
if register_file.load_from_register(26)in range(32,127):
self.x26.setText(chr(register_file.load_from_register(26)))
else: self.x26.setText(hex(register_file.load_from_register(26)))
if register_file.load_from_register(27)in range(32,127):
self.x27.setText(chr(register_file.load_from_register(27)))
else: self.x27.setText(hex(register_file.load_from_register(27)))
if register_file.load_from_register(28)in range(32,127):
self.x28.setText(chr(register_file.load_from_register(28)))
else: self.x28.setText(hex(register_file.load_from_register(28)))
if register_file.load_from_register(29)in range(32,127):
self.x29.setText(chr(register_file.load_from_register(29)))
else: self.x29.setText(hex(register_file.load_from_register(29)))
if register_file.load_from_register(30)in range(32,127):
self.x30.setText(chr(register_file.load_from_register(30)))
else: self.x30.setText(hex(register_file.load_from_register(30)))
if register_file.load_from_register(31)in range(32,127):
self.x31.setText(chr(register_file.load_from_register(31)))
else: self.x31.setText(hex(register_file.load_from_register(31)))
self.pc_edit.setText(hex(PC.PC))
def STEP_IT(self):
Commander_normal.step_button()
self.CURRENT_VAL()
file = QtCore.QFile('Memory_file.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.address_code.setText(stream.readAll())
file.close()
def RESET_IT(self): # Click Reset Button Please check once if the reset is fine
self.runflag=0
configme.breakflag=1
#if self.knob ==0:
Commander_normal.initializereg()
#elif self.knob ==1:
# PipCommander.initializereg()
self.CURRENT_VAL()
self.basic_code.clear()
self.console.clear()
self.address_code.clear()
PC.PC=0
def PREV_IT(self):
Commander_normal.previous_button()
self.CURRENT_VAL()
file = QtCore.QFile('Memory_file.txt')
file.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file)
self.address_code.setText(stream.readAll())
file.close()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
palette = QtGui.QPalette()
palette.setColor(QPalette.Window, QColor(0,0,0))
#palette.setColor(QPalette.Background,QColor(0,0,0))
palette.setColor(QPalette.WindowText, QColor(0,159,255)) ######
palette.setColor(QPalette.Base, QColor(25, 25, 25))
palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
palette.setColor(QPalette.ToolTipBase, Qt.white)
palette.setColor(QPalette.ToolTipText, Qt.white)
palette.setColor(QPalette.Text, QColor(255,128,0))
palette.setColor(QPalette.Button, QColor(0, 0, 0))
palette.setColor(QPalette.ButtonText,QColor(0,159,255) ) ########
palette.setColor(QPalette.BrightText, Qt.red)
palette.setColor(QPalette.Link, QColor(42, 130, 218))
palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
palette.setColor(QPalette.HighlightedText, Qt.black)
app.setPalette(palette)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.showMinimized()
sys.exit(app.exec_())
|
tableau=[1,1,0,0,1,0,0,0,1]
grpe_nul=0
for compteur in range(len(tableau)) :
if tableau[compteur]==0 :
grpe_nul+=1
else :
grpe_nul_maxi,grpe_nul=grpe_nul,0
print("Le plus long groupe d'éléments nuls est de",grpe_nul_maxi)
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
Renames svg, jpg, and png files, removing the ID-number at the end of the filename
"""
from __future__ import print_function
import os
def new_name(name):
base_name, extension = os.path.splitext(name)
parts = base_name.split('_')
if parts[-1].isdigit():
return True, '_'.join(parts[:-1]) + extension
return False, name
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
def main():
# base counter
fr = 0
# listing directory content
for name in os.listdir('.'):
name_fpath = os.path.abspath(name)
# avoid dirs and fiter by extension
if os.path.isfile(name) and os.path.splitext(name)[-1] in ['.jpg', '.png', '.svg']:
res, newn = new_name(name)
if res:
os.rename(name, newn)
fr += 1
print(" {} files renamed".format(fr))
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
if __name__ == '__main__':
main()
|
# 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.
from oslo_config import cfg
from keystone.conf import utils
_DEPRECATE_DII_MSG = utils.fmt("""
The option to set domain_id_immutable to false has been deprecated in the M
release and will be removed in the O release.
""")
admin_token = cfg.StrOpt(
'admin_token',
secret=True,
default=None,
help=utils.fmt("""
A "shared secret" that can be used to bootstrap Keystone. This "token" does not
represent a user, and carries no explicit authorization. If set to `None`, the
value is ignored and the `admin_token` log in mechanism is effectively
disabled. To completely disable `admin_token` in production (highly
recommended), remove AdminTokenAuthMiddleware from your paste application
pipelines (for example, in keystone-paste.ini).
"""))
public_endpoint = cfg.StrOpt(
'public_endpoint',
help=utils.fmt("""
The base public endpoint URL for Keystone that is advertised to clients (NOTE:
this does NOT affect how Keystone listens for connections). Defaults to the
base host URL of the request. E.g. a request to http://server:5000/v3/users
will default to http://server:5000. You should only need to set this value if
the base URL contains a path (e.g. /prefix/v3) or the endpoint should be found
on a different server.
"""))
admin_endpoint = cfg.StrOpt(
'admin_endpoint',
help=utils.fmt("""
The base admin endpoint URL for Keystone that is advertised to clients (NOTE:
this does NOT affect how Keystone listens for connections). Defaults to the
base host URL of the request. E.g. a request to http://server:35357/v3/users
will default to http://server:35357. You should only need to set this value if
the base URL contains a path (e.g. /prefix/v3) or the endpoint should be found
on a different server.
"""))
max_project_tree_depth = cfg.IntOpt(
'max_project_tree_depth',
default=5,
help=utils.fmt("""
Maximum depth of the project hierarchy, excluding the project acting as a
domain at the top of the hierarchy. WARNING: setting it to a large value may
adversely impact performance.
"""))
max_param_size = cfg.IntOpt(
'max_param_size',
default=64,
help=utils.fmt("""
Limit the sizes of user & project ID/names.
"""))
# we allow tokens to be a bit larger to accommodate PKI
max_token_size = cfg.IntOpt(
'max_token_size',
default=8192,
help=utils.fmt("""
Similar to max_param_size, but provides an exception for token values.
"""))
member_role_id = cfg.StrOpt(
'member_role_id',
default='9fe2ff9ee4384b1894a90878d3e92bab',
help=utils.fmt("""
Similar to the member_role_name option, this represents the default role ID
used to associate users with their default projects in the v2 API. This will be
used as the explicit role where one is not specified by the v2 API.
"""))
member_role_name = cfg.StrOpt(
'member_role_name',
default='_member_',
help=utils.fmt("""
This is the role name used in combination with the member_role_id option; see
that option for more detail.
"""))
# NOTE(lbragstad/morganfainberg): This value of 10k was measured as having an
# approximate 30% clock-time savings over the old default of 40k. The passlib
# default is not static and grows over time to constantly approximate ~300ms of
# CPU time to hash; this was considered too high. This value still exceeds the
# glibc default of 5k.
crypt_strength = cfg.IntOpt(
'crypt_strength',
default=10000,
min=1000,
max=100000,
help=utils.fmt("""
The value passed as the keyword "rounds" to passlib\'s encrypt method.
"""))
list_limit = cfg.IntOpt(
'list_limit',
help=utils.fmt("""
The maximum number of entities that will be returned in a collection, with no
limit set by default. This global limit may be then overridden for a specific
driver, by specifying a list_limit in the appropriate section (e.g.
[assignment]).
"""))
domain_id_immutable = cfg.BoolOpt(
'domain_id_immutable',
default=True,
deprecated_for_removal=True,
deprecated_reason=_DEPRECATE_DII_MSG,
help=utils.fmt("""
Set this to false if you want to enable the ability for user, group and project
entities to be moved between domains by updating their domain_id. Allowing such
movement is not recommended if the scope of a domain admin is being restricted
by use of an appropriate policy file (see policy.v3cloudsample as an example).
This ability is deprecated and will be removed in a future release.
"""))
strict_password_check = cfg.BoolOpt(
'strict_password_check',
default=False,
help=utils.fmt("""
If set to true, strict password length checking is performed for password
manipulation. If a password exceeds the maximum length, the operation will fail
with an HTTP 403 Forbidden error. If set to false, passwords are automatically
truncated to the maximum length.
"""))
secure_proxy_ssl_header = cfg.StrOpt(
'secure_proxy_ssl_header',
default='HTTP_X_FORWARDED_PROTO',
deprecated_for_removal=True,
deprecated_reason=utils.fmt("""
Use http_proxy_to_wsgi middleware configuration instead.
"""),
help=utils.fmt("""
The HTTP header used to determine the scheme for the original request, even if
it was removed by an SSL terminating proxy.
"""))
insecure_debug = cfg.BoolOpt(
'insecure_debug',
default=False,
help=utils.fmt("""
If set to true the server will return information in the response that may
allow an unauthenticated or authenticated user to get more information than
normal, such as why authentication failed. This may be useful for debugging but
is insecure.
"""))
default_publisher_id = cfg.StrOpt(
'default_publisher_id',
help=utils.fmt("""
Default publisher_id for outgoing notifications
"""))
notification_format = cfg.StrOpt(
'notification_format',
default='basic',
choices=['basic', 'cadf'],
help=utils.fmt("""
Define the notification format for Identity Service events. A "basic"
notification has information about the resource being operated on. A "cadf"
notification has the same information, as well as information about the
initiator of the event.
"""))
notification_opt_out = cfg.MultiStrOpt(
'notification_opt_out',
default=[],
help=utils.fmt("""
Define the notification options to opt-out from. The value expected is:
identity.<resource_type>.<operation>. This field can be set multiple times in
order to add more notifications to opt-out from. For example:
notification_opt_out=identity.user.create
notification_opt_out=identity.authenticate.success
"""))
GROUP_NAME = 'DEFAULT'
ALL_OPTS = [
admin_token,
public_endpoint,
admin_endpoint,
max_project_tree_depth,
max_param_size,
max_token_size,
member_role_id,
member_role_name,
crypt_strength,
list_limit,
domain_id_immutable,
strict_password_check,
secure_proxy_ssl_header,
insecure_debug,
default_publisher_id,
notification_format,
notification_opt_out,
]
def register_opts(conf):
conf.register_opts(ALL_OPTS)
def list_opts():
return {GROUP_NAME: ALL_OPTS}
|
import numpy as np
import matplotlib.pyplot as plt
N = 6
accident_means = (520, 580, 490, 405, 550, 480)
accident_std = (2, 3, 4, 1, 2, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, accident_means, width, color='r', yerr=accident_std)
death_means = (410, 550, 440, 380, 410, 400)
death_std = (3, 5, 2, 3, 3, 2)
rects2 = ax.bar(ind + width, death_means, width, color='y', yerr=death_std)
# add some text for labels, title and axes ticks
ax.set_ylabel('No. of Accidents/Deaths')
ax.set_title('Road Accidents and deaths in Jan-June 2016')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('Jan', 'Feb', 'Mar', 'Apr', 'may', 'Jun'))
ax.legend((rects1[0], rects2[0]), ('Accidents', 'Death'))
plt.show()
|
import random
def generarnumero():
return random.randint(1000,9999)
def ordenarlista(listanombres,listaintentos):
largo=len(listaintentos)
for i in range(largo-1):
for j in range (i+1,largo):
if listaintentos[i] > listaintentos[j]:
aux=listaintentos[i]
aux2=listanombres[i]
listaintentos[i]=listaintentos[j]
listanombres[i]=listanombres[j]
listaintentos[j]=aux
listanombres[j]=aux2
return
trampa=True
listaintentos=[]
listanombres=[]
continuarjuego=True
respuesta=''
while continuarjuego:
numero = generarnumero()
if trampa:
print ("Esto es trampa!!",numero)
numerousuario=int(input("Ingrese numero:"))
intentos=1
while numerousuario != numero and numerousuario != -1:
if numerousuario > numero:
print("El numero ingresado es mayor")
elif numerousuario < numero:
print("El numero ingresado es menor")
intentos=intentos+1
numerousuario=int(input("Ingrese numero:"))
if numerousuario == -1:
print("Te rendiste!!")
else:
print("Cantidad de intentos", intentos)
if len(listaintentos) < 5:
nombre=input("Ingrese su nombre:")
listaintentos.append(intentos)
listanombres.append(nombre)
ordenarlista(listanombres,listaintentos)
print("Felicitaciones estas en el top 5")
else:
if intentos < listaintentos[4]:
nombre=input("Ingrese su nombre:")
listanombres[4] = nombre
listaintentos[4] = intentos
ordenarlista(listanombres,listaintentos)
print("Felicitaciones estas en el top 5")
respuesta=input("Queres continuar con el juego? (s/n)")
if respuesta=='n':
continuarjuego=False
else:
continuarjuego=True
largo=len(listaintentos)
print ()
print ("Ranking de los cinco mejores jugadores")
print ()
for i in range(largo):
print("Jugador:",listanombres[i],".Sus intentos:",listaintentos[i])
|
import math
import sys
import os
import copy
import time
def main(argv):
#start counting time
start_time = time.time()
#time limit is current time + minutes
time_limit = time.time() + 600
# Get the file name from the command line argument
filename = os.path.splitext(sys.argv[-1])[0]
# List to hold all the data from the file
data = readInput(filename)
graph = createGraph(data)
walk = nearestNeighbor(graph)
distance = totalLength(walk, graph)
print("Before 2 opt")
print(walk)
print(distance)
##print (time.time())
##print(time_limit)
if time.time() < time_limit:
improvedTour = twoOptTour(walk, graph, filename,time_limit)
walk = improvedTour
distance = totalLength(improvedTour, graph)
print("After 2 opt")
print(walk)
print(distance)
time_taken = time.time() - start_time
print("Time taken: %d" %time_taken)
writeOutput(distance, walk, filename)
# This function takes a filename and returns a list of tuples containing (city number, x-coordinate, y-coordinate)
def readInput(filename):
data = []
with open(filename + ".txt", "r") as inputFile:
for line in inputFile:
source, sourceXCoordinate, sourceYCoordinate = (int(i) for i in line.split())
data.append(tuple([source, sourceXCoordinate, sourceYCoordinate]))
#https://stackoverflow.com/questions/11354544/read-lines-containing-integers-from-a-file-in-python
inputFile.close()
return data
# This function will write the tour length and each city in tour list
def writeOutput(tourLength, tourList, filename):
filename = filename + ".txt.tour"
with open(filename, "w") as outputFile:
outputFile.write("%d\n" %tourLength)
# Write each city in tour. Exclude writing the last city
# since each city should only appear once. Last city is a repeated vertex
lastElement = len(tourList) - 1
for city in tourList[0:lastElement]:
outputFile.write("%d\n" %city)
outputFile.close()
# Will take a list of tuples representing city name, xCoordinate, y-Coordinate and create an adjacency list
def createGraph(data):
# Graph will be represented by an adjacency list
graph = {}
distanceTable = [[0 for i in range(len(data))]for j in range(len(data))]
# Create an adjacency list
# {City1: {neighbor1: distance, neighbor2: distance...}...}
# Iterate over each location
for source, xCoordinate, yCoordinate in data:
currentSource = source
currentX = xCoordinate
currentY = yCoordinate
# Create a dictionary consisting of all neighbors of currentSource and the distance to currentSource
neighbors = {}
for dest, destX, destY in data:
# Don't calculate the distance from one location to the same location
if dest != currentSource:
if distanceTable[source][dest] > 0:
distance = distanceTable[source][dest]
else:
distance = calculateDistance(currentX, destX, currentY, destY)
distanceTable[source][dest] = distance
distanceTable[dest][source] = distance
neighbors.update({dest: distance})
graph[currentSource] = neighbors
return graph
# This function returns the euclidean distance between two points given x and y coordinates
def calculateDistance(x1, x2, y1, y2):
x_diff = x1 - x2
y_diff = y1 - y2
distance = math.sqrt(x_diff * x_diff + y_diff * y_diff)
# Return the distance rounded to the nearest integer
return int(round(distance))
def nearestNeighbor(graph):
cities = graph.keys()
citiesVisited = 0
currentCity = 0
order = [0]
while(citiesVisited < len(cities)):
minDistance = sorted(graph[currentCity], key=graph[currentCity].get)
for city in minDistance:
if city in order:
continue
else:
nearest = city
order.append(nearest)
break
citiesVisited += 1
currentCity = nearest
order.append(order[0])
return order
# calculate tour length
def totalLength(walk, graph):
totalDistance = 0
walkLength = (len(walk)-1)
# iterate through all walk items
for i in range(walkLength):
sourceCity = walk[i]
if (i+1) > (walkLength): # fixes out of range
destCity = walk[0]
else:
destCity = walk[i+1]
# look up distance between source city and destination city in graph
distance = graph[sourceCity][destCity]
totalDistance += distance
return totalDistance
# This function will use the two opt local search algorithm to improve TSP solution
# https://en.wikipedia.org/wiki/2-opt
def twoOptTour(tour, graph, filename,time_limit):
bestDistance = totalLength(tour, graph)
madeChange = True
# Keep creating a new tour if a previous call to create new tour created a better solution
# Otherwise return the tour
while(madeChange == True):
#print("while")
if time.time() > time_limit:
break
madeChange, tour = createNewTour(tour, graph, filename,time_limit)
return tour
def createNewTour(tour, graph,filename,time_limit):
bestDistance = totalLength(tour, graph)
# Start at city m that is not the start and perform swaps from m+1 to length of the tour - 1
# since last city cannot be swapped either
for m in xrange(1, len(tour) - 1):
for n in xrange(m + 1, len(tour) - 1):
#if time limit has been reached end loop
if time.time() > time_limit:
break
#create a new tour and get its distance
newTour = twoOptSwap(tour, m, n)
newDistance = totalLength(newTour, graph)
# If the new distance is better than best distance, assign tour to the new improved tour
if(newDistance < bestDistance):
tour = newTour
writeOutput(newDistance, tour, filename)
return True, tour
return False, tour #Indicate no changes was made
# Perform a 2-opt swap when given a tour and cities m and n
# https://en.wikipedia.org/wiki/2-opt
def twoOptSwap(tour, m, n):
newTour = []
# take tour from start to city m - 1 and add it to new tour
newTour.extend(tour[:m])
# take tour m to n and add them in reverse order
index = n
while(index >= m):
newTour.append(tour[index])
index -= 1
# take the rest of the tour after m and add it to the new tour
newTour.extend(tour[n+1:])
return newTour
if __name__ == "__main__":
main(sys.argv)
|
from django.urls import path
from . import views
urlpatterns = [
path('session/<int:pk>/', views.AssessmentSessionDetailView.as_view(), name="assessmentsession_detail"),
path('submission/<int:pk>/', views.SubmissionUpdateView.as_view(), name="submission_edit"),
path('submit/<int:assessmentsession_id>/', views.SubmissionFileCreateView.as_view(), name="submission_submit"),
path('thanks/', views.SubmissionFileThanksView.as_view(), name="submission_thanks"),
]
|
class Solution(object):
def minAreaFreeRect_tle(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
def dotProduct(a, b, c):
baX, baY = b[0] - a[0], b[1] - a[1]
caX, caY = c[0] - a[0], c[1] - a[1] # bugfixed, typo
return baX * caX + baY * caY # bugfixed dot product
def distance(a, b):
# print (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2
return ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** 0.5
res, s = float('inf'), []
for i in xrange(len(points)):
for j in xrange(0, len(points)):
if j == i:
continue
for k in xrange(0, len(points)):
if k == i or k == j:
continue
if not dotProduct(points[i], points[j], points[k]):
for l in xrange(0, len(points)):
if l == k or l == i or l == j or sorted([i, j, k, l]) in s \
or dotProduct(points[l], points[j], points[k]) \
or dotProduct(points[j], points[i], points[l]):
continue
s.append(sorted([i, j, k, l]))
res = min(res,
distance(points[i], points[j]) * distance(points[i], points[k]))
return res if res < float('inf') else 0
def minAreaFreeRect(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
def dotProduct(a, b, c):
baX, baY = b[0] - a[0], b[1] - a[1]
caX, caY = c[0] - a[0], c[1] - a[1] # bugfixed, typo
return baX * caX + baY * caY # bugfixed dot product
def distance(a, b):
# print (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2
return ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** 0.5
points.sort()
res, s = float('inf'), []
for i in xrange(len(points)):
for j in xrange(i + 1, len(points)):
for k in xrange(j + 1, len(points)):
if not dotProduct(points[i], points[j], points[k]):
for l in xrange(k + 1, len(points)):
if not dotProduct(points[l], points[j], points[k]) and \
not dotProduct(points[j], points[i], points[l]):
res = min(res,
distance(points[i], points[j]) * distance(points[i], points[k]))
return res if res < float('inf') else 0
if __name__ == '__main__':
print Solution().minAreaFreeRect([[1, 2], [2, 1], [1, 0], [0, 1]])
print Solution().minAreaFreeRect([[0, 1], [2, 1], [1, 1], [1, 0], [2, 0]])
print Solution().minAreaFreeRect([[0, 3], [1, 2], [3, 1], [1, 3], [2, 1]])
print Solution().minAreaFreeRect([[3, 1], [1, 1], [0, 1], [2, 1], [3, 3], [3, 2], [0, 2], [2, 3]])
print Solution().minAreaFreeRect([[3, 3], [2, 2], [0, 0], [2, 1], [3, 0], [1, 3], [3, 1], [0, 1]])
print Solution().minAreaFreeRect([[0, 2], [0, 1], [3, 3], [1, 0], [2, 3], [1, 2], [1, 3]])
|
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
import h5py
import matplotlib.pyplot as plt
import random
from torch.utils.data import Dataset, DataLoader, random_split
import torch.nn as nn
import torch.optim as optim
import os
from tqdm import tqdm
import time
import pickle
import umetrics
class MaskTrainer:
def __init__(self, device, net,
train_set,
val_set,
batch_size,
optimizer,
scheduler=None,
loss = nn.MSELoss(),
in_key = 0,
target_key = 1,
mask_key = 2,
num_workers=0,
checkpoint_dir='./models/',
exp_name='net',
mask=False,
hingeloss=False,
classification=False):
self.device = device
self.net = net.to(device)
self.loss = loss
self.batch_size = batch_size
self.train_loader = DataLoader(train_set, batch_size=self.batch_size,
num_workers=num_workers, shuffle=True)
self.val_loader = DataLoader(val_set, batch_size=self.batch_size,
num_workers=num_workers, shuffle=False)
self.in_key = in_key
self.target_key = target_key
self.mask_key = mask_key
self.optimizer = optimizer
self.scheduler = scheduler
logging_dir_name = exp_name + '_' + str(time.time()) + '/'
self.checkpoint_dir = checkpoint_dir + logging_dir_name
if not os.path.isdir(checkpoint_dir):
os.mkdir(checkpoint_dir)
os.mkdir(self.checkpoint_dir)
self.epochs_so_far = 0
self.mask = mask
self.hingeloss = hingeloss
self.classification = classification
def plot_predictions(self, img, graph_pred, graph_target):
plt.subplot(1, 3, 1)
plt.imshow(img.permute(1, 2, 0))
plt.title("Input")
plt.subplot(1, 3, 2)
plt.imshow(graph_target.transpose(1, 2, 0)[:, :, 0])
plt.title("GT Graph 0")
plt.subplot(1, 3, 3)
if self.classification:
graph_pred = np.squeeze(graph_pred[:, 0, :, :])
graph_pred = np.squeeze(np.argmax(graph_pred, axis=0))
plt.imshow(graph_pred - 1)
else:
plt.imshow(graph_pred.transpose(1, 2, 0)[:, :, 0])
plt.title("Pred Graph 0")
plt.show()
def train(self, epochs, checkpoint=False, train_loader=None, val_loader=None, start_epoch=0):
# Phases and Logging
phases = { 'train': train_loader if train_loader else self.train_loader,
'val': val_loader if val_loader else self.val_loader }
start_time = time.time()
train_log = []
# Training
for i in range(start_epoch, epochs):
epoch_data = { 'train_mean_loss': 0.0, 'val_mean_loss': 0.0, 'train_mean_iou': 0.0, 'val_mean_iou': 0.0, 'train_mean_jaccard': 0.0, 'val_mean_jaccard': 0.0 }
for phase, loader in phases.items():
if phase == 'train':
self.net.train()
else:
self.net.eval()
running_loss = 0.0
total, correct = 0, 0
running_iou, running_jaccard = 0.0, 0.0
for batch in tqdm(loader):
_in, _out, _mask = batch[self.in_key].to(self.device), batch[self.target_key].to(self.device), batch[self.mask_key].to(self.device)
# Forward
self.optimizer.zero_grad()
output = self.net(_in)
# Apply loss to masked outputs
if self.mask:
output, _out = output.permute(0, 2, 3, 1), _out.permute(0, 2, 3, 1)
_mask = _mask.squeeze()
output, _out = output[_mask != 0].float(), _out[_mask != 0].float()
# if self.hingeloss:
# output = output.reshape(output.shape[0], output.shape[1]*output.shape[2]*output.shape[3])
# _out = _out.reshape(_out.shape[0], _out.shape[1]*_out.shape[2]*_out.shape[3])
loss = self.loss(output, _out)
# display
if i % 5 == 0:
self.plot_predictions(_in[0], output[0].to(torch.device("cpu")).detach().numpy(), _out[0].cpu().detach().numpy())
# metrics
q = np.squeeze(output[:, 0, :, :])
graph_pred = q.data.to(torch.device("cpu")).numpy()
pred = graph_pred.transpose(0, 2, 3, 1)
target = _out.data.to(torch.device("cpu")).numpy().transpose(0, 2, 3, 1)
for i in range(target.shape[0]):
result = umetrics.calculate(target[i], pred[i], strict=True)
if len(result.per_object_IoU) > 0:
running_iou += np.mean(result.per_object_IoU)
tp = result.n_true_positives
fn = result.n_false_negatives
fp = result.n_false_positives
running_jaccard += tp / (tp+fn+fp)
# Optimize
if phase == 'train':
loss.backward()
self.optimizer.step()
# Log batch results
running_loss += loss.item()
torch.cuda.empty_cache()
# Log phase results
epoch_data[phase + '_mean_loss'] = running_loss / len(loader)
epoch_data[phase + '_mean_iou'] = running_iou / len(loader)
epoch_data[phase + '_mean_jaccard'] = running_jaccard / len(loader)
# Display Progress
duration_elapsed = time.time() - start_time
print('\n-- Finished Epoch {}/{} --'.format(i, epochs - 1))
print('Training Loss: {}'.format(epoch_data['train_mean_loss']))
print('Validation Loss: {}'.format(epoch_data['val_mean_loss']))
if i % 5 == 0:
print('Training Mean IoU: {}'.format(epoch_data['train_mean_iou']))
print('Validation Mean IoU: {}'.format(epoch_data['val_mean_iou']))
print('Training Mean Jaccard: {}'.format(epoch_data['train_mean_jaccard']))
print('Validation Mean Jaccard: {}'.format(epoch_data['val_mean_jaccard']))
print('Time since start: {}'.format(duration_elapsed))
epoch_data['time_elapsed'] = duration_elapsed
train_log.append(epoch_data)
# Scheduler
if self.scheduler:
self.scheduler.step()
# Checkpoint
checkpoint_time = time.time()
if checkpoint:
path = self.checkpoint_dir + 'checkpoint_optim_' + str(self.epochs_so_far)
torch.save({
'optim': self.optimizer.state_dict(),
'sched': self.scheduler.state_dict(),
'state_dict': self.net.state_dict(),
'start_epoch': self.epochs_so_far + 1,
'log': train_log
}, path)
self.epochs_so_far += 1
# Save train_log
path = self.checkpoint_dir + 'train_log_' + str(self.epochs_so_far)
with open(path, 'wb') as fp:
pickle.dump(train_log, fp)
return train_log
def evaluate(self, batch):
self.net.eval()
_in = batch[self.in_key].to(self.device)
output = self.net(_in)
return output.cpu().detach().numpy()
class DualMaskTrainer:
def __init__(self, device, net,
train_set,
val_set,
batch_size,
optimizer,
scheduler=None,
losses = [nn.CrossEntropyLoss(), nn.MSELoss()],
alpha = 0.5,
in_key = 0,
target_key = 1,
mask_key = 2,
num_workers=0,
checkpoint_dir='./models/',
exp_name='net'):
self.device = device
self.net = net.to(device)
self.losses = losses
self.alpha = alpha
self.batch_size = batch_size
self.train_loader = DataLoader(train_set, batch_size=self.batch_size,
num_workers=num_workers, shuffle=True)
self.val_loader = DataLoader(val_set, batch_size=self.batch_size,
num_workers=num_workers, shuffle=False)
self.in_key = in_key
self.target_key = target_key
self.mask_key = mask_key
self.optimizer = optimizer
self.scheduler = scheduler
logging_dir_name = exp_name + '_' + str(time.time()) + '/'
self.checkpoint_dir = checkpoint_dir + logging_dir_name
if not os.path.isdir(checkpoint_dir):
os.mkdir(checkpoint_dir)
os.mkdir(self.checkpoint_dir)
self.epochs_so_far = 0
def train(self, epochs, checkpoint=False, train_loader=None, val_loader=None):
loss_seg, loss_graph = self.losses
# Phases and Logging
phases = { 'train': train_loader if train_loader else self.train_loader,
'val': val_loader if val_loader else self.val_loader }
start_time = time.time()
train_log = []
# Training
for i in range(epochs):
epoch_data = { 'train_mean_loss_seg': 0.0, 'train_mean_loss_graph': 0.0,
'val_mean_loss_seg': 0.0, 'val_mean_loss_graph': 0.0,
'train_mean_iou_seg': 0.0, 'val_mean_iou_seg': 0.0,
'train_mean_jaccard_seg': 0.0, 'val_mean_jaccard_seg': 0.0,
'train_mean_iou_graph': 0.0, 'val_mean_iou_graph': 0.0,
'train_mean_jaccard_graph': 0.0, 'val_mean_jaccard_graph': 0.0}
for phase, loader in phases.items():
if phase == 'train':
self.net.train()
else:
self.net.eval()
running_losses = np.zeros(2)
total, correct = 0, 0
running_iou_seg, running_jaccard_seg = 0.0, 0.0
running_iou_graph, running_jaccard_graph = 0.0, 0.0
for batch in tqdm(loader):
_in, _out, _mask = batch[self.in_key].to(self.device), batch[self.target_key], batch[self.mask_key].to(self.device)
_out_seg, _out_graph = _out
_out_seg, _out_graph = _out_seg.to(self.device).squeeze().long(), _out_graph.to(self.device)
# Forward
self.optimizer.zero_grad()
output_seg, output_graph = self.net(_in)
# Apply loss to masked outputs
output_graph, _out_graph = output_graph.permute(0, 2, 3, 1), _out_graph.permute(0, 2, 3, 1)
_mask = _mask.squeeze()
output_graph, _out_graph = output_graph[_mask != 0].float(), _out_graph[_mask != 0].float()
loss0, loss1 = loss_seg(output_seg, _out_seg), loss_graph(output_graph, _out_graph)
loss = self.alpha * loss0 + (1 - self.alpha) * loss1
# metrics
q = np.squeeze(output_graph[:, 0, :, :])
graph_pred = q.data.to(torch.device("cpu")).numpy()
pred = graph_pred.transpose(0, 2, 3, 1)
target = _out_graph.data.to(torch.device("cpu")).numpy().transpose(0, 2, 3, 1)
for i in range(target.shape[0]):
result_graph = umetrics.calculate(target[i], pred[i], strict=True)
result_seg = umetrics.calculate(_out_seg[i], output_seg[i], strict=True)
if len(result_graph.per_object_IoU) > 0:
running_iou_graph += np.mean(result_graph.per_object_IoU)
tp = result_graph.n_true_positives
fn = result_graph.n_false_negatives
fp = result_graph.n_false_positives
running_jaccard_graph += tp / (tp+fn+fp)
# Optimize
if phase == 'train':
loss.backward()
self.optimizer.step()
# Log batch results
running_losses += [loss0.item(), loss1.item()]
torch.cuda.empty_cache()
# Log phase results
running_loss_seg, running_loss_graph = running_losses
epoch_data[phase + '_mean_loss_seg'] = running_loss_seg / len(loader)
epoch_data[phase + '_mean_loss_graph'] = running_loss_graph / len(loader)
epoch_data[phase + '_mean_iou_seg'] = running_iou_seg / len(loader)
epoch_data[phase + '_mean_jaccard_seg'] = running_jaccard_seg / len(loader)
epoch_data[phase + '_mean_iou_graph'] = running_iou_graph / len(loader)
epoch_data[phase + '_mean_jaccard_graph'] = running_jaccard_graph / len(loader)
# Display Progress
duration_elapsed = time.time() - start_time
print('\n-- Finished Epoch {}/{} --'.format(i, epochs - 1))
print('Training Loss (Segmentation): {}'.format(epoch_data['train_mean_loss_seg']))
print('Training Loss (Graph): {}'.format(epoch_data['train_mean_loss_graph']))
print('Validation Loss (Segmentation): {}'.format(epoch_data['val_mean_loss_seg']))
print('Validation Loss (Graph): {}'.format(epoch_data['val_mean_loss_graph']))
print('Time since start: {}'.format(duration_elapsed))
epoch_data['time_elapsed'] = duration_elapsed
train_log.append(epoch_data)
# Scheduler
if self.scheduler:
self.scheduler.step()
# Checkpoint
checkpoint_time = time.time()
if checkpoint:
path = self.checkpoint_dir + 'checkpoint_' + str(self.epochs_so_far) + '_' + str(checkpoint_time)
torch.save(self.net.state_dict(), path)
self.epochs_so_far += 1
# Save train_log
path = self.checkpoint_dir + 'train_log_' + str(checkpoint_time)
with open(path, 'wb') as fp:
pickle.dump(train_log, fp)
return train_log
def evaluate(self, batch):
self.net.eval()
_in = batch[self.in_key].to(self.device)
output_seg, output_graph = self.net(_in)
return output_seg.cpu().detach().numpy(), output_graph.cpu().detach().numpy() |
#!/bin/env python
# encoding: utf-8
__author__ = 'icejoywoo'
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
if x < 0:
return False
y = x
div = 1
while y / div >= 10:
div *= 10
while y:
print y, div
l = y / div
r = y % 10
if l != r:
return False
y = (y % div) / 10
div /= 100
return True
if __name__ == '__main__':
assert Solution().isPalindrome(121) == True
assert Solution().isPalindrome(1001) == True
assert Solution().isPalindrome(-121) == False
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import numpy as np
def run():
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))
cv2.namedWindow('Webcam', cv2.WINDOW_AUTOSIZE)
# allow the camera to warmup
time.sleep(0.1)
#picture counter
c=0
# define range of blue color in HSV
# voir https://www.google.com/search?client=firefox-b&q=%23D9E80F
# convertir valeur dans [0,179], [0,255], [0,255]
teinte_min = 160
teinte_max = 207
sat_min = 50
sat_max = 100
val_min = 51
val_max = 100
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
image = frame.array
# Convert BGR to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_blue = np.array([int(teinte_min/2),int(sat_min*255/100),int(val_min*255/100)])
upper_blue = np.array([int(teinte_max/2),int(sat_max*255/100),int(val_max*255/100)])
# Threshold the HSV image to get only yellow/green colors
mask1 = cv2.inRange(hsv, lower_blue, upper_blue)
mask1 = cv2.medianBlur(mask1, 5)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(image,image, mask= mask1)
ret1,thresh1 = cv2.threshold(mask1,127,255,0)
im2,contours1,hierarchy1 = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, 2)
if len(contours1) > 0:
cnt1 = max(contours1, key = cv2.contourArea)
(x1,y1),radius1 = cv2.minEnclosingCircle(cnt1)
center1 = (int(x1),int(y1))
radius1 = int(radius1)
cv2.circle(image,center1,radius1,(255,0,0),2)
cv2.circle(image,center1,5,(255,0,0),2)
image = cv2.flip(image, 0)
# clear the stream in preparation for the next frame
rawCapture.truncate(0)
#show the frame
cv2.imshow('Webcam',image)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q") or rospy.is_shutdown():
break
# if the SPACE key was pressed, take a picture
elif key == 32:
c += 1
cv2.imwrite('fra%i.png'%c,image)
print("Picture saved")
cv2.destroyAllWindows()
|
"""
This type stub file was generated by pyright.
"""
from rdkit.VLib.Supply import SupplyNode
class SmilesSupplyNode(SupplyNode):
""" Smiles supplier
Sample Usage:
>>> import os
>>> from rdkit import RDConfig
>>> fileN = os.path.join(RDConfig.RDCodeDir,'VLib','NodeLib',\
'test_data','pgp_20.txt')
>>> suppl = SmilesSupplyNode(fileN,delim="\\t",smilesColumn=2,nameColumn=1,titleLine=1)
>>> ms = [x for x in suppl]
>>> len(ms)
20
>>> ms[0].GetProp("_Name")
'ALDOSTERONE'
>>> ms[0].GetProp("ID")
'RD-PGP-0001'
>>> ms[1].GetProp("_Name")
'AMIODARONE'
>>> ms[3].GetProp("ID")
'RD-PGP-0004'
>>> suppl.reset()
>>> suppl.next().GetProp("_Name")
'ALDOSTERONE'
>>> suppl.next().GetProp("_Name")
'AMIODARONE'
>>> suppl.reset()
"""
def __init__(self, fileName, delim=..., nameColumn=..., smilesColumn=..., titleLine=..., **kwargs) -> None:
...
def reset(self): # -> None:
...
def next(self):
"""
"""
...
if __name__ == '__main__':
...
|
#import tkinter 1
from tkinter import *
window = Tk()
window.title("Tkinter demo")
window.minsize(width=500, height=500)
window.config(padx=100, pady=200)
my_label = Label(text="I am a Label", font=("Arial", 24, "bold"))
#my_label.pack()
#my_label.place(x=0, y=0)
my_label.grid(column=0, row=0)
my_label["text"] = "New text"
my_label.config(text="More new text")
def button_clicked():
new_text = input.get()
my_label.config(text=new_text)
def spinbox_used():
print(spinbox.get())
def scale_used(value):
print(value)
def checkbutton_used():
print(checked_state.get())
def radio_used():
print(radio_state.get())
def listbox_used(event):
print(listbox.get(listbox.curselection()))
spinbox = Spinbox(from_=0, to=100, width=5, command=spinbox_used)
#spinbox.pack()
spinbox.grid(column=2, row=2)
button = Button(text="Click Me", command=button_clicked)
button.grid(column=3,row=3)
input = Entry(width=10)
#input.pack()
input
text = Text(height=5, width=30)
text.focus()
text.insert(END, "Multi-line text entry")
text.grid(column=4,row=4)
scale = Scale(from_=0, to=100, command=scale_used)
scale.grid(column=4,row=5)
checked_state = IntVar()
checkedbutton = Checkbutton(text="Is On?", variable=checked_state, command=checkbutton_used)
checkedbutton.grid(column=2,row=0)
radio_state = IntVar()
radiobutton1 = Radiobutton(text="Option1", value=1, variable=radio_state,command=radio_used)
radiobutton2 = Radiobutton(text="Option2", value=2, variable=radio_state,command=radio_used)
radiobutton3 = Radiobutton(text="Option3", value=3, variable=radio_state,command=radio_used)
radiobutton1.grid(column=2,row=2)
radiobutton2.grid(column=2,row=3)
radiobutton3.grid(column=2,row=4)
listbox = Listbox(height=4)
fruits = ["Apple", "Pear", "Orange", "Banana"]
for item in fruits:
listbox.insert(fruits.index(item), item)
listbox.bind("<<ListboxSelect>>", listbox_used)
listbox.grid(column=5,row=0)
window.mainloop()
|
import random
def quick_sort(arr):
start, end = 0, len(arr)-1
def sort(arr, start, end):
if start - end == 1 : #Already sorted if only elem or no elem
return arr
pivot = random.randint(start, end )
arr[pivot], arr[end], pivot = arr[end], arr[pivot], end #Move pivot elem to end
swap_pos = end - 1 #First free position to swap to
##Partition the array to one side larger than pivot and other smaller
for com_pos in range(end-1, start-1, -1):
if arr[com_pos] > arr[pivot]:
arr[com_pos], arr[swap_pos] = arr[swap_pos], arr[com_pos]
swap_pos -= 1 #Update the next position to swap to
arr[pivot], arr[swap_pos+1], pivot = arr[swap_pos+1], arr[pivot], swap_pos+1 #Swap pivot to last item that was swapped.
##Call quick sort on both the partitions either side of pivot
sort(arr, start, pivot-1)
sort(arr, pivot+1, end)
sort(arr, start, end)
if __name__ == "__main__":
arr = [3, 21, 123, 2, 1, 2, 3, 48, 12, 10, 13]
print(f'''Using merge sort to sort the following array {arr}...''')
quick_sort(arr)
print(f'''Sorted array is: {arr}''') |
# Generated by Django 2.2.6 on 2020-05-23 10:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pictionary', '0006_cards'),
]
operations = [
migrations.DeleteModel(
name='Cards',
),
]
|
#3-4
guests = ["John Skeet", "McKeel Hagerty", "Dave Chappelle"]
baseMessage = "Dear %s,\nI would like to formally invite to my home for dinner Saturday, January 30, 2021. Please let me know if you plan to attend.\n\nThank you.\n\n"
for guest in guests:
print(baseMessage%(guest))
#3-5
print(f"Unfortunately, {guests[1]} is unable to attend dinner this weekend.")
guests.pop(1)
guests.insert(1, "Morgan Freeman")
for guest in guests:
print(baseMessage%(guest))
#3-6
biggerTableMessage = "Hello there, I've found and purchased a new dining room table that will seat more of us for our lovely evening."
print(biggerTableMessage)
guests.insert(0, "Bill Burr")
guests.insert(2, "Mike Rowe")
guests.append("James Spader")
for guest in guests:
print(baseMessage%(guest))
print(f"Our guest list has {len(guests)} people in it.\n\n")
#3-7
print("Hello there, unfortunately, due to unforeseen shipping delays, the dinner table won't arrive in time for this weekend's dinner. I will be in touch to schedule another dinner soon. Thanks for understanding.")
for seatNumber in range(4):
print(f"Hello, {guests[-1]}. I apologize, but my new dinner table will not arrive in time. I hope you understand that I will have to shorten the guest list. I hope we can reschedule for another time. Thank you.")
guests.pop()
for guest in guests:
print(f"\n\nDear {guest}, with the shortage of seating, I've unfortunately been forced into shortening the guest list. You, however, are still invited for dinner this Saturday if you would still like to attend. Please let me know your intentions as soon as possible. Thank you.")
del guests[0]
del guests[0]
print(guests) |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 10:35:36 2018
google colab 사용해서
@author: SDEDU
"""
import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets.cifar10 import load_data
#다음 배치를 읽어오기 위한 함수
#num 개수만큼 랜덤하게 이미지와 레이블을 리턴
def next_batch(num,data,labels):
idx=np.arange(0,len(data))
np.random.shuffle(idx)
idx=idx[:num]
data_shuffle=[data[i] for i in idx]
labels_shuffle=[labels[i] for i in idx]
return np.asarray(data_shuffle), np.asarray(labels_shuffle)
#CNN망을 설계 정의하는 함수
def build_CNN_classifier(x,keep_prob):
#입력 이미지 행렬
x_image=x
#step 1 Convolution
#Filter 5x5, 3(color) ,filter 개수: 64개
W_conv1=tf.Variable(tf.truncated_normal(shape=[5,5,3,64],stddev=5e-2))
b_conv1=tf.Variable(tf.truncated_normal(shape=[64],stddev=5e-2))
c_conv1=tf.nn.conv2d(x_image,W_conv1,strides=[1,1,1,1],
padding='SAME')
h_conv1=tf.nn.relu(c_conv1+b_conv1) # 32 x 32
#step 1 Pooling ( 3x3 = 9 개중의 가장 큰거 뽑기)
h_pool1=tf.nn.max_pool(h_conv1,ksize=[1,3,3,1], # 16 x 16( strides가 2x2 이고 패딩이 same이여서 1/2로 줄음)
strides=[1,2,2,1],padding='SAME')
#step 2 convolution 64 -> 64
W_conv2=tf.Variable(tf.truncated_normal(shape=[5,5,64,64],stddev=5e-2))
b_conv2=tf.Variable(tf.truncated_normal(shape=[64],stddev=5e-2))
c_conv2=tf.nn.conv2d(h_pool1,W_conv2,strides=[1,1,1,1],
padding='SAME')#16 x 16
h_conv2=tf.nn.relu(c_conv2+ b_conv2)
#step 2 Pooling
h_pool2=tf.nn.max_pool(h_conv2, ksize=[1,3,3,1], #8 x 8
strides=[1,2,2,1],padding='SAME')
#step 3 Convolution
W_conv3=tf.Variable(tf.truncated_normal(shape=[3,3,64,128],stddev=5e-2))
b_conv3=tf.Variable(tf.truncated_normal(shape=[128]))
c_conv3=tf.nn.conv2d(h_pool2,W_conv3,strides=[1,1,1,1],
padding='SAME') #8 x 8
h_conv3=tf.nn.relu(c_conv3+ b_conv3)
#step 4 Convolution
W_conv4=tf.Variable(tf.truncated_normal(shape=[3,3,128,128],stddev=5e-2))
b_conv4=tf.Variable(tf.truncated_normal(shape=[128],stddev=5e-2))
c_conv4=tf.nn.conv2d(h_conv3,W_conv4,strides=[1,1,1,1],
padding='SAME') # 8 x 8
h_conv4=tf.nn.relu(c_conv4+ b_conv4)
#step 5 Convolution
W_conv5=tf.Variable(tf.truncated_normal(shape=[3,3,128,128],stddev=5e-2))
b_conv5=tf.Variable(tf.truncated_normal(shape=[128],stddev=5e-2))
c_conv5=tf.nn.conv2d(h_conv4,W_conv5,strides=[1,1,1,1],
padding='SAME') # 8 x 8
h_conv5=tf.nn.relu(c_conv5+ b_conv5)
#step 6 Fully Network Layer
W_fc1=tf.Variable(tf.truncated_normal(shape=[8*8*128,384],stddev=5e-2))
b_fc1=tf.Variable(tf.truncated_normal(shape=[384],stddev=5e-2))
h_conv5_flat=tf.reshape(h_conv5, [-1,8*8*128])
m_fc1=tf.matmul(h_conv5_flat,W_fc1)+b_fc1
h_fc1=tf.nn.relu(m_fc1)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
#step 7 Hidden Network Layer
W_fc2=tf.Variable(tf.truncated_normal(shape=[384,10],stddev=5e-2))
b_fc2=tf.Variable(tf.truncated_normal(shape=[10],stddev=5e-2))
logits=tf.matmul(h_fc1_drop,W_fc2)+b_fc2
y_pred=tf.nn.softmax(logits)
return y_pred, logits
#시작 함수
def main():
#input, output, dropout을 위한 placeholder를 정의
# None: batchsize, 32 x 32 x 3(color image)
x=tf.placeholder(tf.float32,shape=[None,32,32,3])
# 10개 class로 분리
y=tf.placeholder(tf.float32,shape=[None,10])
# 1: 100%, 0.8: 80%
keep_prob=tf.placeholder(tf.float32)
#CIFAR-10 이미지 다운 및 불러오기
(x_train,y_train),(x_test,y_test)=load_data()
#scalar 형태의 레이블(0~9)을 one-hot 인코딩으로 변환
y_train_one_hot=tf.squeeze(tf.one_hot(y_train,10),axis=1)
y_test_one_hot=tf.squeeze(tf.one_hot(y_test,10),axis=1)
#CNN 그래프 생성
#ypred는 softmax함수를 통과한값
#logits는 softmax함수를 통과하기 전의 값
y_pred, logits=build_CNN_classifier(x,keep_prob)
#Cross Entropy 함수를 cost function으로 정의한다, logits: softmax하기 전 값
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
labels=y,logits=logits))
optimizer=tf.train.RMSPropOptimizer(1e-3)
train_step=optimizer.minimize(loss)
#정확도를 계산하는 연산을 추가
correct_prediction=tf.equal(tf.argmax(y_pred,1),tf.argmax(y,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
#세션을 열고 학습 진행
sess=tf.Session()
sess.run(tf.global_variables_initializer())
loop_num=10000
batch_size=128
for i in range(loop_num):
batch=next_batch(batch_size,x_train,sess.run(y_train_one_hot))
#학습
sess.run(train_step,feed_dict={x:batch[0], y:batch[1],keep_prob:0.8})
# i가 10 step 마다 화면에 정확도와 loss를 출력
if i%100 == 0:
train_accuracy,loss_print=sess.run([accuracy,loss],
feed_dict={x:batch[0],
y:batch[1],
keep_prob:1.0})
print('Epoch: [%04d/%d], accuracy: %f, Loss: %f' %(i,loop_num,train_accuracy,loss_print))
#학습 후 테스트 데이터(10000개) 에 대한 정확도 출력
test_accuracy=0.0
loop_num=10
sample_num=1000
for i in range(loop_num):
test_batch=next_batch(sample_num,x_test,sess.run(y_test_one_hot))
test_accuracy +=sess.run(accuracy,
feed_dict={x:test_batch[0],
y:test_batch[1],
keep_prob:1.0})
test_accuracy /=loop_num
print('테스트 정확도: %f' %test_accuracy)
sess.close()
if __name__ =='__main__':
main() |
#---------------------------------------------------------
#Python Layer for the cityscapes dataset
# Adapted from: Fully Convolutional Networks for Semantic Segmentation by Jonathan Long*, Evan Shelhamer*, and Trevor Darrell. CVPR 2015 and PAMI 2016. http://fcn.berkeleyvision.org
#---------------------------------------------------------
import caffe
import numpy as np
from PIL import Image
import os
import pdb
import random
import re
import math
class input_layer(caffe.Layer):
"""
Load (input image, label image) pairs from the SBDD extended labeling
of PASCAL VOC for semantic segmentation
one-at-a-time while reshaping the net to preserve dimensions.
Use this to feed data to a fully convolutional network.
"""
def setup(self, bottom, top):
"""
Setup data layer according to parameters:
- cityscapes_dir: path to SBDD `dataset` dir
- split: train / seg11valid
- mean: tuple of mean values to subtract
- randomize: load in random order (default: True)
- seed: seed for randomization (default: None / current time)
for SBDD semantic segmentation.
N.B.segv11alid is the set of segval11 that does not intersect with SBDD.
Find it here: https://gist.github.com/shelhamer/edb330760338892d511e.
example
params = dict(cityscapes_dir="/path/to/SBDD/dataset",
mean=(104.00698793, 116.66876762, 122.67891434),
split="valid")
"""
# config
params = eval(self.param_str)
self.channel6_dir = params['input_dir']
self.split = params['split']
self.mean = np.array(params['mean'])
self.resize = np.array(params['resize'])
self.random = params.get('randomize', True)
self.seed = params.get('seed', None)
self.batch_size = params.get('batch_size', None)
self.idx = np.array(range(self.batch_size))
self.batch = np.array([self.batch_size]*self.batch_size)
#self.idx = [324]
self.path = '/media/ys/1a32a0d7-4d1f-494a-8527-68bb8427297f/End_to_End/'
label_path4 = '/media/ys/1a32a0d7-4d1f-494a-8527-68bb8427297f/End_to_End/Mobis_crop/TRAIN1.txt'
# two tops: data and label
if len(top) != 2:
raise Exception("Need to define two tops: data and label.")
# data layers have no bottoms
if len(bottom) != 0:
raise Exception("Do not define a bottom.")
train_data = []
filename4 = open(label_path4, 'r')
patten4 = '(\w*/\w*/\w*.\w*),([-\d]*.\d*)'
r4 = re.compile(patten4)
summation = 0
summation_sqr = 0
while True:
line = filename4.readline()
line_split = r4.findall(line)
if not line: break
train_data.append(line_split[0])
# pdb.set_trace()
summation += float(line_split[0][1])
summation_sqr += (float(line_split[0][1])) * (float(line_split[0][1]))
filename4.close()
self.train_data = train_data
#pdb.set_trace()
if self.random:
random.seed(self.seed)
self.idx = random.sample(range(len(self.train_data)),self.batch_size)
length = len(self.train_data)
mean = summation/length
sqr_mean = summation_sqr/length
var = sqr_mean - mean * mean
std = math.sqrt(var)
self.mean_label = mean
self.sqr_mean = sqr_mean
self.std = std
#pdb.set_trace()
# make eval deterministic
if 'train' not in self.split:
self.random = False
def reshape(self, bottom, top):
# load image + label image pair
#pdb.set_trace()
self.data, self.label = self.load_batch(self.idx, self.batch_size)
#pdb.set_trace()
# reshape tops to f~/it (leading 1 is for batch dimension)
top[0].reshape(*self.data.shape)
top[1].reshape(*self.label.shape)
def forward(self, bottom, top):
# pdb.set_trace()
# assign output
top[0].data[...] = self.data
top[1].data[...] = self.label
# pick next input
#pdb.set_trace()
if self.random:
self.idx = random.sample(range(len(self.train_data)),self.batch_size)
else:
#self.idx = self.idx
self.idx = self.idx + self.batch
#pdb.set_trace()
if self.idx[-1] > len(self.train_data) - self.batch_size:
self.idx = np.array(range(self.batch_size))
#pdb.set_trace()
def backward(self, top, propagate_down, bottom):
#pdb.set_trace()
pass
def load_batch(self, idx, batch_size):
batch_im = np.zeros((self.batch_size,3,100,250), dtype = np.float32)
for i in range(self.batch_size):
# pdb.set_trace()
batch_im[i] = self.load_image_label(self.path+'Mobis_crop/'+self.train_data[self.idx[i]][0])
# pdb.set_trace()
angle = np.zeros((self.batch_size,1), dtype = np.float32)
for i in range(self.batch_size):
angle[i] = float(self.train_data[self.idx[i]][1])
# angle[i] = float(self.train_data[self.idx[i]][1])/(180/np.pi)
# angle[i] = (float(self.train_data[self.idx[i]][1])-self.mean_label)/self.std
# pdb.set_trace()
return batch_im, angle
def load_image_label(self, idx):
"""
Load input image and preprocess for Caffe:
- cast to float
- switch channels RGB -> BGR
- subtract mean
- transpose to channel x height x width order
"""
#pdb.set_trace()
im = Image.open(idx)
# in_ori = np.array(im, dtype=np.float32)
# pdb.set_trace()
im = im.resize([self.resize[1],self.resize[0]],Image.ANTIALIAS)
in_ = np.array(im, dtype=np.float32)
# in_ = -1.0 + 2.0 * in_/255.0
# pdb.set_trace()
in_ = in_[:,:,::-1]
in_ = in_.transpose((2,0,1))
return in_ |
"""
Reads the grammar in text and returns Terminals and NonTerminal objects
"""
import re
from grammar_elements import Terminal, NonTerminal, ElementType
OR_SYMBOL = '|'
EPSILON_SYMBOL = '\L'
def from_string(string):
"""
:param string: a string that contains the syntax grammar rule definitions
:return: a list of NonTerminal objects with their corresponding rules defined
"""
non_terminals_dict = {}
non_terminals_list = []
# split by lines ending in '\n' not followed by an OR_SYMBOL
lines = re.split(r'\n', string)
for line in lines:
non_terminal_name, rule_string = line.replace('\n', ' ').split('::=')
non_terminal_name = non_terminal_name.replace(' ', '')
non_terminal = NonTerminal(non_terminal_name)
rule_split = [element for element in rule_string.split(' ') if element != '']
for i, grammar_element in enumerate(rule_split):
# skip OR_SYMBOL
if grammar_element == OR_SYMBOL:
continue
# turn the grammar_element string to a GrammarElement object
else:
if grammar_element == EPSILON_SYMBOL:
grammar_element = Terminal.create_epsilon()
elif grammar_element[0].isupper():
grammar_element = NonTerminal(grammar_element)
else:
grammar_element = Terminal(grammar_element)
# add grammar_element to the non_terminal productions
if rule_split[i - 1] == OR_SYMBOL:
non_terminal.or_with(grammar_element)
else:
non_terminal.and_with(grammar_element)
# add nonterminal to hash for faster retrieval
non_terminals_dict[non_terminal.name] = non_terminal
# append the found non_terminal to the resultant list
non_terminals_list.append(non_terminal)
# add correct references for NonTerminal objects in every productions
for non_terminal in non_terminals_list:
for production in non_terminal.productions:
for i, element in enumerate(production):
if element.type == ElementType.NonTerminal:
try:
production[i] = non_terminals_dict[element.name]
except:
# raise ValueError('Non terminal "' + element.name + '" is not defined.')
pass
# return a list of the NonTerminal objects
return non_terminals_list
def from_file(path):
"""
:param path: a string of the path of the file containing the syntax grammar rule definitions
:return: a list of NonTerminal objects with their corresponding rules defined
"""
content = open(path).read()
return from_string(content)
def get_terminals(non_terminals):
result = set()
for non_terminal in non_terminals:
for production in non_terminal.productions:
for element in production:
if element.type == ElementType.Terminal:
result.add(element.name)
result.add('$')
return list(result)
|
import requests
class Repustate:
def __init__(self, api_key=None, server='api.repustate.com', cache=None):
"""
:param str api_key:
:param disk.Cache.Cache cache:
"""
self._api_key = api_key or '$APIKEY'
self._server = server
self._cache = cache
if self._cache:
self.get_entities = self._cache.make_cached(
id='repustate_get_entities_function',
function=self._get_entities,
sub_directory='get_entities'
)
self.get_sentiment = self._cache.make_cached(
id='repustate_get_sentiment_function',
function=self._get_sentiment,
sub_directory='get_sentiment'
)
else:
self.get_entities = self._get_entities
self.get_sentiment = self._get_sentiment
@property
def usage(self):
response = requests.get(
f'https://{self._server}/v4/{self._api_key}/usage.json',
verify=False,
)
return response.json()
def _get_entities(self, text, language='en'):
response = requests.post(
f'https://{self._server}/v4/{self._api_key}/entities.json',
verify=False, data={'text': text, 'lang': language}
)
return response.json()
def _get_sentiment(self, text, topics=None, language='en'):
if isinstance(text, str):
if topics is None:
response = requests.post(
f'https://{self._server}/v4/{self._api_key}/score.json',
verify=False, data={'text': text, 'lang': language}
)
else:
response = requests.post(
f'https://{self._server}/v4/{self._api_key}/topic.json',
verify=False, data={'text': text, 'topics': ','.join(topics) , 'lang': language}
)
elif isinstance(text, list):
if topics is None:
data = {f'text{i}': t for i, t in enumerate(text)}
data['lang'] = language
response = requests.post(
f'https://{self._server}/v4/{self._api_key}/bulk-score.json',
verify=False, data=data
)
else:
response = None
else:
response = None
return response.json()
|
import unittest
from selenium import webdriver
import time
links = ["http://suninjuly.github.io/registration1.html", "http://suninjuly.github.io/registration2.html"]
class TestForms(unittest.TestCase):
browser = webdriver.Chrome()
def test_fill_form(self):
for link in links:
self.browser.get(link)
input1 = self.browser.find_element_by_css_selector('div.first_block input.form-control.first')
input1.send_keys("Ivan")
input2 = self.browser.find_element_by_css_selector('div.first_block input.form-control.second')
input2.send_keys("Petrov")
input3 = self.browser.find_element_by_css_selector('div.first_block input.form-control.third')
input3.send_keys("addr@mail.ru")
self.browser.find_element_by_css_selector("button.btn").click()
time.sleep(1)
welcome_text = self.browser.find_element_by_tag_name("h1").text
self.assertEqual("Congratulations! You have successfully registered!", welcome_text,
"{link} {welcome_text} should be equal 'Congratulations! You have successfully"
" registered!' ")
time.sleep(3)
self.browser.quit()
if __name__ == "__main__":
unittest.main()
|
import qcodes.plots.pyqtgraph as qplt
import numpy as np
import datetime as t
import os
import csv
'''
Data wrapper that can create a live plot (based on qcodes.plots.pyqtgraph),
a text file and a csv file containing the data.
By: Zhang Zhongming
INSTRUCTIONS ON USE
To initialize:
data = Data(<directory>, <experiment_name>, <column_block_size>)
Remark: The directory is where all the data will be stored, the folder must be created before
you use this wrapper.
To add a coordinate:
data.add_coordinate(<coordinate name>, <coordinate units>, <coordinate array>)
Remark: coordinate array is a pre-set set of values that the coordinate can take.
Remark: Value is variable that is to be measured
To add a value:
data.add_value(<value name>, <value unit>)
Remark: The coordinate name and value names identifies the coordinate and value.
Important: use DIFFERENT names for every coordinate and value.
To add a 2D plot:
data.add_2D_plot(<plot title>, <coordinate name>, <value name>, newtrace = <bool>,
fig_width = <fig_width>, fig_height = <fig_height>,
fig_x_pos = <fig_x_pos>, fig_y_pos = <fig_y_pos>)
To add a 3D plot:
data.add_3D_plot(<plot title>, <coordinate1 name>, <coordinate2 name>, <value name>,
fig_width = <fig_width>, fig_height = <fig_height>,
fig_x_pos = <fig_x_pos>, fig_y_pos = <fig_y_pos>)
Remark: fig_width and fig_height is in pixels. The width and height of the entire monitor is usually
around 2000 x 1000. fig_x_pos is the position of the top left corner of the window
To open the files:
data.open_files()
To add results to the data object:
data.add_result(<results dictionary>)
Important: data.open_files() must be called before you can call data.add_result()
Remark: The results dictionary is a python dictionary that has as it's key,
coordinate/value names and as the corresponding values, coordinate index/experimental reading
respectively. A coordinate index is the position of the value that the coordinate is taking
on the coordinate array. For example, if the coordinate array is [0.1, 7 ,-4, 5],
a coordinate index of 0 means it is taking the value 0.1, 2 means its taking on -4 and so on.
Important: ALL values and coordinates must be present in the results dictionary.
To add a new trace to all 2D plots:
data.newtraces()
At the end of the measurement:
data.end_measurement()
Remark: end_measurement() closes the text file and saves all plots in the png format.
Important: If this function is not called, the plots will not be saved and
you may lose data on the text file.
The function generate_array(start, stop, step, reverse = False) is useful for generating
the required arrays.
It returns two things, the array meant for the coordinate, and the corresponding array of
coordinate indexes.
for example:
>>> array1, array2 = generate_array(0,10,1, reverse = True)
>>> print(array1)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
>>> print(array2)
[0 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 0]
>>> array1, array2 = generate_array(0,2,0.2, reverse = False)
>>> print(array1)
[0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. ]
>>> print(array2)
[ 0 1 2 3 4 5 6 7 8 9 10]
'''
# --------- USEFUL FUNCTIONS ------------
def generate_array(start, stop, step, reverse = False):
array = np.arange(min(start,stop),max(start,stop) + 1e-10, step)
count_array = np.arange(0, len(array))
if reverse:
count_array = np.hstack((count_array[:-1], np.flip(count_array)))
return array, count_array
else:
return array, count_array
def produce_datetime(time_module):
string = str(time_module.datetime.now())
date_ = string[:10]
time_ = string[11:19]
time_ = time_[:2] + '-' + time_[3:5] + '-' + time_[-2:]
return date_, time_
def make_block(string, size):
string = string
while len(string) <= size:
string += ' '
return string
class Coordinate:
def __init__(self, name, unit, array):
self.name = name
self.unit = unit
self.array = array
class Value:
def __init__(self, name, unit):
self.name = name
self.unit = unit
class TwoDPlot:
def __init__(self, window_title, coordinate, value, fig_width = None, fig_height= None, fig_x_pos= None,
fig_y_pos=None, new_trace=True):
self.title = window_title
self.plot = qplt.QtPlot(window_title=window_title, figsize=(fig_width, fig_height),
fig_x_position=fig_x_pos, fig_y_position=fig_y_pos)
self.coordinate = coordinate
self.value = value
self.new_trace = new_trace
self.trace_count = 0
self.coord_values = []
self.val_values = []
self.newtrace()
def add_value(self, coord_number, value):
call = self.trace_count - 1
self.coord_values[call].append(self.coordinate.array[coord_number])
self.val_values[call].append(value)
self.plot.update_plot()
def newtrace(self):
self.coord_values.append([])
self.val_values.append([])
call = self.trace_count
self.plot.add(x = self.coord_values[call],
y = self.val_values[call],
xlabel = self.coordinate.name,
xunit= self.coordinate.unit,
ylabel = self.value.name,
yunit = self.value.unit)
self.trace_count += 1
class ThreeDPlot:
def __init__(self, window_title, x_coordinate, y_coordinate, value, fig_width = None, fig_height = None
,fig_x_pos = None, fig_y_pos = None):
self.title = window_title
self.plot = qplt.QtPlot(window_title=window_title, figsize = (fig_width, fig_height),
fig_x_position = fig_x_pos, fig_y_position = fig_y_pos)
self.x_coordinate = x_coordinate
self.y_coordinate = y_coordinate
self.value = value
self.x_values = self.x_coordinate.array
self.y_values = self.y_coordinate.array
self.z_values = np.zeros((len(self.x_values),
len(self.y_values)))
self.plot.add(x = self.x_values, y = self.y_values, z = self.z_values,
xlabel = self.x_coordinate.name,
ylabel = self.y_coordinate.name,
zlabel = self.value.name,
xunit = self.x_coordinate.unit,
yunit = self.y_coordinate.unit,
zunit = self.value.unit)
def add_value(self, xcoord, ycoord, value):
self.z_values[xcoord, ycoord] = value
self.plot.update_plot()
# -------- MAIN DATA OBJECT ------------
class Data:
'''
This dictionary contains details of where the windows will pop up and their size.
If the number of plots added exceeds the number of keys, it will crash.
Edit here to add more windows.
'''
plots_dic = {1: {'fig_width': 600, 'fig_height': 450, 'fig_x_pos': 0, 'fig_y_pos': 0},
2: {'fig_width': 600, 'fig_height': 450, 'fig_x_pos': 0.334, 'fig_y_pos': 0},
3: {'fig_width': 600, 'fig_height': 450, 'fig_x_pos': 0.667, 'fig_y_pos': 0},
4: {'fig_width': 600, 'fig_height': 450, 'fig_x_pos': 0, 'fig_y_pos': 0.5},
5: {'fig_width': 600, 'fig_height': 450, 'fig_x_pos': 0.334, 'fig_y_pos': 0.5},
6: {'fig_width': 600, 'fig_height': 450, 'fig_x_pos': 0.667, 'fig_y_pos': 0.5}}
def __init__(self, directory, experiment_name, column_block_size = 40):
self.coordinate_list = []
self.value_list = []
self.plot_number = 0
self.plots_list = []
# -------- DATA FILES ----------
self.directory = directory
self.experiment_name = experiment_name
date_, _time_ = produce_datetime(t)
self.date = date_
self.time = _time_
self.Column_order = []
# -------- TEXT FILES ----------
self.text_file = None
self.column_block_size = column_block_size
# -------- CSV FILES -----------
self.csv_file = None
# --------- COORDINATE AND VALUE -----------------
def add_coordinate(self, name, unit, array):
coord = Coordinate(name, unit, array)
self.coordinate_list.append(coord)
def add_value(self, name, unit):
val = Value(name, unit)
self.value_list.append(val)
def find_coordinate(self, name):
for coord in self.coordinate_list:
if coord.name == name:
return coord
raise Exception('Please add the coordinate first')
def find_value(self, name):
for val in self.value_list:
if val.name == name:
return val
raise Exception('Please add the value first')
# ------------- PLOTS -----------------
def add_2D_plot(self, window_title, coord_name, value_name, newtrace=True):
self.plot_number += 1
n = self.plot_number
width = self.plots_dic[n]['fig_width']
height = self.plots_dic[n]['fig_height']
x_pos = self.plots_dic[n]['fig_x_pos']
y_pos = self.plots_dic[n]['fig_y_pos']
coord = self.find_coordinate(coord_name)
val = self.find_value(value_name)
plot_ = TwoDPlot(window_title, coord, val, fig_width=width, fig_height=height,
fig_x_pos = x_pos, fig_y_pos = y_pos, new_trace=newtrace)
self.plots_list.append(plot_)
def add_3D_plot(self, window_title, x_coord_name, y_coord_name, value_name):
self.plot_number += 1
n = self.plot_number
width = self.plots_dic[n]['fig_width']
height = self.plots_dic[n]['fig_height']
x_pos = self.plots_dic[n]['fig_x_pos']
y_pos = self.plots_dic[n]['fig_y_pos']
xcoord = self.find_coordinate(x_coord_name)
ycoord = self.find_coordinate(y_coord_name)
val = self.find_value(value_name)
plot_ = ThreeDPlot(window_title, xcoord, ycoord, val, fig_width=width, fig_height=height,
fig_x_pos = x_pos, fig_y_pos = y_pos)
self.plots_list.append(plot_)
def add_result_to_plot(self, results_dict):
for plot in self.plots_list:
if isinstance(plot, TwoDPlot):
coord_name = plot.coordinate.name
coord_val = results_dict[coord_name]
value_name = plot.value.name
value_val = results_dict[value_name]
plot.add_value(coord_val, value_val)
# ThreeDPlot
else:
xcoord_name = plot.x_coordinate.name
xcoord_val = results_dict[xcoord_name]
ycoord_name = plot.y_coordinate.name
ycoord_val = results_dict[ycoord_name]
value_name = plot.value.name
value_val = results_dict[value_name]
plot.add_value(xcoord_val, ycoord_val, value_val)
def newtraces(self):
for plot in self.plots_list:
if isinstance(plot, TwoDPlot):
if plot.new_trace:
plot.newtrace()
self.text_file.write('\n\n')
self.csv_file.writerow([])
# -------------- TEXT FILES ----------------
def create_file_name(self, form, label = None):
dir_name = self.directory + '/' + self.date
if not os.path.exists(dir_name):
os.mkdir(dir_name)
dir_name = dir_name + '/' +self.time
if not os.path.exists(dir_name):
os.mkdir(dir_name)
if label:
filename = dir_name + '/' + self.time + '_' + self.experiment_name + '_' + label + form
else:
filename = dir_name + '/' + self.time + '_' + self.experiment_name + form
return filename
def init_data_files(self):
string = self.experiment_name + ' on ' + self.date + ' ' + self.time
self.text_file.write(string + '\n')
self.csv_file.writerow([string, ])
csv_header = [[],[],[]]
Column_no = 1
for coord in self.coordinate_list:
self.text_file.write(f'Column {Column_no}\n\tname: {coord.name}\n\ttype: coordinate\n\tunit: {coord.unit}\n')
Column_no += 1
self.Column_order.append(coord.name)
csv_header[0].append(coord.name)
csv_header[1].append('coordinate')
csv_header[2].append(coord.unit)
for value in self.value_list:
self.text_file.write(f'Column {Column_no}\n\tname: {value.name}\n\ttype: value\n\tunit: {value.unit}\n')
Column_no += 1
self.Column_order.append(value.name)
csv_header[0].append(value.name)
csv_header[1].append('value')
csv_header[2].append(value.unit)
self.text_file.write('\n\n')
for row in csv_header:
self.csv_file.writerow(row)
self.csv_file.writerow([])
def add_result_to_data_files(self, results_dict):
csv_row = []
for name in self.Column_order:
if name in (coord.name for coord in self.coordinate_list):
val = (self.find_coordinate(name)).array[results_dict[name]]
else:
val = results_dict[name]
self.text_file.write(make_block(str(val), self.column_block_size))
csv_row.append(val)
self.csv_file.writerow(csv_row)
self.text_file.write('\n')
# --------- END USER FUNCTIONS -----------
# results_dict is the dictionary { name of coordinate/value :
# coordinate number/ result }
def add_result(self, results_dict):
self.add_result_to_plot(results_dict)
self.add_result_to_data_files(results_dict)
def open_files(self):
filename_txt = self.create_file_name('.txt')
filename_csv = self.create_file_name('.csv')
self.text_file = open(filename_txt, 'w')
self.csv_file = csv.writer(open(filename_csv, 'w'))
self.init_data_files()
def end_measurement(self):
self.text_file.close()
for plot in self.plots_list:
save_name = self.create_file_name('.png', label=plot.title)
print(save_name)
plot.plot.save(save_name)
print('Measurement ended')
|
"""
Hra o trůny
Stáhni si soubor character-deaths.csv, který obsahuje informace o smrti některých postav z prvních pěti
knih románové série Píseň ohně a ledu (A Song of Fire and Ice).
"""
#import wget
#wget.download("https://raw.githubusercontent.com/pesikj/python-012021/master/zadani/5/character-deaths.csv")
#1 Načti soubor do tabulky (DataFrame) a nastav sloupec Name jako index.
import pandas
postavy = pandas.read_csv("character-deaths.csv")
postavy = postavy.set_index("Name")
#2 Zobraz si sloupce, které tabulka má. Posledních pět sloupců tvoří zkratky názvů knih a informace o tom,
# jestli se v knize postava vyskytuje.
print(postavy.columns)
#3 Použij funkci loc ke zjištění informací o smrti postavy jménem "Hali".
pomocne = postavy.loc[:,"Death Year"]
print(pomocne["Hali"])
#4 Použij funkci loc k zobrazení řádků mezi "Gevin Harlaw" a "Gillam".
print(postavy.loc["Gevin Harlaw":"Gillam"])
#5 Použij funkci loc k zobrazení řádků mezi "Gevin Harlaw" a "Gillam" a sloupce Death Year.
print(postavy.loc["Gevin Harlaw":"Gillam", "Death Year"])
#6 Použij funkci loc k zobrazení řádků mezi "Gevin Harlaw" a "Gillam" a informace o tom, v jakých knihách
# se postava vyskytuje, tj. vypiš všechny sloupce mezi GoT a DwD.
print(postavy.loc["Gevin Harlaw":"Gillam","GoT":"DwD"]) |
import numpy as np
import sys
import pickle
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from collections import deque
import random
from simulate import PendulumDynamics
class KMostRecent:
def __init__(self, max_size):
self.max_size = max_size
self.buffer = deque()
def add(self, thing):
self.buffer.appendleft(thing)
if len(self.buffer) > self.max_size:
self.buffer.pop()
def random_sample(self, size):
if size < len(self.buffer):
return random.sample(self.buffer, size)
else:
return list(self.buffer)
def is_full(self):
return len(self.buffer) == self.max_size
class StatusProcessor:
def __init__(self, sim_field_length, sim_max_speed, sim_theta_max, sim_thetadot_max):
self.x_min = -sim_field_length / 2
self.x_max = sim_field_length / 2
self.xdot_min = -sim_max_speed
self.xdot_max = sim_max_speed
self.theta_min = -sim_theta_max
self.theta_max = sim_theta_max
self.thetadot_min = -sim_thetadot_max
self.thetadot_max = sim_thetadot_max
@staticmethod
def _normalize(y, ymin, ymax):
return 2 * (y - ymin) / (ymax - ymin) - 1
@staticmethod
def _denormalize(y, ymin, ymax):
return ymin + (ymax - ymin) * (y + 1) / 2
def _unpack_and_process(self, status, mapper):
x, xdot, theta, thetadot = status
return (
mapper(x, self.x_min, self.x_max),
mapper(xdot, self.xdot_min, self.xdot_max),
mapper(theta, self.theta_min, self.theta_max),
mapper(thetadot, self.thetadot_min, self.thetadot_max),
)
def normalize(self, status):
return self._unpack_and_process(status, self._normalize)
def denormalize(self, status):
return self._unpack_and_process(status, self._denormalize)
def is_valid(self, status):
x, xdot, theta, thetadot = status
return (
self.x_min < x < self.x_max
) and (
self.xdot_min < xdot < self.xdot_max
) and (
self.theta_min < theta < self.theta_max
) and (
self.thetadot_min < thetadot < self.thetadot_max
)
def is_valid_norm(self, status):
return all(-1 <= x <= 1 for x in status)
def remove_nan(x, o):
return o if np.isnan(x) else x
class QNetwork:
nnet_action_size = 3
def __init__(self, state_size, gamma, tau, regularization_coeff,
learning_rate, hidden_state_size, hidden_size):
self.state_size = state_size
self.gamma = gamma
self.tau = tau
self.regularization_coeff = regularization_coeff
self.learning_rate = learning_rate
self.hidden_state_size = hidden_state_size
self.hidden_size = hidden_size
def get_action(self, session, state):
q_vals = session.run(self.output, feed_dict={
self.nnet_input_state: np.array([state] * 3),
self.nnet_input_action: np.array([
[1, 0, 0], [0, 1, 0], [0, 0, 1]
], dtype=np.float32)
})
if q_vals[0][0] >= q_vals[1][0] and q_vals[0][0] >= q_vals[2][0]:
action = -1
q = q_vals[0][0]
elif q_vals[1][0] >= q_vals[0][0] and q_vals[1][0] >= q_vals[2][0]:
action = 0
q = q_vals[1][0]
else: # if q_vals[2][0] >= q_vals[1][0] and q_vals[2][0] >= q_vals[0][0]:
action = 1
q = q_vals[2][0]
return action, q
def learn_from_replay(self, session, batch_replay):
# get q value for each action in the batch
next_moves_q_state, next_moves_q_action = [], []
for state, action, reward, next_state, end in batch_replay:
next_moves_q_state.extend([next_state] * 3)
next_moves_q_action.extend([
[1, 0, 0], [0, 1, 0], [0, 0, 1]
])
q_vals = session.run(self.target_output, feed_dict={
self.nnet_input_state: np.array(next_moves_q_state),
self.nnet_input_action: np.array(next_moves_q_action, dtype=np.float32)
})
# compute expected reward for the states in the batch
batch_inputs_state, batch_inputs_action, batch_outputs = [], [], []
for i, (state, action, reward, next_state, end) in enumerate(batch_replay):
batch_inputs_state.append(state)
batch_inputs_action.append([(0, 1, 0), (0, 0, 1), (1, 0, 0)][action])
consider_future = 0 if end else 1
batch_outputs.append([reward + consider_future * self.gamma * max(
q_vals[3 * i][0], q_vals[3 * i + 1][0], q_vals[3 * i + 2][0]
)])
# backpropagate
_, loss_value = session.run([self.optimizer, self.loss], feed_dict={
self.nnet_input_state: batch_inputs_state,
self.nnet_input_action: batch_inputs_action,
self.nnet_label: batch_outputs,
})
session.run(self.update_target_network_op)
assert not np.isnan(loss_value)
return loss_value
def build(self):
self._build_network()
self._build_target_network()
def _build_network(self):
self.nnet_input_state = tf.placeholder(
shape=[None, self.state_size], dtype=tf.float32, name='nnet_input_state'
)
self.nnet_input_action = tf.placeholder(
shape=[None, self.nnet_action_size], dtype=tf.float32, name='nnet_input_action'
)
self.nnet_label = tf.placeholder(
shape=[None, 1], dtype=tf.float32, name='nnet_label'
)
self.weights_1, self.bias_1 = self._make_weights(self.state_size, self.hidden_state_size)
self.hidden_state_1 = self._compute_next_layer(self.nnet_input_state, self.weights_1, self.bias_1)
self.weights_2, self.bias_2 = self._make_weights(self.hidden_state_size, self.hidden_size)
self.hidden_state_2 = self._compute_next_layer(self.hidden_state_1, self.weights_2, self.bias_2)
self.weights_3, self.bias_3 = self._make_weights(self.nnet_action_size, self.hidden_size)
self.hidden_action = self._compute_next_layer(self.nnet_input_action, self.weights_3, self.bias_3)
self.bias_5 = tf.Variable(tf.constant(0.1, shape=[self.hidden_size]))
self.hidden_combined = tf.nn.relu(self.hidden_state_2 + self.hidden_action + self.bias_5)
self.weights_4, self.bias_4 = self._make_weights(self.hidden_size, 1)
self.output = self._compute_next_layer(self.hidden_combined, self.weights_4, self.bias_4, activation=None)
self.squared_error = (self.nnet_label - self.output)**2
self.loss = tf.reduce_mean(self.squared_error) + self.regularization_coeff * (
tf.reduce_sum(self.weights_1 ** 2) + tf.reduce_sum(self.bias_1 ** 2) +
tf.reduce_sum(self.weights_2 ** 2) + tf.reduce_sum(self.bias_2 ** 2) +
tf.reduce_sum(self.weights_3 ** 2) + tf.reduce_sum(self.bias_3 ** 2) +
tf.reduce_sum(self.weights_4 ** 2) + tf.reduce_sum(self.bias_4 ** 2) +
tf.reduce_sum(self.bias_5 ** 2)
)
self.network_params = [self.weights_1, self.bias_1, self.weights_2,
self.bias_2, self.weights_3, self.bias_3,
self.weights_4, self.bias_4, self.bias_5]
self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
def _build_target_network(self):
self.target_network_params = [tf.Variable(var.initialized_value())
for var in self.network_params]
self.update_target_network_op = [
target_var.assign(self.tau * var + (1 - self.tau) * target_var)
for var, target_var in zip(self.network_params, self.target_network_params)
]
(
self.target_weights_1, self.target_bias_1, self.target_weights_2,
self.target_bias_2, self.target_weights_3, self.target_bias_3,
self.target_weights_4, self.target_bias_4, self.target_bias_5
) = self.target_network_params
self.target_hidden_state_1 = self._compute_next_layer(self.nnet_input_state, self.target_weights_1, self.target_bias_1)
self.target_hidden_state_2 = self._compute_next_layer(self.target_hidden_state_1, self.target_weights_2, self.target_bias_2)
self.target_hidden_action = self._compute_next_layer(self.nnet_input_action, self.target_weights_3, self.target_bias_3)
self.target_hidden_combined = tf.nn.relu(self.target_hidden_state_2 + self.target_hidden_action + self.target_bias_5)
self.target_output = self._compute_next_layer(self.target_hidden_combined, self.target_weights_4, self.target_bias_4, activation=None)
@staticmethod
def _make_weights(rows, cols):
weights = tf.Variable(tf.truncated_normal(shape=[rows, cols], stddev=0.1))
bias = tf.Variable(tf.constant(0.1, shape=[cols]))
return weights, bias
@staticmethod
def _compute_next_layer(input_layer, weights, bias, activation=tf.nn.relu):
h = tf.matmul(input_layer, weights) + bias
return activation(h) if activation else h
class DQNPendulum:
replay_batch_size = 32 # size of the minibatch for experience replay
simulation_length = 500 # how many steps each episode is
num_episodes = 100000 # stop training after this many episodes
replay_buffer_size = 1000000 # how many experiences to keep in the replay buffer
force_factor = 75 # force intensity for bang-bang control
epsilon_decay = 0.00025 # exploration rate coefficient
min_eps = 0.1 # minimum random exploration rate
save_network_every = 25 # checkpoint interval (episodes)
save_network_path = './logs/dqn' # checkpoint location
past_states_count = 4 # input this many last states to the Q network
gamma = 0.99 # Q-learning discount factor
tau = 0.001 # soft update strength for target network
regularization_coeff = 0.001 # regularization in the loss
learning_rate = 0.001 # learning rate for the Q network
nnet_hidden_state_size = 128 # state is processed alone in this hidden layer
nnet_hidden_size = 128 # this layer combines state and action
sim_field_length = 50 # episode fails if pendulum is outside [-l/2, l/2]
sim_max_speed = 100 # episode fails if the cart moves faster than this
sim_theta_max = 10 # episode fails if pendulum angle is more than this
sim_thetadot_max = 100 # episode fails if pendulum rotates faster than this
network_checkpoint = ''
def learn(self):
graph = tf.Graph()
self.qnet = QNetwork(4 * self.past_states_count, self.gamma, self.tau, self.regularization_coeff,
self.learning_rate, self.nnet_hidden_state_size, self.nnet_hidden_size)
with graph.as_default():
self.qnet.build()
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().run()
writer = tf.summary.FileWriter('logs', session.graph)
saver = tf.train.Saver(self.qnet.target_network_params)
replay_buffer = KMostRecent(self.replay_buffer_size)
state_processor = StatusProcessor(self.sim_field_length, self.sim_max_speed,
self.sim_theta_max, self.sim_thetadot_max)
if self.network_checkpoint:
self.qnet.target_network_params = saver.restore(session, self.network_checkpoint)
for episode in range(self.num_episodes):
stats = self.do_episode(session, episode, replay_buffer, state_processor)
self.write_summary(session, episode, writer, saver, replay_buffer, *stats)
writer.close()
def do_episode(self, session, episode_no, replay_buffer, state_processor):
pendulum = PendulumDynamics(0, 0, np.pi, 0)
last_states = KMostRecent(self.past_states_count)
for _ in range(self.past_states_count):
last_states.add(state_processor.normalize(pendulum.state))
end_early, sim_trace, all_losses, all_rewards, all_qs = False, [], [], [], []
for step in range(self.simulation_length):
state = [x for s in last_states.buffer for x in s]
# choose next action
if self.epsilon_decay > 0 and np.random.random() < max(self.min_eps, np.exp(-episode_no * self.epsilon_decay)):
action = random.choice([-1, 0, 1])
else:
action, qval = self.qnet.get_action(session, state)
all_qs.append(qval)
# perform action
sim_trace.append((step * pendulum.dt, state_processor.denormalize(state[-4:]), action))
old_state = state
pendulum.step_simulate(self.force_factor * action)
last_states.add(state_processor.normalize(pendulum.state))
state = [x for s in last_states.buffer for x in s]
# compute reward
if state_processor.is_valid(pendulum.state):
reward = -0.05 * (abs(pendulum.theta) - 3) - 0.001 * (abs(pendulum.x) - 3)
#reward = 0.1 if abs(pendulum.theta) < 0.25 and abs(pendulum.x < 0.25) else -0.001
else:
reward = -10
end_early = True
replay_buffer.add((old_state, action, reward, state, end_early))
all_rewards.append(reward)
# learn
if not end_early:
batch_replay = replay_buffer.random_sample(self.replay_batch_size)
loss_value = self.qnet.learn_from_replay(session, batch_replay)
all_losses.append(loss_value)
return sim_trace, all_losses, all_rewards, all_qs
def write_summary(self, session, episode_no, writer, saver, replay_buffer,
sim_trace, all_losses, all_rewards, all_qs):
summary = tf.Summary()
summary.value.add(tag='avg_loss', simple_value=np.mean(all_losses))
summary.value.add(tag='avg_reward', simple_value=np.mean(all_rewards))
summary.value.add(tag='sum_reward', simple_value=sum(all_rewards))
summary.value.add(tag='avg_q', simple_value=remove_nan(np.mean(all_qs), 0))
summary.value.add(tag='sum_q', simple_value=np.sum(all_qs))
writer.add_summary(summary, global_step=episode_no)
print('Episode %d - L: %.3f\tAR: %.3f\tSR: %.3f\tAQ: %.3f\tSQ: %.3f' % (
episode_no, np.mean(all_losses), np.mean(all_rewards),
sum(all_rewards), np.mean(all_qs), np.sum(all_qs)
))
if episode_no and not episode_no % self.save_network_every:
saver.save(session, self.save_network_path, global_step=episode_no)
with open('./logs/last-episode.csv', 'w') as f:
f.write('t,force,x,xdot,theta,thetadot\n')
for time, state, action in sim_trace:
f.write('%f,%f,%f,%f,%f,%d\n' % (
(time, action * self.force_factor) + state
))
with open('./logs/last-replay-buffer.pckl', 'wb') as f:
pickle.dump(replay_buffer, f)
print('saved')
def parse_args(gp):
for arg in sys.argv[1:]:
name, val = arg.split('=', 1)
if name.startswith('_'):
continue
orig = getattr(gp, name)
if type(orig) == list: # lists must have homogenuous type
value = [type(orig[0])(e) for e in val.split(',')]
elif type(orig) == dict:
value = {}
for kvp in val.split(';'):
k, v = kvp.split(':', 1)
orig[k] = type(orig[k])(v)
value = orig
else:
value = type(orig)(val)
setattr(gp, name, value)
return gp
if __name__ == '__main__':
qp = parse_args(DQNPendulum())
qp.learn()
|
from flask_sqlalchemy import SQLAlchemy
from extensions.sql_alchemy import db
class CandleStickerModel(db.Model):
__tablename__ = 'candle_sticker'
id = db.Column(db.Integer, primary_key=True)
open_value = db.Column(db.Float(40), nullable=False)
close_value = db.Column(db.Float(40), nullable=False)
max_value = db.Column(db.Float(40), nullable=False)
min_value = db.Column(db.Float(40), nullable=False)
periodicity = db.Column(db.Integer, nullable=False)
date_time = db.Column(db.DateTime, nullable=False)
def insert_candle_sticker(candle: dict) -> None:
candle = CandleStickerModel(**candle)
db.session.add(candle)
db.session.commit()
|
import os
mappingFiles = os.listdir("./pred/prediction")
mappingFiles.sort(key=lambda x: int(x[7:-4]))
# mappingFiles = os.listdir("../mapping/")
fileNumber = 1
for file in mappingFiles:
fileIn = open("./pred/prediction/" + file, "r")
# fileIn = open("../mapping/" + file, "r")
mapping = fileIn.readlines()
for i in range(len(mapping) - 1):
mapping[i] = ' '.join(mapping[i].split('\n')[0].split())
err = ''
for i in range(len(mapping) - 1):
for j in range(i + 1, len(mapping)):
if (mapping[i] == mapping[j]):
err = 'In map file {}: str {} and {} are equal to "{}"'.format(
file, i + 1, j + 1, mapping[i])
print(err)
break
if (err != ''):
break
if (err == ''):
msg = 'Map file {}: OK!'.format(fileNumber)
print(msg)
fileIn.close()
fileNumber += 1
|
from keras import losses
from keras import backend as K
import settings
################################################################################
# Loss functions
################################################################################
def loss_function_carl(y_true, y_pred):
return losses.binary_crossentropy(y_true[:, 0], y_pred[:, 0])
def loss_function_ratio_regression(y_true, y_pred):
r_loss = losses.mean_squared_error(K.exp(K.clip(y_true[:, 1], -10., 10.)),
K.exp(K.clip(y_pred[:, 1], -10., 10.)))
inverse_r_loss = losses.mean_squared_error(K.exp(-K.clip(y_true[:, 1], -10., 10.)),
K.exp(-K.clip(y_pred[:, 1], -10., 10.)))
return y_true[:, 0] * r_loss + (1. - y_true[:, 0]) * inverse_r_loss
def loss_function_score(y_true, y_pred):
score_loss = losses.mean_squared_error(y_true[:, 2:settings.n_params + 2],
y_pred[:, 2:settings.n_params + 2])
return (1. - y_true[:, 0]) * score_loss
def loss_function_combined(y_true, y_pred, alpha=0.1):
carl_loss = loss_function_carl(y_true, y_pred)
score_loss = loss_function_score(y_true, y_pred)
return carl_loss + alpha*score_loss
def loss_function_combinedregression(y_true, y_pred, alpha=0.005):
ratio_regr_loss = loss_function_ratio_regression(y_true, y_pred)
score_loss = loss_function_score(y_true, y_pred)
return ratio_regr_loss + alpha*score_loss
def loss_function_score_regression(y_true, y_pred):
return losses.mean_squared_error(y_true[:, :], y_pred[:, :])
|
from dcgan import DCGAN
import matplotlib.pyplot as plt
import numpy as np
def create_image(gen_imgs, name, xsize=4, ysize=4):
fig, axs = plt.subplots(xsize, ysize, figsize=(xsize*2,ysize*2))
plt.subplots_adjust(left=0.05,bottom=0.05,right=0.95,top=0.95, wspace=0.2, hspace=0.2)
cnt = 0
for i in range(ysize):
for j in range(xsize):
axs[i,j].imshow(gen_imgs[cnt])
axs[i,j].axis('off')
cnt += 1
fig.savefig(name, facecolor='white' )
plt.close()
if __name__ == "__main__":
# make sure to load in the correct sized data
dcgan = DCGAN(img_rows = 128,
img_cols = 128,
channels = 3,
latent_dim=256,
name='goodsell_256_128')
dcgan.load_weights(generator_file="generator ({})4000.h5".format(dcgan.name), discriminator_file="discriminator ({}).h5".format(dcgan.name))
# starting point for every image
seed_start = np.random.normal(0, 1, (16, dcgan.latent_dim))
# these parameters will change every time step
latentSpeed = np.random.normal(3, 1, (16, dcgan.latent_dim))
vary = np.copy(seed_start)
# video settings
time = 0
fps = 30
maxTime = 60 # seconds
frameCount = 0
while (time <= maxTime):
# for each image
for i in range(len(seed_start)):
# change the latent variables
for j in range(dcgan.latent_dim):
vary[i][j] = seed_start[i][j] + np.sin( 2*np.pi*(time/maxTime) * latentSpeed[i][j] )
gen_imgs = dcgan.generator.predict(vary)
create_image(gen_imgs, "images/goodsell_{0:05d}.png".format(frameCount) )
frameCount += 1
time += 1./fps
# ffmpeg -framerate 30 -i "galaxy_%05d.png" -i "Khruangbin_Friday Morning.mp3" -map 0:v:0 -map 1:a:0 -shortest -c:v libx264 -pix_fmt yuv420p -strict -2 galaxy.mp4
# ffmpeg -framerate 30 -i "nebula_%05d.png" -i "planet_caravan.mp3" -map 0:v:0 -map 1:a:0 -c:v libx264 -pix_fmt yuv420p nebula.mp4
# ffmpeg -framerate 30 -i "fluidart_%05d.png" -c:v libx264 -pix_fmt yuv420p fluidart.mp4 |
import unittest
import collections
import dafpy as dfp
######################################
# Some definitions for the tests
######################################
class DataGenerator(object):
def __call__(self):
return {'observations': 10}
@dfp.set_call_rets_decorator('trade')
def decision(position, observation):
return 10
@dfp.set_call_rets_decorator('trade')
def execution(trade):
return trade * 0.99
@dfp.set_call_rets_decorator('sum')
def add(a, b):
return a + b
class DataAppender(object):
def __init__(self):
self.data = []
def __call__(self, data):
self.data.append(data)
class TestDAFPYDec(unittest.TestCase):
def setUp(self):
self.terminal_node = DataAppender()
self.nodes = {
'Data': DataGenerator(),
'Decision': decision,
'Execution': execution,
'Position Update': add,
'Lagged Position': dfp.Lag(0),
'Terminal Node': self.terminal_node,
}
self.edges = [
('Data', 'Decision', 'observations', 'observation'),
('Lagged Position', 'Decision', 'position'),
('Decision', 'Execution', 'trade', 'trade'),
('Execution', 'Position Update', 'trade', 'a'),
('Lagged Position', 'Position Update', 'b'),
('Position Update', 'Lagged Position'),
('Lagged Position', 'Terminal Node', 'data'),
]
def test_terminal_node_data(self):
g = dfp.DataflowEnvironment.from_items(self.nodes, self.edges)
g.start()
l = [g() for __ in range(10)]
assert l == [None] * 10
assert self.terminal_node.data[-1] == 89.10000000000001
|
def solve_part_1(data):
answers = []
answer_data = {
"group_members": 0,
"answers": ''
}
for line in data:
if line == '':
answers.append(answer_data)
answer_data = {
"group_members": 0,
"answers": ''
}
else:
answer_data['group_members'] += 1
answer_data['answers'] += line
answers.append(answer_data)
sum = 0
for group_answers in answers:
answer_map = {}
for answer in group_answers['answers']:
if answer not in answer_map:
answer_map[answer] = 0
answer_map[answer] += 1
for answer in answer_map.values():
print(answer)
if answer == group_answers['group_members']:
sum += 1
print(f"Sum: {sum}")
def solve_part_2(data):
pass
if __name__ == "__main__":
input = open('input.txt', 'r').read().splitlines()
solve_part_1(input)
input_two= open('input.txt', 'r').read().splitlines()
solve_part_2(input_two) |
filename = 'text_files/write2.txt'
# Make a dice class
from random import randint
class Die:
"""A Simple Dice object"""
def __init__(self,sides=6):
"""Initialize name and sides of dice"""
self.sides = sides
def roll_die(self):
return(randint(1,self.sides))
# Make new 6 sided die
new_die = Die()
turn = 0
# Roll the dice and write the turn into a file. Amend the file and do it 100 times.
with open(filename, 'a') as file_object:
while turn < 100:
file_object.write(str(new_die.roll_die()))
turn += 1 |
"""
There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections where connections[i] = [a, b] represents a road from city a to b.
This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
It's guaranteed that each city can reach the city 0 after reorder.
Example 1:
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 2:
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 3:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Constraints:
2 <= n <= 5 * 10^4
connections.length == n-1
connections[i].length == 2
0 <= connections[i][0], connections[i][1] <= n-1
connections[i][0] != connections[i][1]
"""
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
self.ans=0
visited=set()
those_to =collections.defaultdict(list)
those_from=collections.defaultdict(list)
for a,b in connections:
those_to[b].append(a) # b is from a
those_from[a].append(b) # from a to b
bfs_q = collections.deque([0])
while bfs_q:
n = bfs_q[0]
visited.add(n)
bfs_q.popleft()
for e in those_to[n]: # no need to reorder
if e not in visited:
bfs_q.append(e)
for e in those_from[n]: # need to reorder
if e not in visited:
bfs_q.append(e)
self.ans+=1
return self.ans
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Department'
db.create_table(u'kb_department', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('label', self.gf('django.db.models.fields.CharField')(max_length=50)),
))
db.send_create_signal(u'kb', ['Department'])
# Adding model 'Course'
db.create_table(u'kb_course', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('dept', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['kb.Department'])),
('num', self.gf('django.db.models.fields.CharField')(max_length=50)),
('title', self.gf('django.db.models.fields.CharField')(max_length=200)),
))
db.send_create_signal(u'kb', ['Course'])
# Adding model 'Times'
db.create_table(u'kb_times', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('mon', self.gf('django.db.models.fields.IntegerField')()),
('tue', self.gf('django.db.models.fields.IntegerField')()),
('wed', self.gf('django.db.models.fields.IntegerField')()),
('thu', self.gf('django.db.models.fields.IntegerField')()),
('fri', self.gf('django.db.models.fields.IntegerField')()),
('duration', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal(u'kb', ['Times'])
# Adding model 'Offering'
db.create_table(u'kb_offering', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('course', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['kb.Course'])),
('year', self.gf('django.db.models.fields.IntegerField')()),
('term', self.gf('django.db.models.fields.IntegerField')()),
('times', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['kb.Times'], unique=True)),
))
db.send_create_signal(u'kb', ['Offering'])
def backwards(self, orm):
# Deleting model 'Department'
db.delete_table(u'kb_department')
# Deleting model 'Course'
db.delete_table(u'kb_course')
# Deleting model 'Times'
db.delete_table(u'kb_times')
# Deleting model 'Offering'
db.delete_table(u'kb_offering')
models = {
u'kb.course': {
'Meta': {'object_name': 'Course'},
'dept': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['kb.Department']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'num': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'kb.department': {
'Meta': {'object_name': 'Department'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'kb.offering': {
'Meta': {'object_name': 'Offering'},
'course': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['kb.Course']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'term': ('django.db.models.fields.IntegerField', [], {}),
'times': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['kb.Times']", 'unique': 'True'}),
'year': ('django.db.models.fields.IntegerField', [], {})
},
u'kb.times': {
'Meta': {'object_name': 'Times'},
'duration': ('django.db.models.fields.IntegerField', [], {}),
'fri': ('django.db.models.fields.IntegerField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mon': ('django.db.models.fields.IntegerField', [], {}),
'thu': ('django.db.models.fields.IntegerField', [], {}),
'tue': ('django.db.models.fields.IntegerField', [], {}),
'wed': ('django.db.models.fields.IntegerField', [], {})
}
}
complete_apps = ['kb'] |
'''
Copyright (c) 2018 Tobias Sommer
Licensed under the MIT License. See LICENSE file in the project root for full license information.
'''
import os
import base64
LOG_PATH = "logfile.log"
APPLICATION_NAME = os.environ.get('APPLICATION_NAME')
SERVER_PORT = os.environ.get('SERVER_PORT')
MICROSERVICE_SUBSCRIPTION_ENABLED = os.environ.get('MICROSERVICE_SUBSCRIPTION_ENABLED')
C8Y_BASEURL = os.environ.get('C8Y_BASEURL')
C8Y_BASEURL_MQTT = os.environ.get('C8Y_BASEURL_MQTT')
C8Y_MICROSERVICE_ISOLATION = os.environ.get('C8Y_MICROSERVICE_ISOLATION')
C8Y_BOOTSTRAP_REGISTER = os.environ.get('C8Y_BOOTSTRAP_REGISTER')
C8Y_BOOTSTRAP_TENANT = os.environ.get('C8Y_BOOTSTRAP_TENANT')
C8Y_BOOTSTRAP_USER = os.environ.get('C8Y_BOOTSTRAP_USER')
C8Y_BOOTSTRAP_PASSWORD = os.environ.get('C8Y_BOOTSTRAP_PASSWORD')
C8Y_TENANT = os.environ.get('C8Y_TENANT')
C8Y_USER = os.environ.get('C8Y_USER')
C8Y_PASSWORD = os.environ.get('C8Y_PASSWORD')
MEMORY_LIMIT = os.environ.get('MEMORY_LIMIT')
PROXY_HTTP_HOST = os.environ.get('PROXY_HTTP_HOST')
PROXY_HTTP_PORT = os.environ.get('PROXY_HTTP_PORT')
PROXY_HTTP_NON_PROXY_HOSTS = os.environ.get('PROXY_HTTP_NON_PROXY_HOSTS')
PROXY_HTTPS_HOST = os.environ.get('PROXY_HTTPS_HOST')
PROXY_HTTPS_PORT = os.environ.get('PROXY_HTTPS_PORT')
PROXY_SOCKS_HOST = os.environ.get('PROXY_SOCKS_HOST')
PROXY_SOCKS_PORT = os.environ.get('PROXY_SOCKS_PORT')
BOOTSTRAP_AUTHENTHICATION_HEADER = 'Basic ' + base64.b64encode((C8Y_BOOTSTRAP_TENANT + '/' + C8Y_BOOTSTRAP_USER + ':' + C8Y_BOOTSTRAP_PASSWORD).encode()).decode() |
from Raton import Raton
from Teclado import Teclado
from Monitor import Monitor
class Computadora:
contadorComputadoras = 0
def __init__(self, nombre, monitor, teclado, raton):
self._idComputadora = Computadora.aumentarId()
self._nombre = nombre
self._monitor = monitor
self._teclado = teclado
self._raton = raton
@classmethod
def aumentarId(cls):
cls.contadorComputadoras += 1
return cls.contadorComputadoras
@property
def idComputadora(self):
return self._idComputadora
@idComputadora.setter
def idComputadora(self, idComputadora):
self._idComputadora = idComputadora
@property
def nombre(self):
return self._nombre
@property
def monitor(self):
return self._monitor
@property
def teclado(self):
return self._teclado
@property
def raton(self):
return self._raton
@nombre.setter
def nombre(self, nombre):
self._nombre = nombre
@monitor.setter
def monitor(self, monitor):
self._monitor = monitor
@teclado.setter
def teclado(self, teclado):
self._teclado = teclado
@raton.setter
def raton(self, raton):
self._raton = raton
def __str__(self):
return f'''{self._nombre}: {self._idComputadora}
{self._monitor}
{self._teclado}
{self._raton}
'''
# Para testear
if __name__ == "__main__":
monitor1 = Monitor("LG", "Chico")
monitor2 = Monitor("Samsung", "Mediano")
monitor3 = Monitor("Sony", "Grande")
raton1 = Raton('USB', 'Razer')
teclado1 = Teclado('Wireless', 'X Factor')
computadora1 = Computadora('HP', monitor3, teclado1, raton1)
print(computadora1) |
import sys
import os
import time
# ---
goals = {
'Get enough sleep': 3,
'Pass exams': 5,
'Party hard': 4
}
actions = {
'Go to bed': {
'Get enough sleep': -2,
'Pass exams': 1,
'Party hard': 0
},
'Pull all-nighter at the Library': {
'Get enough sleep': 5,
'Pass exams': -4,
'Party hard': 1
},
'Study for exams': {
'Get enough sleep': 0,
'Pass exams': -2,
'Party hard': 1
},
'Have a few quiet drinks with the lads': {
'Get enough sleep': 0,
'Pass exams': 1,
'Party hard': -2
},
'Head to Revs': {
'Get enough sleep': 5,
'Pass exams': 1,
'Party hard': -4
}
}
# ---
def cls():
os.system('cls')
# ----
def printGoalValues():
cls()
print()
for goal, value in goals.items():
print(goal.ljust(20) + '| ' + str(value).rjust(2) + ' | ' + ('#'*value))
# ---
def goalsAchieved():
for goal, value in goals.items():
if value > 0:
return False
return True
# ---
def goalFailed():
for goal, value in goals.items():
if value >= 10:
return True
return False
# ---
def chooseMostImportantGoal():
result = None
for goal, value in goals.items():
if result == None or (value > goals[result] and value > 0):
result = goal
return result
# ---
def getUtility(goal, outcomes):
algorithms = {
'1': getUtility1,
'2': getUtility2,
'3': getUtility3,
}
return algorithms[sys.argv[1]](goal, outcomes)
# ---
def getUtility1(goal, outcomes):
return -outcomes[goal]
# ---
def getUtility2(goal, outcomes):
for outcomeGoal, outcomeChange in outcomes.items():
if goals[outcomeGoal] + outcomeChange >= 10:
return 0
return -outcomes[goal]
# ---
def getUtility3(goal, outcomes):
sideEffects = 0
for outcomeGoal, outcomeChange in outcomes.items():
if goals[outcomeGoal] + outcomeChange >= 10:
return 0
elif outcomeGoal != goal:
sideEffects += outcomeChange
return -outcomes[goal] + sideEffects
# ---
def chooseBestAction(goal):
result = None
bestUtility = None
for action, outcomes in actions.items():
if goal in outcomes:
utility = getUtility(goal, outcomes)
if result == None or utility > bestUtility:
result = action
bestUtility = utility
return result
# ---
def executeAction(action):
for goal in actions[action]:
goals[goal] += actions[action][goal]
if goals[goal] > 10:
goals[goal] = 10
# ---
while not goalsAchieved():
printGoalValues()
goal = chooseMostImportantGoal()
action = chooseBestAction(goal)
print()
print('Goal: ' + goal)
print('Action: ' + action)
executeAction(action)
if goalFailed():
break
time.sleep(0.2)
printGoalValues()
print()
print('Goal: ' + goal)
print('Action: ' + action) |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 06:18:53 2019
@author: Eric Born
"""
from random import shuffle
playerNum = 3
class Card(object):
suit = [None, 'Hearts', 'Diamonds', 'Spades', 'Clubs']
rank = [None, '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace',]
def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank
def __str__(self):
return '%s of %s' % (Card.rank[self.rank],
Card.suit[self.suit])
class Deck(object):
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def add_card(self, card):
'''Adds a card to the deck.'''
self.cards.append(card)
def remove_card(self, card):
'''Removes a card from the deck.'''
self.cards.remove(card)
def pop_card(self, i=-1):
'''removes a card from the top of the deck'''
return self.cards.pop(i)
def shuffleDeck(self):
'''shuffles the cards'''
shuffle(self.cards)
def deal(self, hand):
hand.add_card(self.pop_card())
class Player(Deck):
def __init__(self, num=0, label=''):
self.cards = []
self.num = num
self.label = label
'''
def sort(self):
self.cards.sort
'''
class Score(Player):
def __init__(self, score=0):
self.score = score
STRAIGHT_FLUSH = 8000000
FOUR_OF_A_KIND = 7000000
FULL_HOUSE = 6000000
FLUSH = 5000000
STRAIGHT = 4000000
SET = 3000000
TWO_PAIRS = 2000000
ONE_PAIR = 1000000
def valueHand(Player):
if isFlush(h) and isStraight(h)
return valueStraightFlush(h)
else if ( is4s(h) )
return valueFourOfAKind(h)
else if ( isFullHouse(h) )
return valueFullHouse(h)
else if ( isFlush(h) )
return valueFlush(h)
else if ( isStraight(h) )
return valueStraight(h)
else if ( is3s(h) )
return valueSet(h)
else if ( is22s(h) )
return valueTwoPairs(h)
else if ( is2s(h) )
return valueOnePair(h)
else
return valueHighCard(h)
def find_defining_class(obj, method_name):
"""Finds and returns the class object that will provide
the definition of method_name (as a string) if it is
invoked on obj.
obj: any python object
method_name: string method name
"""
for ty in type(obj).mro():
if method_name in ty.__dict__:
return ty
return None
if __name__ == '__main__':
deck = Deck()
deck.shuffleDeck()
#hand = Hand()
#print(find_defining_class(hand, 'shuffle'))
#Player(1, deck.pocket(hand))
#deck.pocket(hand)
#hand.sort()
#deck.deal(players[1]) #deal 1 card to player number
#intialize players based on playerNum variable
players = []
for i in range(playerNum):
#players.append(Player((i+1), deck.deal))
players.append(Player(i+1))
#deal 2 cards to each player
for i in range(2):
for k in range(len(players)):
deck.deal(players[k])
#initialize dealer
dealer = []
dealer.append(Player(0))
#dealer burns one card
deck.pop_card()
#dealer takes 3 cards (flop)
for i in range(3):
deck.deal(dealer[0])
#make prediction here
#dealer takes 1 card (the turn)
deck.deal(dealer[0])
#dealer takes last card (the river)
deck.deal(dealer[0])
#make final prediciton
players[0].cards[0].rank
print(players[1])
print(players[1])
print(players[2])
print(dealer[0])
print(deck) |
from __future__ import division
def compute_extent_size(lattice):
number_of_objects = len(lattice._context._objects)
extent_size_index = {}
for c in lattice:
extent_size_index[c.concept_id] = len(c.extent) / number_of_objects
return extent_size_index |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.