index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
41,360,587
dopplershift/MetPy
refs/heads/stop-dependabot
/examples/formats/NEXRAD_Level_3_File.py
# Copyright (c) 2015,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ NEXRAD Level 3 File =================== Use MetPy to read information from a NEXRAD Level 3 (NIDS product) file and plot """ import matplotlib.pyplot as plt import numpy as np from metpy.cbook import get_test_data from metpy.io import Level3File from metpy.plots import add_metpy_logo, add_timestamp, colortables ########################################### fig, axes = plt.subplots(1, 2, figsize=(15, 8)) add_metpy_logo(fig, 190, 85, size='large') ctables = (('NWSStormClearReflectivity', -20, 0.5), # dBZ ('NWS8bitVel', -100, 1.0)) # m/s for v, ctable, ax in zip(('N0Q', 'N0U'), ctables, axes): # Open the file name = get_test_data(f'nids/KOUN_SDUS54_{v}TLX_201305202016', as_file_obj=False) f = Level3File(name) # Pull the data out of the file object datadict = f.sym_block[0][0] # Turn into an array using the scale specified by the file data = f.map_data(datadict['data']) # Grab azimuths and calculate a range based on number of gates az = np.array(datadict['start_az'] + [datadict['end_az'][-1]]) rng = np.linspace(0, f.max_range, data.shape[-1] + 1) # Convert az,range to x,y xlocs = rng * np.sin(np.deg2rad(az[:, np.newaxis])) ylocs = rng * np.cos(np.deg2rad(az[:, np.newaxis])) # Plot the data norm, cmap = colortables.get_with_steps(*ctable) ax.pcolormesh(xlocs, ylocs, data, norm=norm, cmap=cmap) ax.set_aspect('equal', 'datalim') ax.set_xlim(-40, 20) ax.set_ylim(-30, 30) add_timestamp(ax, f.metadata['prod_time'], y=0.02, high_contrast=True) plt.show()
{"/src/metpy/plots/declarative.py": ["/src/metpy/plots/__init__.py"], "/src/metpy/plots/__init__.py": ["/src/metpy/plots/declarative.py"]}
41,360,588
dopplershift/MetPy
refs/heads/stop-dependabot
/src/metpy/io/metar.py
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Parse METAR-formatted data.""" # Import the necessary libraries from collections import namedtuple from datetime import datetime import warnings import numpy as np import pandas as pd from ._tools import open_as_needed from .metar_parser import parse, ParseError from .station_data import station_info from ..calc import altimeter_to_sea_level_pressure, wind_components from ..package_tools import Exporter from ..plots.wx_symbols import wx_code_map from ..units import units exporter = Exporter(globals()) # Configure the named tuple used for storing METAR data Metar = namedtuple('metar', ['station_id', 'latitude', 'longitude', 'elevation', 'date_time', 'wind_direction', 'wind_speed', 'current_wx1', 'current_wx2', 'current_wx3', 'skyc1', 'skylev1', 'skyc2', 'skylev2', 'skyc3', 'skylev3', 'skyc4', 'skylev4', 'cloudcover', 'temperature', 'dewpoint', 'altimeter', 'current_wx1_symbol', 'current_wx2_symbol', 'current_wx3_symbol']) # Create a dictionary for attaching units to the different variables col_units = {'station_id': None, 'latitude': 'degrees', 'longitude': 'degrees', 'elevation': 'meters', 'date_time': None, 'wind_direction': 'degrees', 'wind_speed': 'kts', 'eastward_wind': 'kts', 'northward_wind': 'kts', 'current_wx1': None, 'current_wx2': None, 'current_wx3': None, 'low_cloud_type': None, 'low_cloud_level': 'feet', 'medium_cloud_type': None, 'medium_cloud_level': 'feet', 'high_cloud_type': None, 'high_cloud_level': 'feet', 'highest_cloud_type': None, 'highest_cloud_level:': None, 'cloud_coverage': None, 'air_temperature': 'degC', 'dew_point_temperature': 'degC', 'altimeter': 'inHg', 'air_pressure_at_sea_level': 'hPa', 'present_weather': None, 'past_weather': None, 'past_weather2': None} @exporter.export def parse_metar_to_dataframe(metar_text, *, year=None, month=None): """Parse a single METAR report into a Pandas DataFrame. Takes a METAR string in a text form, and creates a `pandas.DataFrame` including the essential information (not including the remarks) The parser follows the WMO format, allowing for missing data and assigning nan values where necessary. The WMO code is also provided for current weather, which can be utilized when plotting. Parameters ---------- metar_text : str The METAR report year : int, optional Year in which observation was taken, defaults to current year. Keyword-only argument. month : int, optional Month in which observation was taken, defaults to current month. Keyword-only argument. Returns ------- `pandas.DataFrame` Notes ----- The output has the following columns: 'station_id': Station Identifier (ex. KLOT) 'latitude': Latitude of the observation, measured in degrees 'longitude': Longitude of the observation, measured in degrees 'elevation': Elevation of the observation above sea level, measured in meters 'date_time': Date and time of the observation, datetime object 'wind_direction': Direction the wind is coming from, measured in degrees 'wind_spd': Wind speed, measured in knots 'current_wx1': Current weather (1 of 3) 'current_wx2': Current weather (2 of 3) 'current_wx3': Current weather (3 of 3) 'skyc1': Sky cover (ex. FEW) 'skylev1': Height of sky cover 1, measured in feet 'skyc2': Sky cover (ex. OVC) 'skylev2': Height of sky cover 2, measured in feet 'skyc3': Sky cover (ex. FEW) 'skylev3': Height of sky cover 3, measured in feet 'skyc4': Sky cover (ex. CLR) 'skylev4:': Height of sky cover 4, measured in feet 'cloudcover': Cloud coverage measured in oktas, taken from maximum of sky cover values 'temperature': Temperature, measured in degrees Celsius 'dewpoint': Dew point, measured in degrees Celsius 'altimeter': Altimeter value, measured in inches of mercury, float 'current_wx1_symbol': Current weather symbol (1 of 3), integer 'current_wx2_symbol': Current weather symbol (2 of 3), integer 'current_wx3_symbol': Current weather symbol (3 of 3), integer 'sea_level_pressure': Sea level pressure, derived from temperature, elevation and altimeter value, float """ # Defaults year and/or month to present reported date if not provided if year is None or month is None: now = datetime.now() year = now.year if year is None else year month = now.month if month is None else month # Use the named tuple parsing function to separate metar # Utilizes the station dictionary which contains elevation, latitude, and longitude metar_vars = parse_metar_to_named_tuple(metar_text, station_info, year, month) # Use a pandas dataframe to store the data df = pd.DataFrame({'station_id': metar_vars.station_id, 'latitude': metar_vars.latitude, 'longitude': metar_vars.longitude, 'elevation': metar_vars.elevation, 'date_time': metar_vars.date_time, 'wind_direction': metar_vars.wind_direction, 'wind_speed': metar_vars.wind_speed, 'current_wx1': metar_vars.current_wx1, 'current_wx2': metar_vars.current_wx2, 'current_wx3': metar_vars.current_wx3, 'low_cloud_type': metar_vars.skyc1, 'low_cloud_level': metar_vars.skylev1, 'medium_cloud_type': metar_vars.skyc2, 'medium_cloud_level': metar_vars.skylev2, 'high_cloud_type': metar_vars.skyc3, 'high_cloud_level': metar_vars.skylev3, 'highest_cloud_type': metar_vars.skyc4, 'highest_cloud_level': metar_vars.skylev4, 'cloud_coverage': metar_vars.cloudcover, 'air_temperature': metar_vars.temperature, 'dew_point_temperature': metar_vars.dewpoint, 'altimeter': metar_vars.altimeter, 'present_weather': metar_vars.current_wx1_symbol, 'past_weather': metar_vars.current_wx2_symbol, 'past_weather2': metar_vars.current_wx3_symbol}, index=[metar_vars.station_id]) # Convert to sea level pressure using calculation in metpy.calc try: # Create a field for sea-level pressure and make sure it is a float df['air_pressure_at_sea_level'] = float(altimeter_to_sea_level_pressure( units.Quantity(df.altimeter.values, 'inHg'), units.Quantity(df.elevation.values, 'meters'), units.Quantity(df.temperature.values, 'degC')).to('hPa').magnitude) except AttributeError: df['air_pressure_at_sea_level'] = [np.nan] # Use get wind components and assign them to u and v variables df['eastward_wind'], df['northward_wind'] = wind_components( units.Quantity(df.wind_speed.values, 'kts'), units.Quantity(df.wind_direction.values, 'degree')) # Round the altimeter and sea-level pressure values df['altimeter'] = df.altimeter.round(2) df['air_pressure_at_sea_level'] = df.air_pressure_at_sea_level.round(2) # Set the units for the dataframe--filter out warning from pandas with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) df.units = col_units return df def parse_metar_to_named_tuple(metar_text, station_metadata, year, month): """Parse a METAR report in text form into a list of named tuples. Parameters ---------- metar_text : str The METAR report station_metadata : dict Mapping of station identifiers to station metadata year : int Reported year of observation for constructing 'date_time' month : int Reported month of observation for constructing 'date_time' Returns ------- metar : namedtuple Named tuple of parsed METAR fields Notes ----- Returned data has named tuples with the following attributes: 'station_id': Station Identifier (ex. KLOT) 'latitude': Latitude of the observation, measured in degrees 'longitude': Longitude of the observation, measured in degrees 'elevation': Elevation of the observation above sea level, measured in meters 'date_time': Date and time of the observation, datetime object 'wind_direction': Direction the wind is coming from, measured in degrees 'wind_spd': Wind speed, measured in knots 'current_wx1': Current weather (1 of 3) 'current_wx2': Current weather (2 of 3) 'current_wx3': Current weather (3 of 3) 'skyc1': Sky cover (ex. FEW) 'skylev1': Height of sky cover 1, measured in feet 'skyc2': Sky cover (ex. OVC) 'skylev2': Height of sky cover 2, measured in feet 'skyc3': Sky cover (ex. FEW) 'skylev3': Height of sky cover 3, measured in feet 'skyc4': Sky cover (ex. CLR) 'skylev4:': Height of sky cover 4, measured in feet 'cloudcover': Cloud coverage measured in oktas, taken from maximum of sky cover values 'temperature': Temperature, measured in degrees Celsius 'dewpoint': Dewpoint, measured in degrees Celsius 'altimeter': Altimeter value, measured in inches of mercury, float 'current_wx1_symbol': Current weather symbol (1 of 3), integer 'current_wx2_symbol': Current weather symbol (2 of 3), integer 'current_wx3_symbol': Current weather symbol (3 of 3), integer 'sea_level_pressure': Sea level pressure, derived from temperature, elevation and altimeter value, float """ # Decode the data using the parser (built using Canopy) the parser utilizes a grammar # file which follows the format structure dictated by the WMO Handbook, but has the # flexibility to decode the METAR text when there are missing or incorrectly # encoded values tree = parse(metar_text) # Station ID which is used to find the latitude, longitude, and elevation station_id = tree.siteid.text.strip() # Extract the latitude and longitude values from 'master' dictionary try: lat = station_metadata[tree.siteid.text.strip()].latitude lon = station_metadata[tree.siteid.text.strip()].longitude elev = station_metadata[tree.siteid.text.strip()].altitude except KeyError: lat = np.nan lon = np.nan elev = np.nan # Set the datetime, day, and time_utc try: day_time_utc = tree.datetime.text[:-1].strip() day = int(day_time_utc[0:2]) hour = int(day_time_utc[2:4]) minute = int(day_time_utc[4:7]) date_time = datetime(year, month, day, hour, minute) except (AttributeError, ValueError): date_time = np.nan # Set the wind values try: # If there are missing wind values, set wind speed and wind direction to nan if ('/' in tree.wind.text) or (tree.wind.text == 'KT') or (tree.wind.text == ''): wind_dir = np.nan wind_spd = np.nan # If the wind direction is variable, set wind direction to nan but keep the wind speed else: if (tree.wind.wind_dir.text == 'VRB') or (tree.wind.wind_dir.text == 'VAR'): wind_dir = np.nan wind_spd = float(tree.wind.wind_spd.text) else: # If the wind speed and direction is given, keep the values wind_dir = int(tree.wind.wind_dir.text) wind_spd = int(tree.wind.wind_spd.text) # If there are any errors, return nan except ValueError: wind_dir = np.nan wind_spd = np.nan # Set the weather symbols # If the weather symbol is missing, set values to nan if tree.curwx.text == '': current_wx1 = np.nan current_wx2 = np.nan current_wx3 = np.nan current_wx1_symbol = 0 current_wx2_symbol = 0 current_wx3_symbol = 0 else: wx = [np.nan, np.nan, np.nan] # Loop through symbols and assign according WMO codes wx[0:len((tree.curwx.text.strip()).split())] = tree.curwx.text.strip().split() current_wx1 = wx[0] current_wx2 = wx[1] current_wx3 = wx[2] try: current_wx1_symbol = int(wx_code_map[wx[0]]) except (IndexError, KeyError): current_wx1_symbol = 0 try: current_wx2_symbol = int(wx_code_map[wx[1]]) except (IndexError, KeyError): current_wx2_symbol = 0 try: current_wx3_symbol = int(wx_code_map[wx[3]]) except (IndexError, KeyError): current_wx3_symbol = 0 # Set the sky conditions if tree.skyc.text[1:3] == 'VV': skyc1 = 'VV' skylev1 = tree.skyc.text.strip()[2:] skyc2 = np.nan skylev2 = np.nan skyc3 = np.nan skylev3 = np.nan skyc4 = np.nan skylev4 = np.nan else: skyc = [] skyc[0:len((tree.skyc.text.strip()).split())] = tree.skyc.text.strip().split() try: skyc1 = skyc[0][0:3] if '/' in skyc1: skyc1 = np.nan except (IndexError, ValueError, TypeError): skyc1 = np.nan try: skylev1 = skyc[0][3:] if '/' in skylev1: skylev1 = np.nan else: skylev1 = float(skylev1) * 100 except (IndexError, ValueError, TypeError): skylev1 = np.nan try: skyc2 = skyc[1][0:3] if '/' in skyc2: skyc2 = np.nan except (IndexError, ValueError, TypeError): skyc2 = np.nan try: skylev2 = skyc[1][3:] if '/' in skylev2: skylev2 = np.nan else: skylev2 = float(skylev2) * 100 except (IndexError, ValueError, TypeError): skylev2 = np.nan try: skyc3 = skyc[2][0:3] if '/' in skyc3: skyc3 = np.nan except (IndexError, ValueError): skyc3 = np.nan try: skylev3 = skyc[2][3:] if '/' in skylev3: skylev3 = np.nan else: skylev3 = float(skylev3) * 100 except (IndexError, ValueError, TypeError): skylev3 = np.nan try: skyc4 = skyc[3][0:3] if '/' in skyc4: skyc4 = np.nan except (IndexError, ValueError, TypeError): skyc4 = np.nan try: skylev4 = skyc[3][3:] if '/' in skylev4: skylev4 = np.nan else: skylev4 = float(skylev4) * 100 except (IndexError, ValueError, TypeError): skylev4 = np.nan # Set the cloud cover variable (measured in oktas) if ('OVC' or 'VV') in tree.skyc.text: cloudcover = 8 elif 'BKN' in tree.skyc.text: cloudcover = 6 elif 'SCT' in tree.skyc.text: cloudcover = 4 elif 'FEW' in tree.skyc.text: cloudcover = 2 elif ('SKC' in tree.skyc.text) or ('NCD' in tree.skyc.text) \ or ('NSC' in tree.skyc.text) or 'CLR' in tree.skyc.text: cloudcover = 0 else: cloudcover = 10 # Set the temperature and dewpoint if (tree.temp_dewp.text == '') or (tree.temp_dewp.text == ' MM/MM'): temp = np.nan dewp = np.nan else: try: if 'M' in tree.temp_dewp.temp.text: temp = (-1 * float(tree.temp_dewp.temp.text[-2:])) else: temp = float(tree.temp_dewp.temp.text[-2:]) except ValueError: temp = np.nan try: if 'M' in tree.temp_dewp.dewp.text: dewp = (-1 * float(tree.temp_dewp.dewp.text[-2:])) else: dewp = float(tree.temp_dewp.dewp.text[-2:]) except ValueError: dewp = np.nan # Set the altimeter value and sea level pressure if tree.altim.text == '': altim = np.nan else: if (float(tree.altim.text.strip()[1:5])) > 1100: altim = float(tree.altim.text.strip()[1:5]) / 100 else: altim = units.Quantity(int(tree.altim.text.strip()[1:5]), 'hPa').to('inHg').m # Returns a named tuple with all the relevant variables return Metar(station_id, lat, lon, elev, date_time, wind_dir, wind_spd, current_wx1, current_wx2, current_wx3, skyc1, skylev1, skyc2, skylev2, skyc3, skylev3, skyc4, skylev4, cloudcover, temp, dewp, altim, current_wx1_symbol, current_wx2_symbol, current_wx3_symbol) @exporter.export def parse_metar_file(filename, *, year=None, month=None): """Parse a text file containing multiple METAR reports and/or text products. Parameters ---------- filename : str or file-like object If str, the name of the file to be opened. If `filename` is a file-like object, this will be read from directly. year : int, optional Year in which observation was taken, defaults to current year. Keyword-only argument. month : int, optional Month in which observation was taken, defaults to current month. Keyword-only argument. Returns ------- `pandas.DataFrame` Notes ----- The returned `pandas.DataFrame` has the following columns: 'station_id': Station Identifier (ex. KLOT) 'latitude': Latitude of the observation, measured in degrees 'longitude': Longitude of the observation, measured in degrees 'elevation': Elevation of the observation above sea level, measured in meters 'date_time': Date and time of the observation, datetime object 'wind_direction': Direction the wind is coming from, measured in degrees 'wind_spd': Wind speed, measured in knots 'current_wx1': Current weather (1 of 3) 'current_wx2': Current weather (2 of 3) 'current_wx3': Current weather (3 of 3) 'skyc1': Sky cover (ex. FEW) 'skylev1': Height of sky cover 1, measured in feet 'skyc2': Sky cover (ex. OVC) 'skylev2': Height of sky cover 2, measured in feet 'skyc3': Sky cover (ex. FEW) 'skylev3': Height of sky cover 3, measured in feet 'skyc4': Sky cover (ex. CLR) 'skylev4:': Height of sky cover 4, measured in feet 'cloudcover': Cloud coverage measured in oktas, taken from maximum of sky cover values 'temperature': Temperature, measured in degrees Celsius 'dewpoint': Dew point, measured in degrees Celsius 'altimeter': Altimeter value, measured in inches of mercury, float 'current_wx1_symbol': Current weather symbol (1 of 3), integer 'current_wx2_symbol': Current weather symbol (2 of 3), integer 'current_wx3_symbol': Current weather symbol (3 of 3), integer 'sea_level_pressure': Sea level pressure, derived from temperature, elevation and altimeter value, float """ # Defaults year and/or month to present reported date if not provided if year is None or month is None: now = datetime.now() year = now.year if year is None else year month = now.month if month is None else month # Function to merge METARs def merge(x, key=' '): tmp = [] for i in x: if (i[0:len(key)] != key) and len(tmp): yield ' '.join(tmp) tmp = [] if i.startswith(key): i = i[5:] tmp.append(i) if len(tmp): yield ' '.join(tmp) # Open the file myfile = open_as_needed(filename, 'rt') # Clean up the file and take out the next line (\n) value = myfile.read().rstrip() list_values = value.split('\n') list_values = list(filter(None, list_values)) # Call the merge function and assign the result to the list of metars list_values = list(merge(list_values)) # Remove the short lines that do not contain METAR observations or contain # METAR observations that lack a robust amount of data metars = [] for metar in list_values: if len(metar) > 25: metars.append(metar) else: continue # Create a dictionary with all the station name, locations, and elevations master = station_info # Setup lists to append the data to station_id = [] lat = [] lon = [] elev = [] date_time = [] wind_dir = [] wind_spd = [] current_wx1 = [] current_wx2 = [] current_wx3 = [] skyc1 = [] skylev1 = [] skyc2 = [] skylev2 = [] skyc3 = [] skylev3 = [] skyc4 = [] skylev4 = [] cloudcover = [] temp = [] dewp = [] altim = [] current_wx1_symbol = [] current_wx2_symbol = [] current_wx3_symbol = [] # Loop through the different metars within the text file for metar in metars: try: # Parse the string of text and assign to values within the named tuple metar = parse_metar_to_named_tuple(metar, master, year=year, month=month) # Append the different variables to their respective lists station_id.append(metar.station_id) lat.append(metar.latitude) lon.append(metar.longitude) elev.append(metar.elevation) date_time.append(metar.date_time) wind_dir.append(metar.wind_direction) wind_spd.append(metar.wind_speed) current_wx1.append(metar.current_wx1) current_wx2.append(metar.current_wx2) current_wx3.append(metar.current_wx3) skyc1.append(metar.skyc1) skylev1.append(metar.skylev1) skyc2.append(metar.skyc2) skylev2.append(metar.skylev2) skyc3.append(metar.skyc3) skylev3.append(metar.skylev3) skyc4.append(metar.skyc4) skylev4.append(metar.skylev4) cloudcover.append(metar.cloudcover) temp.append(metar.temperature) dewp.append(metar.dewpoint) altim.append(metar.altimeter) current_wx1_symbol.append(metar.current_wx1_symbol) current_wx2_symbol.append(metar.current_wx2_symbol) current_wx3_symbol.append(metar.current_wx3_symbol) except ParseError: continue df = pd.DataFrame({'station_id': station_id, 'latitude': lat, 'longitude': lon, 'elevation': elev, 'date_time': date_time, 'wind_direction': wind_dir, 'wind_speed': wind_spd, 'current_wx1': current_wx1, 'current_wx2': current_wx2, 'current_wx3': current_wx3, 'low_cloud_type': skyc1, 'low_cloud_level': skylev1, 'medium_cloud_type': skyc2, 'medium_cloud_level': skylev2, 'high_cloud_type': skyc3, 'high_cloud_level': skylev3, 'highest_cloud_type': skyc4, 'highest_cloud_level': skylev4, 'cloud_coverage': cloudcover, 'air_temperature': temp, 'dew_point_temperature': dewp, 'altimeter': altim, 'present_weather': current_wx1_symbol, 'past_weather': current_wx2_symbol, 'past_weather2': current_wx3_symbol}, index=station_id) # Calculate sea-level pressure from function in metpy.calc df['air_pressure_at_sea_level'] = altimeter_to_sea_level_pressure( units.Quantity(altim, 'inHg'), units.Quantity(elev, 'meters'), units.Quantity(temp, 'degC')).to('hPa').magnitude # Use get wind components and assign them to eastward and northward winds df['eastward_wind'], df['northward_wind'] = wind_components( units.Quantity(df.wind_speed.values, 'kts'), units.Quantity(df.wind_direction.values, 'degree')) # Drop duplicate values df = df.drop_duplicates(subset=['date_time', 'latitude', 'longitude'], keep='last') # Round altimeter and sea-level pressure values df['altimeter'] = df.altimeter.round(2) df['air_pressure_at_sea_level'] = df.air_pressure_at_sea_level.round(2) # Set the units for the dataframe--filter out warning from Pandas with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) df.units = col_units return df
{"/src/metpy/plots/declarative.py": ["/src/metpy/plots/__init__.py"], "/src/metpy/plots/__init__.py": ["/src/metpy/plots/declarative.py"]}
41,360,589
dopplershift/MetPy
refs/heads/stop-dependabot
/src/metpy/plots/__init__.py
# Copyright (c) 2014,2015,2016,2017 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause r"""Contains functionality for making meteorological plots.""" import logging # Trigger matplotlib wrappers from . import _mpl # noqa: F401 from ._util import (add_metpy_logo, add_timestamp, add_unidata_logo, # noqa: F401 convert_gempak_color) from .ctables import * # noqa: F403 from .declarative import * # noqa: F403 from .skewt import * # noqa: F403 from .station_plot import * # noqa: F403 from .wx_symbols import * # noqa: F403 logger = logging.getLogger(__name__) __all__ = ctables.__all__[:] # pylint: disable=undefined-variable __all__.extend(declarative.__all__) # pylint: disable=undefined-variable __all__.extend(skewt.__all__) # pylint: disable=undefined-variable __all__.extend(station_plot.__all__) # pylint: disable=undefined-variable __all__.extend(wx_symbols.__all__) # pylint: disable=undefined-variable __all__.extend(['add_metpy_logo', 'add_timestamp', 'add_unidata_logo', 'convert_gempak_color']) try: from .cartopy_utils import USCOUNTIES, USSTATES # noqa: F401 __all__.extend(['USCOUNTIES', 'USSTATES']) except ImportError: logger.warning('Cannot import USCOUNTIES and USSTATES without Cartopy installed.')
{"/src/metpy/plots/declarative.py": ["/src/metpy/plots/__init__.py"], "/src/metpy/plots/__init__.py": ["/src/metpy/plots/declarative.py"]}
41,360,590
dopplershift/MetPy
refs/heads/stop-dependabot
/tests/io/test_station_data.py
# Copyright (c) 2020 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test station data information.""" import numpy as np from numpy.testing import assert_almost_equal import pandas as pd from metpy.io import add_station_lat_lon def test_add_lat_lon_station_data(): """Test for when the METAR does not correspond to a station in the dictionary.""" df = pd.DataFrame({'station': ['KOUN', 'KVPZ', 'KDEN', 'PAAA']}) df = add_station_lat_lon(df, 'station') assert_almost_equal(df.loc[df.station == 'KOUN'].latitude.values[0], 35.25) assert_almost_equal(df.loc[df.station == 'KOUN'].longitude.values[0], -97.47) assert_almost_equal(df.loc[df.station == 'KVPZ'].latitude.values[0], 41.45) assert_almost_equal(df.loc[df.station == 'KVPZ'].longitude.values[0], -87) assert_almost_equal(df.loc[df.station == 'KDEN'].latitude.values[0], 39.85) assert_almost_equal(df.loc[df.station == 'KDEN'].longitude.values[0], -104.65) assert_almost_equal(df.loc[df.station == 'PAAA'].latitude.values[0], np.nan) assert_almost_equal(df.loc[df.station == 'PAAA'].longitude.values[0], np.nan)
{"/src/metpy/plots/declarative.py": ["/src/metpy/plots/__init__.py"], "/src/metpy/plots/__init__.py": ["/src/metpy/plots/declarative.py"]}
41,360,591
dopplershift/MetPy
refs/heads/stop-dependabot
/tests/io/test_metar.py
# Copyright (c) 2008,2015,2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test various metars.""" from datetime import datetime import numpy as np from numpy.testing import assert_almost_equal, assert_equal import pytest from metpy.cbook import get_test_data from metpy.io import parse_metar_file, parse_metar_to_dataframe def test_station_id_not_in_dictionary(): """Test for when the METAR does not correspond to a station in the dictionary.""" df = parse_metar_to_dataframe('METAR KLBG 261155Z AUTO 00000KT 10SM CLR 05/00 A3001 RMK ' 'AO2=') assert df.station_id.values == 'KLBG' assert_almost_equal(df.latitude.values, np.nan) assert_almost_equal(df.longitude.values, np.nan) assert_almost_equal(df.elevation.values, np.nan) assert_almost_equal(df.wind_direction.values, 0) assert_almost_equal(df.wind_speed.values, 0) def test_broken_clouds(): """Test for skycover when there are broken clouds.""" df = parse_metar_to_dataframe('METAR KLOT 261155Z AUTO 00000KT 10SM BKN100 05/00 A3001 ' 'RMK AO2=') assert df.low_cloud_type.values == 'BKN' assert df.cloud_coverage.values == 6 def test_few_clouds_(): """Test for skycover when there are few clouds.""" df = parse_metar_to_dataframe('METAR KMKE 266155Z AUTO /////KT 10SM FEW100 05/00 A3001 ' 'RMK AO2=') assert df.low_cloud_type.values == 'FEW' assert df.cloud_coverage.values == 2 assert_almost_equal(df.wind_direction.values, np.nan) assert_almost_equal(df.wind_speed.values, np.nan) assert_almost_equal(df.date_time.values, np.nan) def test_all_weather_given(): """Test when all possible weather slots are given.""" df = parse_metar_to_dataframe('METAR RJOI 261155Z 00000KT 4000 -SHRA BR VCSH BKN009 ' 'BKN015 OVC030 OVC040 22/21 A2987 RMK SHRAB35E44 SLP114 ' 'VCSH S-NW P0000 60021 70021 T02220206 10256 20211 55000=') assert df.station_id.values == 'RJOI' assert_almost_equal(df.latitude.values, 34.14, decimal=2) assert_almost_equal(df.longitude.values, 132.22, decimal=2) assert df.current_wx1.values == '-SHRA' assert df.current_wx2.values == 'BR' assert df.current_wx3.values == 'VCSH' assert df.low_cloud_type.values == 'BKN' assert df.low_cloud_level.values == 900 assert df.high_cloud_type.values == 'OVC' assert df.high_cloud_level.values == 3000 def test_missing_temp_dewp(): """Test when missing both temperature and dewpoint.""" df = parse_metar_to_dataframe('KIOW 011152Z AUTO A3006 RMK AO2 SLPNO 70020 51013 PWINO=') assert_almost_equal(df.air_temperature.values, np.nan) assert_almost_equal(df.dew_point_temperature.values, np.nan) assert_almost_equal(df.cloud_coverage.values, 10) def test_missing_values(): """Test for missing values from nearly every field.""" df = parse_metar_to_dataframe('METAR KBOU 011152Z AUTO 02006KT //// // ////// 42/02 ' 'Q1004=') assert_almost_equal(df.current_wx1.values, np.nan) assert_almost_equal(df.current_wx2.values, np.nan) assert_almost_equal(df.current_wx3.values, np.nan) assert_almost_equal(df.present_weather.values, 0) assert_almost_equal(df.past_weather.values, 0) assert_almost_equal(df.past_weather2.values, 0) assert_almost_equal(df.low_cloud_type.values, np.nan) assert_almost_equal(df.medium_cloud_type.values, np.nan) assert_almost_equal(df.high_cloud_type.values, np.nan) def test_vertical_vis(): """Test for when vertical visibility is given.""" df = parse_metar_to_dataframe('KSLK 011151Z AUTO 21005KT 1/4SM FG VV002 14/13 A1013 RMK ' 'AO2 SLP151 70043 T01390133 10139 20094 53002=') assert df.low_cloud_type.values == 'VV' def test_date_time_given(): """Test for when date_time is given.""" df = parse_metar_to_dataframe('K6B0 261200Z AUTO 00000KT 10SM CLR 20/M17 A3002 RMK AO2 ' 'T01990165=', year=2019, month=6) assert_equal(df['date_time'][0], datetime(2019, 6, 26, 12)) assert df.eastward_wind.values == 0 assert df.northward_wind.values == 0 def test_parse_metar_df_positional_datetime_failure(): """Test that positional year, month arguments fail for parse_metar_to_dataframe.""" # pylint: disable=too-many-function-args with pytest.raises(TypeError, match='takes 1 positional argument but 3 were given'): parse_metar_to_dataframe('K6B0 261200Z AUTO 00000KT 10SM CLR 20/M17' 'A3002 RMK AO2 T01990165=', 2019, 6) def test_named_tuple_test1(): """Test the named tuple parsing function.""" df = parse_metar_to_dataframe('KDEN 012153Z 09010KT 10SM FEW060 BKN110 BKN220 27/13 ' 'A3010 RMK AO2 LTG DSNT SW AND W SLP114 OCNL LTGICCG ' 'DSNT SW CB DSNT SW MOV E T02670128') assert df.wind_direction.values == 90 assert df.wind_speed.values == 10 assert df.air_temperature.values == 27 assert df.dew_point_temperature.values == 13 def test_parse_file(): """Test the parser on an entire file.""" input_file = get_test_data('metar_20190701_1200.txt', as_file_obj=False) df = parse_metar_file(input_file) test = df[df.station_id == 'KVPZ'] assert test.air_temperature.values == 23 assert test.air_pressure_at_sea_level.values == 1016.76 def test_parse_file_positional_datetime_failure(): """Test that positional year, month arguments fail for parse_metar_file.""" # pylint: disable=too-many-function-args input_file = get_test_data('metar_20190701_1200.txt', as_file_obj=False) with pytest.raises(TypeError, match='takes 1 positional argument but 3 were given'): parse_metar_file(input_file, 2016, 12) def test_parse_file_bad_encoding(): """Test the parser on an entire file that has at least one bad utf-8 encoding.""" input_file = get_test_data('2020010600_sao.wmo', as_file_obj=False) df = parse_metar_file(input_file) test = df[df.station_id == 'KDEN'] assert test.air_temperature.values == 2 assert test.air_pressure_at_sea_level.values == 1024.71 def test_parse_file_object(): """Test the parser reading from a file-like object.""" input_file = get_test_data('metar_20190701_1200.txt', mode='rt') df = parse_metar_file(input_file) test = df[df.station_id == 'KOKC'] assert test.air_temperature.values == 21 assert test.dew_point_temperature.values == 21 assert test.altimeter.values == 30.03
{"/src/metpy/plots/declarative.py": ["/src/metpy/plots/__init__.py"], "/src/metpy/plots/__init__.py": ["/src/metpy/plots/declarative.py"]}
41,360,592
dopplershift/MetPy
refs/heads/stop-dependabot
/tests/interpolate/test_points.py
# Copyright (c) 2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test the `points` module.""" import logging import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_equal import pytest from scipy.spatial import cKDTree, Delaunay from metpy.cbook import get_test_data from metpy.interpolate import (interpolate_to_points, inverse_distance_to_points, natural_neighbor_to_points) from metpy.interpolate.geometry import dist_2, find_natural_neighbors from metpy.interpolate.points import (barnes_point, cressman_point, natural_neighbor_point) logging.getLogger('metpy.interpolate.points').setLevel(logging.ERROR) @pytest.fixture() def test_data(): r"""Return data used for tests in this file.""" x = np.array([8, 67, 79, 10, 52, 53, 98, 34, 15, 58], dtype=float) y = np.array([24, 87, 48, 94, 98, 66, 14, 24, 60, 16], dtype=float) z = np.array([0.064, 4.489, 6.241, 0.1, 2.704, 2.809, 9.604, 1.156, 0.225, 3.364], dtype=float) return x, y, z @pytest.fixture() def test_points(): r"""Return point locations used for tests in this file.""" with get_test_data('interpolation_test_grid.npz') as fobj: data = np.load(fobj) return np.stack([data['xg'].reshape(-1), data['yg'].reshape(-1)], axis=1) def test_nn_point(test_data): r"""Test find natural neighbors for a point interpolation function.""" xp, yp, z = test_data tri = Delaunay(list(zip(xp, yp))) sim_gridx = [30] sim_gridy = [30] members, tri_info = find_natural_neighbors(tri, list(zip(sim_gridx, sim_gridy))) val = natural_neighbor_point(xp, yp, z, [sim_gridx[0], sim_gridy[0]], tri, members[0], tri_info) truth = 1.009 assert_almost_equal(truth, val, 3) def test_cressman_point(test_data): r"""Test Cressman interpolation for a point function.""" xp, yp, z = test_data r = 40 obs_tree = cKDTree(list(zip(xp, yp))) indices = obs_tree.query_ball_point([30, 30], r=r) dists = dist_2(30, 30, xp[indices], yp[indices]) values = z[indices] truth = 1.05499444404 value = cressman_point(dists, values, r) assert_almost_equal(truth, value) def test_barnes_point(test_data): r"""Test Barnes interpolation for a point function.""" xp, yp, z = test_data r = 40 obs_tree = cKDTree(list(zip(xp, yp))) indices = obs_tree.query_ball_point([60, 60], r=r) dists = dist_2(60, 60, xp[indices], yp[indices]) values = z[indices] assert_almost_equal(barnes_point(dists, values, 5762.7), 4.0871824) def test_natural_neighbor_to_points(test_data, test_points): r"""Test natural neighbor interpolation to grid function.""" xp, yp, z = test_data obs_points = np.vstack([xp, yp]).transpose() img = natural_neighbor_to_points(obs_points, z, test_points) with get_test_data('nn_bbox0to100.npz') as fobj: truth = np.load(fobj)['img'].reshape(-1) assert_array_almost_equal(truth, img) interp_methods = ['cressman', 'barnes', 'shouldraise'] @pytest.mark.parametrize('method', interp_methods) def test_inverse_distance_to_points(method, test_data, test_points): r"""Test inverse distance interpolation to grid function.""" xp, yp, z = test_data obs_points = np.vstack([xp, yp]).transpose() extra_kw = {} if method == 'cressman': extra_kw['r'] = 20 extra_kw['min_neighbors'] = 1 test_file = 'cressman_r20_mn1.npz' elif method == 'barnes': extra_kw['r'] = 40 extra_kw['kappa'] = 100 test_file = 'barnes_r40_k100.npz' elif method == 'shouldraise': extra_kw['r'] = 40 with pytest.raises(ValueError): inverse_distance_to_points( obs_points, z, test_points, kind=method, **extra_kw) return img = inverse_distance_to_points(obs_points, z, test_points, kind=method, **extra_kw) with get_test_data(test_file) as fobj: truth = np.load(fobj)['img'].reshape(-1) assert_array_almost_equal(truth, img) @pytest.mark.parametrize('method', ['natural_neighbor', 'cressman', 'barnes', 'linear', 'nearest', 'rbf', 'shouldraise', 'cubic']) def test_interpolate_to_points(method, test_data): r"""Test main grid interpolation function.""" xp, yp, z = test_data obs_points = np.vstack([xp, yp]).transpose() * 10 with get_test_data('interpolation_test_points.npz') as fobj: test_points = np.load(fobj)['points'] extra_kw = {} if method == 'cressman': extra_kw['search_radius'] = 200 extra_kw['minimum_neighbors'] = 1 elif method == 'barnes': extra_kw['search_radius'] = 400 extra_kw['minimum_neighbors'] = 1 extra_kw['gamma'] = 1 elif method == 'shouldraise': with pytest.raises(ValueError): interpolate_to_points( obs_points, z, test_points, interp_type=method, **extra_kw) return img = interpolate_to_points(obs_points, z, test_points, interp_type=method, **extra_kw) with get_test_data(f'{method}_test.npz') as fobj: truth = np.load(fobj)['img'].reshape(-1) assert_array_almost_equal(truth, img)
{"/src/metpy/plots/declarative.py": ["/src/metpy/plots/__init__.py"], "/src/metpy/plots/__init__.py": ["/src/metpy/plots/declarative.py"]}
41,360,593
dopplershift/MetPy
refs/heads/stop-dependabot
/examples/formats/NEXRAD_Level_2_File.py
# Copyright (c) 2015,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ NEXRAD Level 2 File =================== Use MetPy to read information from a NEXRAD Level 2 (volume) file and plot """ import matplotlib.pyplot as plt import numpy as np from metpy.cbook import get_test_data from metpy.io import Level2File from metpy.plots import add_metpy_logo, add_timestamp ########################################### # Open the file name = get_test_data('KTLX20130520_201643_V06.gz', as_file_obj=False) f = Level2File(name) print(f.sweeps[0][0]) ########################################### # Pull data out of the file sweep = 0 # First item in ray is header, which has azimuth angle az = np.array([ray[0].az_angle for ray in f.sweeps[sweep]]) # 5th item is a dict mapping a var name (byte string) to a tuple # of (header, data array) ref_hdr = f.sweeps[sweep][0][4][b'REF'][0] ref_range = np.arange(ref_hdr.num_gates) * ref_hdr.gate_width + ref_hdr.first_gate ref = np.array([ray[4][b'REF'][1] for ray in f.sweeps[sweep]]) rho_hdr = f.sweeps[sweep][0][4][b'RHO'][0] rho_range = (np.arange(rho_hdr.num_gates + 1) - 0.5) * rho_hdr.gate_width + rho_hdr.first_gate rho = np.array([ray[4][b'RHO'][1] for ray in f.sweeps[sweep]]) ########################################### fig, axes = plt.subplots(1, 2, figsize=(15, 8)) add_metpy_logo(fig, 190, 85, size='large') for var_data, var_range, ax in zip((ref, rho), (ref_range, rho_range), axes): # Turn into an array, then mask data = np.ma.array(var_data) data[np.isnan(data)] = np.ma.masked # Convert az,range to x,y xlocs = var_range * np.sin(np.deg2rad(az[:, np.newaxis])) ylocs = var_range * np.cos(np.deg2rad(az[:, np.newaxis])) # Plot the data ax.pcolormesh(xlocs, ylocs, data, cmap='viridis') ax.set_aspect('equal', 'datalim') ax.set_xlim(-40, 20) ax.set_ylim(-30, 30) add_timestamp(ax, f.dt, y=0.02, high_contrast=True) plt.show()
{"/src/metpy/plots/declarative.py": ["/src/metpy/plots/__init__.py"], "/src/metpy/plots/__init__.py": ["/src/metpy/plots/declarative.py"]}
41,457,279
kensonman/webframe
refs/heads/master
/views.py
# -*- coding: utf-8 -*- # File: views.py # Author: Kenson Man # Date: 2017-05-11 11:53 # Desc: The webframe default views. from datetime import datetime from django.conf import settings from django.contrib import messages from django.contrib.auth import get_user_model, logout as auth_logout, login as auth_login, authenticate from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.models import Group from django.core.exceptions import PermissionDenied from django.db import transaction from django.http import HttpResponseForbidden, QueryDict, Http404, JsonResponse from django.shortcuts import render, redirect, get_object_or_404 as getObj from django.views import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.utils.translation import ugettext_lazy as _, ugettext as gettext, activate from django.urls import reverse from django_tables2 import RequestConfig from rest_framework import authentication, permissions from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.views import APIView from rest_framework.response import Response from .tasks import sendEmail from .decorators import is_enabled from .functions import getBool, isUUID, LogMessage as lm, getClientIP, getTime from .models import * from .serializers import APIResult, MenuItemSerializer, UserSerializer from .tables import * import hashlib, logging, json CONFIG_KEY='ConfigKey' logger=logging.getLogger('webframe.views') #Make sure the translation _('django.contrib.auth.backends.ModelBackend') _('django_auth_ldap.backend.LDAPBackend') _('nextPage') _('thisPage:%(page)s') _('prevPage') def getAbsoluteUrl(req): url=getattr(settings, 'ABSOLUTE_PATH', req.build_absolute_uri('/')[:-1]) try: if not url: host=req.build_absolute_uri() host=host[0:host.index('/', 9)] url=host elif url.index('%s')>=0: host=req.build_absolute_uri() host=host[0:host.index('/', 9)] url=url%host except ValueError: ''' url.index('%s') will raise the ValueError if string not found ''' pass return url class Login( View ): def __loadDefault__(self, req): params=dict() try: params['next']=req.POST.get('next', req.GET.get('next', reverse('index'))) if params['next']==reverse('webframe:login'): raise ValueError #Make sure do not loopback the login page. if params['next']==reverse('webframe:logout'): raise ValueError #Make sure do not loopback the login page. except: params['next']=req.POST.get('next', req.GET.get('next', reverse('index'))) params['socialLogin_facebook']=hasattr(settings, 'SOCIAL_AUTH_FACEBOOK_KEY') params['socialLogin_twitter']=hasattr(settings, 'SOCIAL_AUTH_TWITTER_KEY') params['socialLogin_github']=hasattr(settings, 'SOCIAL_AUTH_GITHUB_KEY') params['socialLogin_google']=hasattr(settings, 'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') req.session['next']=params['next'] logger.debug('Next URL: {0}'.format(params['next'])) logger.debug('Login templates: %s'%getattr(settings, 'TMPL_LOGIN', 'webframe/login.html')) params['backends']=[_(b) for b in settings.AUTHENTICATION_BACKENDS] return params def get(self, req): 'Return the login form' params=self.__loadDefault__(req) return render(req, getattr(settings, 'TMPL_LOGIN', 'webframe/login.html'), params) def login(self, req, username, password): params=self.__loadDefault__(req) User=get_user_model() if User.objects.exclude(username=getattr(settings, 'ANONYMOUS_USER_NAME', 'AnonymousUser')).count()<1: ## 2017-09-30 10:44, Kenson Man ## Let the first login user be the system administrator u=User() u.username=username u.first_name='System' u.last_name='Administrator' u.is_staff=True u.is_superuser=True u.set_password(password) u.save() messages.warning(req, 'Created the first user %s as system administroator'%username) try: u=authenticate(req, username=username, password=password) if not u: raise AttributeError if not hasattr(u, 'profile'): raise TypeError if u.profile: if not u.profile.alive: raise Error(lm('User[{0}] is expired! {1}~{2}', u.id, u.profile.effDate, u.profile.expDate)) except AttributeError: logger.debug(lm('User<{0}> cannot be found, or the password is incorrect.', username)) except (User.profile.RelatedObjectDoesNotExist, TypeError): logger.debug(lm('User<{0}> does not have the related profile, ignore the effective checking!', username)) except: logger.debug('Failed to login', exc_info=True) u=None return u def post(self, req): params=self.__loadDefault__(req) username=req.POST['username'] password=req.POST['password'] u=self.login(req, username, password) if u: auth_login(req, u) nextUrl=params.get('next', reverse('index')) return redirect(nextUrl) if getattr(settings, 'WF_DEFAULT_LOGIN_WARNINGS', True): messages.warning(req, gettext('Invalid username or password')) params['username']=username return render(req, getattr(settings, 'TMPL_LOGIN', 'webframe/login.html'), params) def delete(self, req): auth_logout(req) next=req.POST.get('next', req.GET.get('next', '/')) return redirect(next) def logout(req): ''' Logout the session. ''' return Login().delete(req) @login_required def users(req): ''' Show the users page. It is supported to the default User Model (django.contrib.auth.models.User) ''' # Check permission if req.user.is_superuser: pass elif req.user.has_perm('auth.browse_user'): pass else: return HttpResponseForbidden('<h1>403 - Forbidden</h1>') params=dict() params['target']=UserTable(get_user_model().objects.all()) params['btns']=getattr(settings, 'USERS_BTNS', None) rc=RequestConfig(req) rc.configure(params['target']) return render(req, getattr(settings, 'TMPL_USERS', 'webframe/users.html'), params) @login_required def ajaxUsers(req): q=req.GET.get('q', None) if q and len(q)>=3: rst=get_user_model().objects.filter(username__icontains=q).order_by('username') data=[{'key':u.id, 'value': u.username} for u in rst] return JsonResponse(data, safe=False) raise Http404() @transaction.atomic @login_required def user(req, user): user=get_user_model()() if user=='add' or user=='new' else getObj(get_user_model(), username=user) params=dict() args=QueryDict(req.body) if req.method=='GET': # Check permission if req.user.is_superuser: pass elif req.user.username==username: pass elif req.user.has_perm('auth.browse_user'): pass else: return HttpResponseForbidden('<h1>403-Forbidden</h1>') # Generate the result params['target']=user params['groups']=Group.objects.all() params['btns']=getattr(settings, 'USER_BTNS', None) params['AUTH_PASSWORD_REQUIRED']=getBool(getattr(settings, 'AUTH_PASSWORD_REQUIRED', True)) logger.debug('btns: %s'%params['btns']) return render(req, getattr(settings, 'TMPL_USER', 'webframe/user.html'), params) elif req.method=='DELETE': _('User.msg.confirmDelete') user.delete() return redirect(args.get('next', 'webframe:users')) elif req.method=='POST': # Check permission if req.user.is_superuser: pass elif req.user==user: pass elif user.id is None and req.user.has_perm('auth.add_user'): pass elif user.id is not None and req.user.has_perm('auth.change_user'): pass else: return HttpResponseForbidden('<h1>403 - Forbidden</h1>') user.first_name=req.POST.get('first_name', None) user.last_name=req.POST.get('last_name', None) user.email=req.POST.get('email', None) if req.user.is_superuser or req.user.has_perm('auth.add_user') or req.user.has_perm('auth.change_user'): user.username=req.POST.get('username', user.username) user.is_superuser = req.POST.get('is_superuser', '').upper() in ['TRUE', 'T', 'YES', 'Y', '1'] user.is_active = req.POST.get('is_active', '').upper() in ['TRUE', 'T', 'YES', 'Y', '1'] user.is_staff = req.POST.get('is_staff', '').upper() in ['TRUE', 'T', 'YES', 'Y', '1'] password=req.POST.get('password', None) if password: user.set_password(password) user.save() #2017-09-26 17:21, Kenson Man #Implement the groups logic user.groups.clear() for gid in req.POST.getlist('groups'): Group.objects.get(id=gid).user_set.add(user) if hasattr(settings, 'AUTH_DEFAULT_GROUPS'): for g in getattr(settings, 'AUTH_DEFAULT_GROUPS', list()): gp=Group.objects.filter(name=g) if gp.count()==1: gp[0].user_set.add(user) return redirect(args.get('next', 'webframe:users')) elif req.method=='PUT': #The PUT method is used for user to update their own personal information, webframe/preferences.html # Check permission if req.user.is_superuser: pass elif req.user==user: pass elif user.id is not None and req.user.has_perm('auth.change_user'): pass else: return HttpResponseForbidden('<h1>403 - Forbidden</h1>') user.first_name=req.POST.get('first_name', None) user.last_name=req.POST.get('last_name', None) user.email=req.POST.get('email', None) user.save() return redirect(args.get('next', 'users')) @login_required def prefs(req, user=None): ''' Show the preference page of the specified user. If requesting to show user that is not current session, the superuser permission are required. ''' if user=='_': return redirect('webframe:prefs', user=req.user) if user==None: user=req.user.username if user!=req.user.username and not req.user.is_superuser: if req.user.username!=user: return HttpResponseForbidden('<h1>403-Forbidden</h1>') user=getObj(get_user_model(), username=user) if req.method=='POST': newPwd=req.POST.get('newPwd', None) if newPwd and newPwd==req.POST.get('rePwd', None): user.set_password(newPwd) user.save() auth_logout(req) return redirect('webframe:prefs', user=user) params=dict() params['preference']=PreferenceTable(Preference.objects.filter(owner=req.user, parent__isnull=True)) params['config']=PreferenceTable(Preference.objects.filter(owner__isnull=True, parent__isnull=True)) rc=RequestConfig(req) rc.configure(params['preference']) rc.configure(params['config']) params['currentuser']=user if req.user.has_perm('webframe.add_config') or req.user.has_perm('webframe.change.config'): m=hashlib.md5() m.update(user.username.encode('utf-8')) m.update(CONFIG_KEY.encode('utf-8')) params['config_key']=m.hexdigest() return render(req, getattr(settings, 'TMPL_PREFERENCES', 'webframe/preferences.html'), params) @transaction.atomic @login_required def pref(req, user=None, prefId=None): ''' Showing the preference form for input. ''' if user=='_': return redirect('webframe:pref', user=req.user, prefId=prefId) # Declare the preference's owner if user: if user.upper()=='NONE': user=None else: if user!=req.user.username and not req.user.is_superuser: if req.user.username!=user: return HttpResponseForbidden('<h1>403-Forbidden</h1>') user=getObj(get_user_model(), username=user) params=dict() params['TYPES']=Preference.TYPES # Get the target preference if prefId=='add' or prefId=='new': pref=Preference() pref.owner=user if 'parent' in req.GET: pref.parent=getObj(Preference, id=req.GET['parent']) elif isUUID(prefId): pref=getObj(Preference, id=prefId) else: pref=getObj(Preference, name=prefId, owner=user) if 'admin' in req.GET and req.GET['admin'] in TRUE_VALUES: return redirect('admin:webframe_preference_change', object_id=pref.id) return redirect('webframe:pref', prefId=pref.id, user=user.username if user else 'none') if req.method=='GET': if 'admin' in req.GET and req.GET['admin'] in TRUE_VALUES: return redirect('admin:webframe_preference_change', object_id=pref.id) isConfig=getBool(req.GET.get('config', 'False')) if isConfig: if not (req.user.has_perm('webframe.add_config') or req.user.has_perm('webframe.change_config')): # Returns 403 if user cannot edit config return HttpResponseForbidden('<h1>403-Forbidden</h1>') pref.owner=None else: pref.owner=user # Preparing the form view params['target']=pref params['childs']=PreferenceTable(pref.childs) params['currentuser']=user params['TYPES']=Preference.TYPES return render(req, getattr(settings, 'TMPL_PREFERENCE', 'webframe/preference.html'), params) elif req.method=='POST' or req.method=='PUT': # Security Checking if req.POST.get('owner', None): if pref.isNew() and req.user.has_perm('webframe.add_preference'): pass #Allow to add preference elif (not pref.isNew()) and req.user.has_perm('webframe.change_preference'): pass #Allow to change preference else: logger.warning('Forbidden to add or change preference') return HttpResponseForbidden('<h1>403-Forbidden</h1>') pref.owner=getObj(get_user_model(), id=req.POST['owner']) else: if pref.isNew() and req.user.has_perm('webframe.add_config'): pass #Allow to add config elif (not pref.isNew()) and req.user.has_perm('webframe.change_config'): pass #Allow to change config else: logger.warning('Forbidden to add or change config') return HttpResponseForbidden('<h1>403-Forbidden</h1>') pref.owner=None # Saving pref.tipe=int(req.POST['tipe']) pref.name=req.POST['name'] pref.value=req.POST['value'] pref.sequence=int(req.POST['sequence']) pref.parent=None if req.POST.get('parent') is None else getObj(Preference, id=req.POST['parent']) pref.save() elif req.method=='DELETE': # Delete the method _('Preference.msg.confirmDelete') pref.delete() if req.POST.get('nextUrl', None): return redirect(req.POST.get('nextUrl', '/')) if pref.parent: return redirect('webframe:pref', user=pref.parent.owner, prefId=pref.parent.id) else: logger.warning('saved without parent') return redirect('webframe:prefs', user=pref.owner if pref.owner else req.user) @login_required @is_enabled('WF-AJAX_PREF') def ajaxPref(req, name): ''' Get the preference according to the name in JSON format ''' logger.debug('Getting pref<{0}>'.format(name)) rst=Preference.objects.pref(name, user=req.user, defval=None, returnValue=False) rst={'name': rst.name, 'value': rst.value, 'id': rst.id} return JsonResponse(rst, safe=False) @login_required @is_enabled('WF-AJAX_PREFS') def ajaxPrefs(req, name): ''' Get the preferences according to the name in JSON format ''' logger.debug('Getting prefs<{0}>'.format(name)) rst=Preference.objects.pref(name, user=req.user, defval=None, returnValue=False) rst=[{'id': i.id, 'name':i.name, 'value':i.value} for i in rst.childs] return JsonResponse(rst, safe=False) @login_required @permission_required('webframe.view_preference') @is_enabled('WF-PREFS_DOC') def prefsDoc(req): ''' Show the preference docs ''' logger.debug('Showing the prefs-doc...') params=dict() params['target']=Preference.objects.filter(parent__isnull=True).order_by('owner', 'sequence', 'name') params['TYPES']=Preference.TYPES params['now']=getTime('now') return render(req, 'webframe/prefsDoc.html', params) def help_menuitem(req): params=dict() return render(req, 'webframe/menuitem.html', params) @login_required @permission_required('webframe.add_menuitem') def help_create_menuitem(req): if req.method=='POST': root=MenuItem(name='/', label=_('appName'), props={'href': 'index'}) root.save() lm=MenuItem(name='/L', parent=root) lm.save() lroot=MenuItem(name='/L/Root', label='Goto Root', parent=lm, props={'href': 'index'}) lroot.save() rm=MenuItem(name='/R', parent=root, props={'class': 'navbar-right'}) rm.save() lang=MenuItem(name='/R/locale', parent=rm, icon='fa-globe') lang.save() hi=MenuItem(name='/R/Hi', parent=rm, label='Hi, {username}') hi.save() logout=MenuItem(name='/R/Hi/Logout', parent=hi, label='Logout', props={'href': reverse('webframe:logout')}) logout.save() activate('en') en=MenuItem(name='/R/locale/en', parent=lang, label=_('english'), props={'href':reverse('index')}) en.save() activate('zh-hant') zht=MenuItem(name='/R/locale/zht', parent=lang, label=_('zh-hant'), props={'href':reverse('index')}) zht.save() return redirect('admin:webframe_menuitem_changelist') return HttpResponseForbidden() class WhoAmIView(APIView): authentication_classes = [authentication.TokenAuthentication, authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] def get(self, req, format=None): return Response(UserSerializer(req.user).data) class HeaderView(APIView): authentication_classes = [authentication.TokenAuthentication, authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get(self, req, format=None): logger.warn(req.method) qs=MenuItem.objects.filter(parent__isnull=True) if req.user.is_authenticated: qs=qs.filter(models.Q(user__isnull=True)|models.Q(user=req.user)).order_by('-user') else: qs=qs.filter(user__isnull=True).order_by('-user') qs=MenuItem.filter(qs, req.user) if len(qs)>0: return Response(MenuItemSerializer(qs[0]).data) else: rst=MenuItem(name='Generated NavBar', label=_('appName')) lhs=MenuItem(parent=rst) hlp=MenuItem(parent=lhs, label='MenuItem Help', props={'href': reverse('webframe:help-menuitem')}) lhs.childs=[hlp, ] if req.user.is_staff or req.user.is_superuser: adm=MenuItem(parent=lhs, label='Admin Tools', icon='fa-cogs', props={'href': reverse('admin:index')}) lhs.childs.append(adm) rst.childs=[lhs,] return Response(MenuItemSerializer(rst).data) class ResetPasswordView(View): def get(self, req): params=dict() params['passwordReseted']=req.session.pop('reset-password', False) try: token=ResetPassword.objects.get(key=req.GET.get('token', None)) if str(token.user.id)!=req.GET.get('uid'): raise get_user_model().DoesNotExist if token.isDead(): raise IndexError params['token']=token except ResetPassword.DoesNotExist: if 'token' in req.GET: messages.info(req, _('ResetPassword.tokenNotFound')) except get_user_model().DoesNotExist: messages.info(req, _('ResetPassword.userNotFound')) except IndexError: messages.info(req, _('ResetPassword.notEffective')) except: logger.exception('Unexpected error') return render(req, getattr(settings, 'TMPL_RESET_PASSWORD', 'webframe/resetPassword.html'), params) def post(self, req): if 'token' in req.POST: return self._step2(req) else: return self._step1(req) def _step1(self, req): # Initializes params=dict() username=req.POST.get('username') User=get_user_model() user=None ipAddr=getClientIP(req) # Getting target user try: user=User.objects.get(username=username) except User.DoesNotExist: try: user=User.objects.get(email=username) except User.DoesNotExist: messages.warning(req, _('Cannot found the user: %(username)')%{'username':username}) return redirect('webframe:resetPassword') # Security check: repeating reset requested=ResetPassword.objects.filter(request_by=ipAddr, cd__gte=getTime(datetime.now(), offset='-1H')).count() logger.warning(lm('ResetPassword: There have {count} time(s) requested within 1 hour', count=requested)) if requested >= 5: messages.warning(req, _('Too many times to reset password')) return redirect('webframe:resetPassword') # Sending reset email with transaction.atomic(): ResetPassword.objects.filter(user=user, enabled=True).update(enabled=False) #Invalid previous token reset=ResetPassword(user=user, request_by=ipAddr) reset.save() tmpl=Preference.objects.pref('TMPL_RESET_PASSWORD', defval='<p>Dear {user.first_name} {user.last_name},</p><p>Please click the link to reset your password: <a href="{absolute_url}{url}?uid={user.id}&token={token}" target="_blank">{absolute_url}{url}?uid={user.id}&token={token}</a>.</p>') subj=Preference.objects.pref('TMPL_RESET_PASSWORD_SUBJECT', defval=_('resetPassword')) sender=Preference.objects.pref('EMAIL_FROM', defval='info@kenson.idv.hk') tmpl=tmpl.format(user=user, absolute_url=getAbsoluteUrl(req), token=reset.key, url=reverse('webframe:resetPassword')) sendEmail.delay(sender=sender, subject=subj, recipients=user.email, content=tmpl) email='{0}***{1}'.format(user.email[0:3], user.email[-7:]) messages.info(req, _('The reset password instruction has been email to %(email)s. Please follow the instruction to reset your password')%{'email': user.email} ) return redirect('webframe:resetPassword') def _step2(self, req): params=dict() try: token=getObj(ResetPassword, key=req.POST.get('token', None)) if str(token.user.id)!=req.GET.get('uid'): raise get_user_model().DoesNotExist if token.isDead(): raise IndexError passwd=req.POST.get('password', datetime.now()) again=req.POST.get('passwordAgain', 'Abc123$%^') if passwd!=again: raise ValueError with transaction.atomic(): token.user.set_password(passwd) token.user.save() token.complete_date=datetime.now() token.complete_by=getClientIP(req) token.enabled=False token.save() messages.info(req, _('The password has been updated successfully.')) tmpl=Preference.objects.pref('TMPL_RESETED_PASSWORD', defval='<p>Dear {user.first_name} {user.last_name},</p>i<p>Your password has been updated successfully.</p>') subj=Preference.objects.pref('TMPL_RESET_PASSWORD_SUBJECT', defval=_('resetPassword')) sender=Preference.objects.pref('EMAIL_FROM', defval='info@kenson.idv.hk') tmpl=tmpl.format(user=token.user, absolute_url=getAbsoluteUrl(req), token=token.key, url=reverse('webframe:resetPassword')) sendEmail.delay(sender=sender, subject=subj, recipients=token.user.email, content=tmpl) req.session['reset-password']=True except ResetPassword.DoesNotExist: messages.info(req, _('ResetPassword.tokenNotFound')) except get_user_model().DoesNotExist: messages.info(req, _('ResetPassword.userNotFound')) except IndexError: messages.info(req, _('ResetPassword.notEffective')) return redirect('webframe:resetPassword') @method_decorator(csrf_exempt, name='dispatch') class RegisterView(View): ''' Login the user and register the AuthToken ''' def post(self, req): logger.warning('Content-Type: %s'%req.headers.get('Content-Type')) if req.headers.get('Content-Type', 'application/x-www-form-urlencoded').startswith('application/json'): params=json.loads(req.body) else: params=req.POST username=params.get('username', None) password=params.get('password', None) deviceName=params.get('deviceName', None) try: if not username: raise ValueError('username is None') if not password: raise ValueError('password is None') if not deviceName: raise ValueError('deviceName is None') user=Login().login(req, username, password) if not user: raise PermissionDenied() logger.info('Got the loging: %s'%user.username) except PermissionDenied: raise except: logger.debug('', exc_info=True) user=None raise PermissionDenied() try: token=Token.objects.get(user=user) created=False tokenDetail=TokenDetail.objects.get(token=token) if not tokenDetail: raise TokenDetail.DoesNotExist except Token.DoesNotExist: token=Token.objects.create(user=user) created=True tokenDetail=TokenDetail(token=token, name=deviceName) tokenDetail.save() except TokenDetail.DoesNotExist: tokenDetail=TokenDetail(token=token, name=deviceName) tokenDetail.save() logger.debug({'token': token.key, 'status': 'created' if created else 'retrieved', 'deviceName': deviceName, 'username':user.username}) return JsonResponse({'token': 'ENC:{0}'.format(token.key[::-1]), 'status': 'created' if created else 'retrieved', 'username':user.username})
{"/webframe/migrations/0012_numbering.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0022_menuitem.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0026_webauthnpubkey.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0023_translation.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/lookups.py": ["/webframe/models.py"], "/webframe/migrations/0024_resetpassword.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/tasks.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/tables.py": ["/webframe/models.py"], "/webframe/providers.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/migrations/0003_ValueObjectAndAliveObject.py": ["/webframe/CurrentUserMiddleware.py"], "/webframe/views.py": ["/webframe/authentications.py", "/webframe/decorators.py", "/webframe/functions.py", "/webframe/models.py", "/webframe/serializers.py", "/webframe/tasks.py", "/webframe/tables.py"], "/webframe/migrations/0017_profile.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/serializers.py": ["/webframe/models.py"], "/webframe/decorators.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/migrations/0019_preference_filecontent.py": ["/webframe/models.py"], "/webframe/templatetags/calc.py": ["/webframe/models.py", "/webframe/CurrentUserMiddleware.py"], "/webframe/admin.py": ["/webframe/models.py", "/webframe/templatetags/trim.py"], "/webframe/authentications.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/templatetags/pref.py": ["/webframe/models.py", "/webframe/functions.py", "/webframe/CurrentUserMiddleware.py"], "/webframe/templatetags/encrypt.py": ["/webframe/functions.py"], "/webframe/tests/test_webframe.py": ["/webframe/functions.py"], "/webframe/models.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/functions.py"], "/webframe/management/commands/pref.py": ["/webframe/functions.py", "/webframe/models.py", "/webframe/providers.py"], "/webframe/migrations/0004_privilege.py": ["/webframe/CurrentUserMiddleware.py"], "/webframe/migrations/0025_tokendetail.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/authentications.py": ["/webframe/functions.py", "/webframe/models.py"]}
41,457,280
kensonman/webframe
refs/heads/master
/authentications.py
# -*- coding: utf-8 -*- # File: webframe/authentications.py # Author: Kenson Man <kenson@atomsystem.com.hk> # Date: 2021-03-07 12:36 # Desc: Provide the customized AuthenticationBackend, which will take care of the effective period when authenticate(req, username, password) from datetime import datetime from django.conf import settings from django.contrib import messages from django.contrib.auth import get_user_model as usermodel from django.contrib.auth.backends import ModelBackend from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.models import * from django.contrib.auth.signals import user_logged_in from django.db.models import Q from django.utils.timezone import utc from django.utils.translation import ugettext_lazy as _, ugettext as __ from django.utils import timezone as tz from webframe.functions import getBool from webframe.models import Preference, Profile import logging logger=logging.getLogger('webframe.authentications') class AuthenticationBackend(ModelBackend): ''' The authentication backend that including the effective period checking. Due to the default authentication backend (Django provided) does not include the effective period checking. This authentication backend will also **ignore** the case of username. USAGE ==== ```Python # proj/settings.py AUTHENTICATION_BACKENDS = [ 'webframe.authentications.AuthenticationBackend' ] AUTHENTICATION_BACKEND_CASE_INSENSITIVE = True #Set to Fase if you want case-sensitive ``` ''' def __init__(self): pass def authenticate(self, req, username=None, password=None): '''Handling the authentication''' messages.get_messages(req).used=True try: if getattr(settings, 'AUTHENTICATION_BACKEND_CASE_INSENSITIVE', True): logger.warning('B4 case-insensitive: {0}'.format(username)) username=usermodel()._default_manager.get(username__iexact=username).get_username() logger.warning('AF case-insensitive: {0}'.format(username)) user=super().authenticate(req, username=username, password=password) if user: if user.is_superuser and user.is_active: logger.debug('Ignore effective period checking for active superuser: {0}'.format(user.username)) else: now=datetime.utcnow().replace(tzinfo=utc) try: prof=Profile.objects.get(user=user) if not prof.alive: logger.debug('User<{0}> is not effective! {{effDate: {1}, expDate: {2}, now: {3}}}'.format(user.username, prof.effDate, prof.expDate, now)) messages.info(req, _('Your account is not effective')) user=None except Profile.DoesNotExist: allow=getattr(settings, 'WF_ALLOW_USER_NO_PROFILE', True) if getBool(allow): logger.warn('Ignored effective-period checking due to the specified user does\'not contains the profile: {0}'.format(username)) else: logger.warn('User<{0}> is not configured properly!'.format(user.username)) messages.info(req, _('Your account is not configured correctly')) user=None if user: logger.info('User<{0}> was signed-in!'.format(user.username)) #TODO: fire the signal here if necessary return user else: raise User.DoesNotExist except User.DoesNotExist: logger.debug('Invalid username/password, {0}/{1}'.format(username, password)) messages.info(req, _('invalid username or password')) return None except: logger.exception('Unexpected exception when authenticate the user: {0}'.format(username)) class ActiveUserRequiredMixin(UserPassesTestMixin): def test_func(self): if not self.request: return False if not self.request.user: return False if not self.request.user.is_authenticated: return False if not self.request.user.is_active: return False try: pf=self.request.user.profile return pf.alive except Profile.DoesNotExist: #Ignore the checking pass return True
{"/webframe/migrations/0012_numbering.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0022_menuitem.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0026_webauthnpubkey.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0023_translation.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/lookups.py": ["/webframe/models.py"], "/webframe/migrations/0024_resetpassword.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/tasks.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/tables.py": ["/webframe/models.py"], "/webframe/providers.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/migrations/0003_ValueObjectAndAliveObject.py": ["/webframe/CurrentUserMiddleware.py"], "/webframe/views.py": ["/webframe/authentications.py", "/webframe/decorators.py", "/webframe/functions.py", "/webframe/models.py", "/webframe/serializers.py", "/webframe/tasks.py", "/webframe/tables.py"], "/webframe/migrations/0017_profile.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/serializers.py": ["/webframe/models.py"], "/webframe/decorators.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/migrations/0019_preference_filecontent.py": ["/webframe/models.py"], "/webframe/templatetags/calc.py": ["/webframe/models.py", "/webframe/CurrentUserMiddleware.py"], "/webframe/admin.py": ["/webframe/models.py", "/webframe/templatetags/trim.py"], "/webframe/authentications.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/templatetags/pref.py": ["/webframe/models.py", "/webframe/functions.py", "/webframe/CurrentUserMiddleware.py"], "/webframe/templatetags/encrypt.py": ["/webframe/functions.py"], "/webframe/tests/test_webframe.py": ["/webframe/functions.py"], "/webframe/models.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/functions.py"], "/webframe/management/commands/pref.py": ["/webframe/functions.py", "/webframe/models.py", "/webframe/providers.py"], "/webframe/migrations/0004_privilege.py": ["/webframe/CurrentUserMiddleware.py"], "/webframe/migrations/0025_tokendetail.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/authentications.py": ["/webframe/functions.py", "/webframe/models.py"]}
41,457,281
kensonman/webframe
refs/heads/master
/urls.py
# -*- coding: utf-8 -*- # from django.conf import settings from django.urls import path, re_path, include from django.views.i18n import JavaScriptCatalog from . import views app_name='webframe' urlpatterns=[ re_path(r'^login/?$', views.Login.as_view(), name='login'), re_path(r'^logout/?$', views.logout, name='logout'), re_path(r'^resetPassword/?$', views.ResetPasswordView.as_view(), name='resetPassword'), re_path(r'^obtainToken/?$', views.RegisterView.as_view(), name='obtainToken'), re_path(r'^users/?$', views.users, name='users'), re_path(r'^users/(?P<user>[^/]*)/?$', views.user, name='user'), re_path(r'^users/(?P<user>[^/]*)/prefs/?$', views.prefs, name='prefs'), re_path(r'^users/(?P<user>[^/]*)/prefs/(?P<prefId>[^/]*)/?$', views.pref, name='pref'), re_path(r'^ajax/users/?$', views.ajaxUsers, name='ajax-users'), re_path(r'^ajax/pref/(?P<name>[^/]+)/?$', views.ajaxPref, name='ajax-pref'), #It can be disabled in WF-AJAX_PREF re_path(r'^ajax/prefs/(?P<name>[^/]+)/?$', views.ajaxPrefs, name='ajax-prefs'), #It can be disabled in WF-AJAX_PREFS re_path(r'^prefsDoc/?$', views.prefsDoc, name='prefs-doc'), #It can be disabled in WF-PREFS_DOC, required vgallery.view_preference re_path(r'^href/menuitem/?$', views.help_menuitem, name='help-menuitem'), re_path(r'^href/menuitem/create/?$', views.help_create_menuitem, name='help-create-menuitem'), re_path(r'headers/?$', views.HeaderView.as_view(), name='headers'), re_path(r'whoami/?$', views.WhoAmIView.as_view(), name='whoami'), re_path('jsi18n/', JavaScriptCatalog.as_view(domain='django', packages=['webframe',]), name='js'), ]
{"/webframe/migrations/0012_numbering.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0022_menuitem.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0026_webauthnpubkey.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/migrations/0023_translation.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/lookups.py": ["/webframe/models.py"], "/webframe/migrations/0024_resetpassword.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/tasks.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/tables.py": ["/webframe/models.py"], "/webframe/providers.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/migrations/0003_ValueObjectAndAliveObject.py": ["/webframe/CurrentUserMiddleware.py"], "/webframe/views.py": ["/webframe/authentications.py", "/webframe/decorators.py", "/webframe/functions.py", "/webframe/models.py", "/webframe/serializers.py", "/webframe/tasks.py", "/webframe/tables.py"], "/webframe/migrations/0017_profile.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/webframe/serializers.py": ["/webframe/models.py"], "/webframe/decorators.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/migrations/0019_preference_filecontent.py": ["/webframe/models.py"], "/webframe/templatetags/calc.py": ["/webframe/models.py", "/webframe/CurrentUserMiddleware.py"], "/webframe/admin.py": ["/webframe/models.py", "/webframe/templatetags/trim.py"], "/webframe/authentications.py": ["/webframe/functions.py", "/webframe/models.py"], "/webframe/templatetags/pref.py": ["/webframe/models.py", "/webframe/functions.py", "/webframe/CurrentUserMiddleware.py"], "/webframe/templatetags/encrypt.py": ["/webframe/functions.py"], "/webframe/tests/test_webframe.py": ["/webframe/functions.py"], "/webframe/models.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/functions.py"], "/webframe/management/commands/pref.py": ["/webframe/functions.py", "/webframe/models.py", "/webframe/providers.py"], "/webframe/migrations/0004_privilege.py": ["/webframe/CurrentUserMiddleware.py"], "/webframe/migrations/0025_tokendetail.py": ["/webframe/CurrentUserMiddleware.py", "/webframe/models.py"], "/authentications.py": ["/webframe/functions.py", "/webframe/models.py"]}
41,469,441
A2grey/Projet_POO
refs/heads/master
/fonctions.py
# -*- coding: utf8 -*- import os, csv, re import os.path import pathlib from os import path import json from fnmatch import fnmatch from os import getcwd, chdir, mkdir #Fonction de recherche des document abs et retournant les chemin. def recherche_chemin(chemin_initial): liste_chemin=[] chemin = "./hep-th-abs" for path, dirs, files in os.walk(chemin_initial): for dossier in dirs: nv_chemin = os.path.normpath(os.path.join(chemin, dossier)) # on concatene le chemin avec le dossier et on normalise le nouveau chemin obtenu # print(nv_chemin) for path, dirs, files in os.walk(nv_chemin): for fichiers in files: # compteur+=1 data = [] nv_chemin2 = os.path.normpath(os.path.join(nv_chemin,fichiers)) # on concatene le nouveau chemin avec le fichier et on normalise le nouveau chemin obtenu if os.path.isfile(nv_chemin2): # verification de l'existence du fichier liste_chemin.append(nv_chemin2) return liste_chemin #Cette fonction retourne la ligne où se trouve le mot "Authors" ou "Author" def recherche_ligne_auteurs(chemin): if os.path.isfile(chemin): with open(chemin,'r', encoding="cp1252") as f: #print(f.encoding) for ligne_auteurs in f: if "Authors"in ligne_auteurs: return ligne_auteurs elif "Author"in ligne_auteurs: return ligne_auteurs #Cette fonction transforme une phrase en liste de mot, gèrer les abreviations, et supprime les les "And", "and", "et" qu'on pourrait rencontrer dans la phrase def liste_auteurs(ligne_des_auteurs): #print(phrase) #ce code enleve tous les mots à l'interieur d'une parenthèse ainsi que les parenthèses elles meme. p = re.compile(r'\([^)]*\)') nv_phrase = re.sub(p, '', ligne_des_auteurs) p = re.compile(r'\([^)]*') nv_phrase = re.sub(p, '', nv_phrase) if ")" in nv_phrase: #On remplace d'eventuelles parentheses ouverte par rien "" nv_phrase = nv_phrase.replace(")", "") if ", and " in nv_phrase: #On remplace les "and et "And" par des virgules nv_phrase = nv_phrase.replace(", and ", ", ") if " and " or " And " in nv_phrase: #On remplace les "and et "And" par des virgules nv_phrase = nv_phrase.replace(" and ", ", ") nv_phrase = nv_phrase.replace(" And ", ", ") #p = re.compile(r' ,') #nv_phrase = re.sub(p, '', nv_phrase) if ":" in nv_phrase: # On suppprime les deux points ":" nv_phrase = nv_phrase.replace(":", "") if "Authors" or "authors" or "Author" or "author" in nv_phrase: ##On supprime les "Authors" or "Authors:" or"Author:" or "Author" en les remplacant par rien "" nv_phrase = nv_phrase.replace("Authors", "") nv_phrase = nv_phrase.replace("authors", "") nv_phrase = nv_phrase.replace("Author", "") nv_phrase = nv_phrase.replace("author", "") liste_des_auteurs_non = nv_phrase.split(',') #On decoupe la ligne comportant le nom des auteurs en mot liste_des_auteurs=[] for nom in liste_des_auteurs_non: #On enleve les espaces en debut et en fin de chaque nom nv_nom=nom.strip() liste_des_auteurs.append(nv_nom) return liste_des_auteurs #b=liste_auteurs(phraseA) #phraseA = ["R. Roger", "D., -J., y., Cédric", "T.Z., Camus, Mikou"] #Test #print(b) def dictionnaire_par_article(liste_des_auteurs, chemin, dictionnaire): nom_fichier = os.path.basename(chemin) # on prend le dernier element du chemin, il s'agit du fichier avec son extension ".abs" id_fichier = nom_fichier[0:len(nom_fichier) - 4] # on retire l'extension ".abs" dictionnaire[id_fichier] = liste_des_auteurs return dictionnaire def fichier_citations(): root = "./Projet programmation" pattern = "*hep-th-citations" i = 0 for path, subdirs, files in os.walk(root): for name in files: if fnmatch(name, pattern): liste = [] chemin_fichier_citations = os.path.join(path, name) with open('CitationsArticles.txt', 'a') as NvCitations: with open(chemin_fichier_citations, "r", encoding="utf-8") as citation: for lignes in citation: lign=[lignes[0:7],lignes[8:15]] NvCitations.write(lign) liste.append(lignes.split()) return liste def Dictionnaire_citations(): root = "../" pattern = "*hep-th-citations" Dictionnaire_citation={} i = 0 for path, subdirs, files in os.walk(root): for name in files: if fnmatch(name, pattern): chemin_fichier_citations = os.path.join(path, name) with open(chemin_fichier_citations, "r", encoding="utf-8") as citation: cle=1 for lignes in citation: #liste=[] #liste.append(lignes[9:15]) Dictionnaire_citation[cle]=[lignes[0:7],lignes[8:15]] cle +=1 return Dictionnaire_citation
{"/communaute.py": ["/aide.py", "/auteur.py", "/initialisation.py"], "/auteur.py": ["/fonctions.py"], "/initialisation.py": ["/fonctions.py"]}
41,469,442
A2grey/Projet_POO
refs/heads/master
/auteur.py
from fonctions import fichier_citations import networkx as nx from pprint import pprint import time from pprint import pprint import time tmps1 = time.time() #chargement des donnée import json from pprint import pprint chemin1="./ArcticleAuteur.json" chemin2="./CitationsArticles.json" #telechargement de des données def charge_donnees(chemin): with open(chemin,'r') as donnees: return json.load(donnees) #creation du graphe graphe = nx.DiGraph() #graphe orietée #Creation des sommets du graphe dictionnaire_article=charge_donnees(chemin1) liste_articles=list(dictionnaire_article.keys()) graphe.add_nodes_from(liste_articles) #sommet du graphe #Creation des arrets du graphe dictionnaire_citation=charge_donnees(chemin2) liste_arrets=dictionnaire_citation.values() #pprint(liste_arrets) graphe.add_edges_from(list(liste_arrets)) #arrets du graphe #sort la liste de tous les auteurs cités par un auteur donné def auteurs_cites(auteur): #trouver les acticle ecrits par cet auteur articles_ecrits = [] for id_article in list(dictionnaire_article.keys()): if auteur in dictionnaire_article[id_article]: articles_ecrits.append(id_article) return articles_ecrits #trouver les articles cités par les articles trouvés precedement def articles_cites(articles_ecrits): liste_article_cites=[] for article in articles_ecrits: liste_article_cites=list(graphe.successors(article)) return liste_article_cites #donner les auteurs des articles cité def auteur_arcticles_cites(liste_article_cites): liste_auteurs=[] for article in liste_article_cites: for nom in dictionnaire_article[article]: liste_auteurs.append(nom) liste_auteurs=list(set(liste_auteurs)) #liste_auteurs_tries=liste_auteurs.sort() return liste_auteurs def resultat(auteur): articles_ecrits=auteurs_cites( auteur) liste_article_cites=articles_cites(articles_ecrits) resultats=auteur_arcticles_cites(liste_article_cites) return resultats #pprint(resultats) def influence(auteur, N): i = 0 predecesseurs = auteurs_cites(auteur) liste = list(range(N + 1)) liste[i] = auteurs_cites(auteur) dico_aut_int_global = {} while i < N: sommets = predecesseurs nv_elemnt = [] dico_aut_int = {} #print(f"niveau {i + 1} ####################################") for sommet in liste[i]: for article in list(graphe.predecessors(sommet)): predecesseurs.append(article) nv_elemnt.append(article) liste[i + 1] = nv_elemnt # print(f"niveaunv:{i + 1}", nv_elemnt) auteurs_a = [] auteurs_b = [] for art in nv_elemnt: if dictionnaire_article[art] != []: for aut in dictionnaire_article[art]: auteurs_b.append(aut) #print(auteurs_b) for aut1 in auteurs_b: nb_apparition = 0 for aut2 in auteurs_b[auteurs_b.index(aut1):]: if aut1 == aut2: nb_apparition += 1 # print(aut1, nb_apparition) if not aut1 in dico_aut_int.keys(): dico_aut_int[aut1] = round((nb_apparition) / (i + 1), 3) #print(dico_aut_int) for cle in dico_aut_int.keys(): if not cle in dico_aut_int_global.keys(): dico_aut_int_global[cle] = dico_aut_int[cle] else: dico_aut_int_global[cle] += dico_aut_int[cle] i += 1 print("RESULTAT") print(f"Le nombre d'auteur influencés par {auteur} avec une profondeur au plus {N} est : {len(dico_aut_int_global.keys())}") intensite=list(dico_aut_int_global.values()) somme=0 liste_valeur=[] for valeur in intensite: somme+=valeur liste_valeur.append(valeur) # print(f"La plus grande intensité d'influence est : {max(liste_valeur)}") print(f"La plus etite intensité d'influence est : {min(liste_valeur)}") if len(dico_aut_int_global.keys())==0: print(f"L'intensité moyenne est : 0") else: print(f"L'intensité moyenne est : {round(somme / len(dico_aut_int_global.keys()))}") from operator import itemgetter, attrgetter #pprint(dico_aut_int_global) #pprint(sorted(dico_aut_int_global, key=itemgetter(1), reverse=True)) pprint(sorted(dico_aut_int_global.items(), key=lambda t: t[1], reverse=True)) tmps2 = time.time() - tmps1 #On capte le temps d'execution du programme print("Recherche effectuée avec succès") print("Temps d'execution = %f" % tmps2)
{"/communaute.py": ["/aide.py", "/auteur.py", "/initialisation.py"], "/auteur.py": ["/fonctions.py"], "/initialisation.py": ["/fonctions.py"]}
41,469,443
A2grey/Projet_POO
refs/heads/master
/initialisation.py
# -*- coding: utf8 -*- #Importation des modules import os, sys, csv import os.path from os import getcwd, chdir, mkdir from fonctions import * #recherche_ligne_auteurs, liste_auteurs, remplissage_baseArcticle import time class Initialisation: #statut= #if statut=="activé" tmps1 = time.time() # On capte le temps au debut #1-creation du fichier texte des citations bdd = "./CitationsArticles.json" with open(bdd, 'w', encoding='utf-8') as data: data.write(json.dumps(Dictionnaire_citations())) #fichier_citations() #2-creation du fichier texte des articles sous format json #def fichier_arcticle(self): #Parametres chemin_initial = "./hep-th-abs" bdd = "./ArcticleAuteur.json" dictionnaire = {} liste_chemin=recherche_chemin(chemin_initial) #liste des chemins des fichiers abs dans le dossier initial for chemin in liste_chemin: ligne_des_auteurs = recherche_ligne_auteurs(chemin) # constitution de la liste des auteurs pour chaque fichier liste_des_auteurs=liste_auteurs(ligne_des_auteurs) dictionnaire=dictionnaire_par_article(liste_des_auteurs, chemin, dictionnaire) #ajout de l'info de l'artcile( id et auteurs) sous forme de dico au notre dictionnaire des articles #print(dictionnaire.keys()) with open(bdd, 'w', encoding='utf-8') as data: data.write(json.dumps(dictionnaire)) #enregistrement du dictionnaire sous format json tmps2 = time.time() - tmps1 # On capte le temps d'execution du programme print("Temps d'execution = %f" % tmps2) print("Initialisation reussie") def Dictionnaire_article(): Dictionnaire_article=Initialisation.dictionnaire return Dictionnaire_article
{"/communaute.py": ["/aide.py", "/auteur.py", "/initialisation.py"], "/auteur.py": ["/fonctions.py"], "/initialisation.py": ["/fonctions.py"]}
41,469,444
A2grey/Projet_POO
refs/heads/master
/communaute.py
# -*- coding: utf8 -*- from sys import argv #class Main(): #def condition(self): statut = "desactivé" nb_arguments = len(argv) if argv[0] == "communaute.py": if nb_arguments == 1: print("") print( "Veillez indiquer une operation que vous voulez que votre application 'communaute' fasse pour vous avec les éventuels arguments") print("") print("Vous pouvez par exemple faire:") print("./communaute aide Pour savoir comment fonctionne l'application") print("./communaute init Pour initialiser l'application") print("./communaute cite Einstein Pour avoir la liste de tous les euteurs cité par Einstein") print("./communaute influence Einstein Pour avoir la liste de tous les euteurs qui influencent Einstein") print("./communaute communautes Einstein 5 Pour avoir la liste du communaute de profondeur 5 de Einstein") if nb_arguments == 2: if argv[1] == 'init': # statut = 'initialisation activée' if __name__ == "__main__": from initialisation import Initialisation Initialisation() else: if argv[1] == 'aide': #statut = 'aide activée' if __name__ == "__main__": from aide import Aide Aide() else: if argv[1] == 'cite': print("") print("L'opétation 'cite' prend un argument(le nom de l'auteur qui cite") print("") print("Vous pouvez par exemple faire:") print( "./communaute cite Einstein Pour avoir la liste de tous les euteurs cité par Einstein") # statut = "desactivé" else: if argv[1] == 'influence': print("") print("L'opétation 'influence' prend un argument(le nom de l'auteur qui influence") print("Vous pouvez par exemple faire:") print( "./communaute influence Einstein Pour avoir la liste de tous les euteurs qui influencent Einstein") #statut = "desactivé" else: if argv[1] == 'communautes': print("") print( "L'opétation 'communautes' prend deux arguments(le nom de l'auteur et la profondeur de la communauté") print("") print("Vous pouvez par exemple faire:") print("./communaute communautes Einstein 5 Pour initialiser l'application") #statut = "desactivé" else: print("") print( "Veillez choisir l'une des opétations suivantes: aide, init, influence, cite, influence, communautes") print("Besoin d'aide?") print("Tapez:") print("./communaute aide Pour savoir comment fonctionne l'application") #statut = "desactivé" if nb_arguments == 3: if argv[1] == 'init': print("") print("L'opération d'initialisation ne prend aucun argument") print("") print("Vous devez juste faire:") print("./communaute init Pour initialiser l'application") print("") print("Besoin d'aide?") print("Tapez:") print("./communaute aide Pour savoir comment fonctionne l'application") #statut = "desactivé" elif argv[1] == 'aide': statut = 'aide desactivée' print("") print("L'opération d'aide ne prend aucun argument") print("") print("Vous devez juste faire:") print("./communaute aide Pour savoir comment fonctionne l'application") print("") elif argv[1] == 'cite': if __name__ == "__main__": from auteur import resultat resultat(argv[2]) elif argv[1] == 'communautes': print("") print("L'opération 'communautes' prend deux arguments") print("") print("Vous pouvez par exemple faire:") print("./communaute communautes Einstein 5 Pour avoir la liste du communaute de profondeur 5 de Einstein") print("") else: print("L'application 'communaute' ne fait pas l'opertaion que vous avez demandé") print("") print("Vous pouvez faire l'une des opération ci-dessous:") print("./communaute aide Pour savoir comment fonctionne l'application") print("./communaute init Pour initialiser l'application") print("./communaute cite Einstein Pour avoir la liste de tous les euteurs cité par Einstein") print("./communaute influence Einstein Pour avoir la liste de tous les euteurs qui influencent Einstein") print("./communaute communautes Einstein 5 Pour avoir la liste du communaute de profondeur 5 de Einstein") if nb_arguments == 4: if argv[1] == 'influence': if __name__ == "__main__": from auteur import influence influence(argv[2],int(argv[3])) """ if Main.condition=="initialisation activée": from initialisation import Initialisation Initialisation() else: from aide import Aide Aide() if __name__=='__main__': Main() """
{"/communaute.py": ["/aide.py", "/auteur.py", "/initialisation.py"], "/auteur.py": ["/fonctions.py"], "/initialisation.py": ["/fonctions.py"]}
41,534,481
sjacob-cn/dart-api
refs/heads/master
/dart/schema.py
import graphene # from app.schema.data_gaps import Data_gapsQuery,DataMutation # from app.schema.Pipeline_traceability import Pipeline_traceabilityQuery,Pipeline_traceabilityMutation # from app.schema.system_traceability import system_traceabilityQuery,systemtraceabilityMutation from app.schema.traceability import Trace_idsQuery # from app.schema.Traceability_results import Traceability_resultsQuery,Traceability_resultsMutation # from app.schema.sample import SQuery # from graphql_auth.schema import UserQuery, MeQuery class Query(Trace_idsQuery, graphene.ObjectType): pass class Mutation(graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=None)
{"/app/admin.py": ["/app/models.py"], "/dart/schema.py": ["/app/schema/traceability.py"], "/app/schema/traceability.py": ["/app/models.py", "/app/schema/utils.py", "/app/schema/descriptions.py", "/app/schema/validation.py"]}
41,534,482
sjacob-cn/dart-api
refs/heads/master
/app/schema/validation.py
from graphql import GraphQLError class Validation: def check_is_date_empty(value, field): if value is None or value == '': raise GraphQLError("{0} field can't be empty".format(field.title())) def check_is_empty(value, field): if value is None or value == '' or value.isspace(): raise GraphQLError("{0} field can't be empty".format(field.title()))
{"/app/admin.py": ["/app/models.py"], "/dart/schema.py": ["/app/schema/traceability.py"], "/app/schema/traceability.py": ["/app/models.py", "/app/schema/utils.py", "/app/schema/descriptions.py", "/app/schema/validation.py"]}
41,534,483
sjacob-cn/dart-api
refs/heads/master
/app/schema/utils.py
from graphql import GraphQLError import datetime def get_wrapper_details(data_wrapper, qs,page, size): if page <= 1: skip = 0 current_page = 1 else: skip = (page - 1) * size current_page = page total_elements = qs.count() total_pages = int(total_elements / size) total_pages += 1 if (total_elements % size) > 0 else 0 if total_pages > current_page: has_next_page = True else: has_next_page = False if skip: qs = qs[skip:] if size: qs = qs[:size] number_of_elements = qs.count() keyword_args = { 'stages': qs, # 'touch_point':qs, 'total_elements': total_elements, 'size': size, 'total_pages': total_pages, 'current_page': current_page, 'has_next_page': has_next_page, 'number_of_elements': number_of_elements, } return data_wrapper(**keyword_args) def wrapper_without_pagination(data_wrapper, qs): keyword_args = { 'stages': qs } return data_wrapper(**keyword_args) def get_logdate_info(start_logdate, end_logdate): if start_logdate: start_logdate = datetime.datetime.strptime(start_logdate, '%Y-%m-%d').date() if end_logdate: end_logdate = datetime.datetime.strptime(end_logdate, '%Y-%m-%d').date() key = None value = None if start_logdate and not end_logdate: key = 'logdate__gte' value = start_logdate elif end_logdate and not start_logdate: key = 'logdate__lte' value = end_logdate else: if end_logdate >= start_logdate: key = 'logdate__range' value = (start_logdate,end_logdate) else: raise GraphQLError("StartDate should be <= EndDate") return (key, value)
{"/app/admin.py": ["/app/models.py"], "/dart/schema.py": ["/app/schema/traceability.py"], "/app/schema/traceability.py": ["/app/models.py", "/app/schema/utils.py", "/app/schema/descriptions.py", "/app/schema/validation.py"]}
41,534,484
sjacob-cn/dart-api
refs/heads/master
/app/schema/traceability.py
import graphene from graphene_django import DjangoObjectType from graphene import ObjectType from app.models import * from graphql import GraphQLError from django.db import IntegrityError from app.schema.validation import Validation from .utils import * from .descriptions import * import json class Touchpoints(ObjectType): step_detail = graphene.String() # metric_count = graphene.Int() # results =graphene.String() variance = graphene.String() class Stages(DjangoObjectType): system =graphene.String() touch_points =graphene.List(Touchpoints,trace_id = graphene.String(), metric =graphene.String(), dt = graphene.Date(), brand = graphene.String()) class Meta: model = System_traceability def resolve_touch_points(self, info, size=100, page=1, **kwargs): print(kwargs) trace_id = kwargs['trace_id'] qs = Trace_ids.objects.all() qs=qs.filter(trace_id=trace_id) obj = None for each in qs: if each.type == 'system': obj = System_traceability.objects.all() obj = obj.filter(**kwargs).distinct().order_by('-step') print(obj,'ghefgeku') break elif each.type == 'pipeline': obj = Pipeline_traceability.objects.all() obj = obj.filter(**kwargs).distinct().order_by('-step') break res =Traceability_results.objects.all() res = res.filter(trace_id=trace_id).filter(dt=kwargs['dt']) data = '' for each in res: data = each.results json_data =json.loads(data) # print(json_data) v=json_data['breakdown'][kwargs['metric']][kwargs['brand']]['Variance%age'] # print(json_data['breakdown'][kwargs['metric']][kwargs['brand']]['Totals'][sys_name]) # return get_wrapper_detail(Touchpoints, obj, page, size) return obj class Wrapper(ObjectType): stages = graphene.List(Stages) total_elements = graphene.Int() number_of_elements = graphene.Int() size = graphene.Int() total_pages = graphene.Int() current_page = graphene.Int() has_next_page = graphene.Boolean() class Meta: description = desc_wrapper class Trace_idsQuery(ObjectType): trace_ids = graphene.Field( Wrapper , trace_id = graphene.String(), metric =graphene.String(), dt = graphene.Date(), brand = graphene.String() ) def resolve_trace_ids(self, info, size=100, page=1, **kwargs): print(kwargs) trace_id = kwargs['trace_id'] qs = Trace_ids.objects.all() qs=qs.filter(trace_id=trace_id) obj = None for each in qs: if each.type == 'system': obj = System_traceability.objects.all() obj = obj.filter(**kwargs).distinct().order_by('-step') print(obj,'ghefgeku') break elif each.type == 'pipeline': obj = Pipeline_traceability.objects.all() obj = obj.filter(**kwargs).distinct().order_by('-step') break # res =Traceability_results.objects.all() # res = res.filter(trace_id=trace_id).filter(dt=kwargs['dt']) # data = '' # for each in res: # data = each.results # json_data =json.loads(data) # print(json_data) # print(json_data['breakdown'][kwargs['metric']][kwargs['brand']]['Variance%age']) # print(json_data['breakdown'][kwargs['metric']][kwargs['brand']]['Totals'][sys_name]) return get_wrapper_details(Wrapper, obj, page, size)
{"/app/admin.py": ["/app/models.py"], "/dart/schema.py": ["/app/schema/traceability.py"], "/app/schema/traceability.py": ["/app/models.py", "/app/schema/utils.py", "/app/schema/descriptions.py", "/app/schema/validation.py"]}
41,550,791
pyparsing/pyparsing
refs/heads/master
/examples/stackish.py
# stackish.py # # Stackish is a data representation syntax, similar to JSON or YAML. For more info on # stackish, see http://www.savingtheinternetwithhate.com/stackish.html # # Copyright 2008, Paul McGuire # """ NUMBER A simple integer type that's just any series of digits. FLOAT A simple floating point type. STRING A string is double quotes with anything inside that's not a " or newline character. You can include \n and \" to include these characters. MARK Marks a point in the stack that demarcates the boundary for a nested group. WORD Marks the root node of a group, with the other end being the nearest MARK. GROUP Acts as the root node of an anonymous group. ATTRIBUTE Assigns an attribute name to the previously processed node. This means that just about anything can be an attribute, unlike in XML. BLOB A BLOB is unique to Stackish and allows you to record any content (even binary content) inside the structure. This is done by pre- sizing the data with the NUMBER similar to Dan Bernstein's netstrings setup. SPACE White space is basically ignored. This is interesting because since Stackish is serialized consistently this means you can use \n as the separation character and perform reasonable diffs on two structures. """ from pyparsing import ( Suppress, Word, nums, alphas, alphanums, Combine, oneOf, Optional, QuotedString, Forward, Group, ZeroOrMore, srange, pyparsing_common as ppc, ) MARK, UNMARK, AT, COLON, QUOTE = map(Suppress, "[]@:'") NUMBER = ppc.integer() FLOAT = ppc.real() STRING = QuotedString('"', multiline=True) | QuotedString("'", multiline=True) WORD = Word(alphas, alphanums + "_:") ATTRIBUTE = Combine(AT + WORD) strBody = Forward() def setBodyLength(tokens): strBody << Word(srange(r"[\0x00-\0xffff]"), exact=int(tokens[0])) return "" BLOB = Combine( QUOTE + Word(nums).setParseAction(setBodyLength) + COLON + strBody + QUOTE ) item = Forward() def assignUsing(s): def assignPA(tokens): if s in tokens: tokens[tokens[s]] = tokens[0] del tokens[s] return assignPA GROUP = ( MARK + Group( ZeroOrMore( (item + Optional(ATTRIBUTE)("attr")).setParseAction(assignUsing("attr")) ) ) + (WORD("name") | UNMARK) ).setParseAction(assignUsing("name")) item <<= FLOAT | NUMBER | STRING | BLOB | GROUP item.runTests( """\ [ '10:1234567890' @name 25 @age +0.45 @percentage person:zed [ [ "hello" 1 child root [ "child" [ 200 '4:like' "I" "hello" things root [ [ "data" [ 2 1 ] @numbers child root [ [ 1 2 3 ] @test 4 5 6 root """ )
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,792
pyparsing/pyparsing
refs/heads/master
/examples/builtin_parse_action_demo.py
# # builtin_parse_action_demo.py # Copyright, 2012 - Paul McGuire # # Simple example of using builtin functions as parse actions. # from pyparsing import * integer = Word(nums).setParseAction(lambda t: int(t[0])) # make an expression that will match a list of ints (which # will be converted to actual ints by the parse action attached # to integer) nums = OneOrMore(integer) test = "2 54 34 2 211 66 43 2 0" print(test) # try each of these builtins as parse actions for fn in (sum, max, min, len, sorted, reversed, list, tuple, set, any, all): fn_name = fn.__name__ if fn is reversed: # reversed returns an iterator, we really want to show the list of items fn = lambda x: list(reversed(x)) # show how each builtin works as a free-standing parse action print(fn_name, nums.setParseAction(fn).parseString(test))
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,793
pyparsing/pyparsing
refs/heads/master
/examples/chemicalFormulas.py
# # chemicalFormulas.py # # Copyright (c) 2003,2019 Paul McGuire # import pyparsing as pp atomicWeight = { "O": 15.9994, "H": 1.00794, "Na": 22.9897, "Cl": 35.4527, "C": 12.0107, } digits = "0123456789" # Version 1 element = pp.Word(pp.alphas.upper(), pp.alphas.lower(), max=2).set_name("element") # for stricter matching, use this Regex instead # element = Regex("A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|" # "E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|" # "M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|" # "S[bcegimnr]?|T[abcehilm]|U(u[bhopqst])?|V|W|Xe|Yb?|Z[nr]") elementRef = pp.Group(element + pp.Optional(pp.Word(digits), default="1")) formula = elementRef[...] def sum_atomic_weights(element_list): return sum(atomicWeight[elem] * int(qty) for elem, qty in element_list) formula.runTests( """\ H2O C6H5OH NaCl """, fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format( sum_atomic_weights(tokens) ), ) print() # Version 2 - access parsed items by results name elementRef = pp.Group( element("symbol") + pp.Optional(pp.Word(digits), default="1")("qty") ) formula = elementRef[...] def sum_atomic_weights_by_results_name(element_list): return sum(atomicWeight[elem.symbol] * int(elem.qty) for elem in element_list) formula.runTests( """\ H2O C6H5OH NaCl """, fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format( sum_atomic_weights_by_results_name(tokens) ), ) print() # Version 3 - convert integers during parsing process integer = pp.Word(digits).setParseAction(lambda t: int(t[0])).setName("integer") elementRef = pp.Group(element("symbol") + pp.Optional(integer, default=1)("qty")) formula = elementRef[...].setName("chemical_formula") def sum_atomic_weights_by_results_name_with_converted_ints(element_list): return sum(atomicWeight[elem.symbol] * int(elem.qty) for elem in element_list) formula.runTests( """\ H2O C6H5OH NaCl """, fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format( sum_atomic_weights_by_results_name_with_converted_ints(tokens) ), ) print() # Version 4 - parse and convert integers as subscript digits subscript_digits = "₀₁₂₃₄₅₆₇₈₉" subscript_int_map = {e[1]: e[0] for e in enumerate(subscript_digits)} def cvt_subscript_int(s): ret = 0 for c in s[0]: ret = ret * 10 + subscript_int_map[c] return ret subscript_int = pp.Word(subscript_digits).addParseAction(cvt_subscript_int).set_name("subscript") elementRef = pp.Group(element("symbol") + pp.Optional(subscript_int, default=1)("qty")) formula = elementRef[1, ...].setName("chemical_formula") formula.runTests( """\ H₂O C₆H₅OH NaCl """, fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format( sum_atomic_weights_by_results_name_with_converted_ints(tokens) ), ) print()
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,794
pyparsing/pyparsing
refs/heads/master
/examples/parsePythonValue.py
# parsePythonValue.py # # Copyright, 2006, by Paul McGuire # import pyparsing as pp cvtBool = lambda t: t[0] == "True" cvtInt = lambda toks: int(toks[0]) cvtReal = lambda toks: float(toks[0]) cvtTuple = lambda toks: tuple(toks.asList()) cvtDict = lambda toks: dict(toks.asList()) cvtList = lambda toks: [toks.asList()] # define punctuation as suppressed literals lparen, rparen, lbrack, rbrack, lbrace, rbrace, colon, comma = map( pp.Suppress, "()[]{}:," ) integer = pp.Regex(r"[+-]?\d+").setName("integer").setParseAction(cvtInt) real = pp.Regex(r"[+-]?\d+\.\d*([Ee][+-]?\d+)?").setName("real").setParseAction(cvtReal) tupleStr = pp.Forward().set_name("tuple_expr") listStr = pp.Forward().set_name("list_expr") dictStr = pp.Forward().set_name("dict_expr") unistr = pp.unicodeString().setParseAction(lambda t: t[0][2:-1]) quoted_str = pp.quotedString().setParseAction(lambda t: t[0][1:-1]) boolLiteral = pp.oneOf("True False", asKeyword=True).setParseAction(cvtBool) noneLiteral = pp.Keyword("None").setParseAction(pp.replaceWith(None)) listItem = ( real | integer | quoted_str | unistr | boolLiteral | noneLiteral | pp.Group(listStr) | tupleStr | dictStr ).set_name("list_item") tupleStr <<= ( lparen + pp.Optional(pp.delimitedList(listItem, allow_trailing_delim=True)) + rparen ) tupleStr.setParseAction(cvtTuple) listStr <<= ( lbrack + pp.Optional(pp.delimitedList(listItem, allow_trailing_delim=True)) + rbrack ) listStr.setParseAction(cvtList, lambda t: t[0]) dictEntry = pp.Group(listItem + colon + listItem).set_name("dict_entry") dictStr <<= ( lbrace + pp.Optional(pp.delimitedList(dictEntry, allow_trailing_delim=True)) + rbrace ) dictStr.setParseAction(cvtDict) if __name__ == "__main__": tests = """['a', 100, ('A', [101,102]), 3.14, [ +2.718, 'xyzzy', -1.414] ] [{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}] { 'A':1, 'B':2, 'C': {'a': 1.2, 'b': 3.4} } 3.14159 42 6.02E23 6.02e+023 1.0e-7 'a quoted string'""" listItem.runTests(tests)
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,795
pyparsing/pyparsing
refs/heads/master
/examples/numerics.py
# # numerics.py # # Examples of parsing real and integers using various grouping and # decimal point characters, varying by locale. # # Copyright 2016, Paul McGuire # # Format samples from https://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html # tests = """\ # Canadian (English and French) 4 294 967 295,000 # Danish 4 294 967 295,000 # Finnish 4 294 967 295,000 # French 4 294 967 295,000 # German 4 294 967 295,000 # Italian 4.294.967.295,000 # Norwegian 4.294.967.295,000 # Spanish 4.294.967.295,000 # Swedish 4 294 967 295,000 # GB-English 4,294,967,295.000 # US-English 4,294,967,295.000 # Thai 4,294,967,295.000 """ from pyparsing import Regex comma_decimal = Regex(r"\d{1,2}(([ .])\d\d\d(\2\d\d\d)*)?,\d*") comma_decimal.setParseAction( lambda t: float(t[0].replace(" ", "").replace(".", "").replace(",", ".")) ) dot_decimal = Regex(r"\d{1,2}(([ ,])\d\d\d(\2\d\d\d)*)?\.\d*") dot_decimal.setParseAction(lambda t: float(t[0].replace(" ", "").replace(",", ""))) decimal = comma_decimal ^ dot_decimal decimal.runTests(tests, parseAll=True) grouped_integer = Regex(r"\d{1,2}(([ .,])\d\d\d(\2\d\d\d)*)?") grouped_integer.setParseAction( lambda t: int(t[0].replace(" ", "").replace(",", "").replace(".", "")) ) grouped_integer.runTests(tests, parseAll=False)
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,796
pyparsing/pyparsing
refs/heads/master
/examples/unicode_denormalizer.py
# unicode_denormalizer.py # # Demonstration of the pyparsing's transform_string() method, to # convert identifiers in Python source code to equivalent Unicode # characters. Python's compiler automatically normalizes Unicode # characters back to their ASCII equivalents, so that identifiers may # be rewritten using other Unicode characters, and normalize back to # the same identifier. For instance, Python treats "print" and "𝕡𝓻ᵢ𝓃𝘁" # and "𝖕𝒓𝗂𝑛ᵗ" all as the same identifier. # # The converter must take care to *only* transform identifiers - # Python keywords must always be represented in base ASCII form. To # skip over keywords, they are added to the parser/transformer, but # contain no transforming parse action. # # The converter also detects identifiers in placeholders within f-strings. # # Copyright 2022, by Paul McGuire # import keyword import random import unicodedata import pyparsing as pp ppu = pp.pyparsing_unicode ident_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789·" ident_char_map = {}.fromkeys(ident_chars, "") for ch in ppu.identbodychars: normal = unicodedata.normalize("NFKC", ch) if normal in ident_char_map: ident_char_map[normal] += ch ligature_map = { 'ffl': 'ffl ffl ffl ffl ffl', 'ffi': 'ffi ffi ffi ffi ffi', 'ff': 'ff ff', 'fi': 'fi fi', 'fl': 'fl fl', 'ij': 'ij ij', 'lj': 'lj lj', 'nj': 'nj nj', 'dz': 'dz dz', 'ii': 'ii ⅱ', 'iv': 'iv ⅳ', 'vi': 'vi ⅵ', 'ix': 'ix ⅸ', 'xi': 'xi ⅺ', } ligature_transformer = pp.oneOf(ligature_map).add_parse_action(lambda t: random.choice(ligature_map[t[0]].split())) def make_mixed_font(t): t_0 = t[0][0] ret = ['_' if t_0 == '_' else random.choice(ident_char_map.get(t_0, t_0))] t_rest = ligature_transformer.transform_string(t[0][1:]) ret.extend(random.choice(ident_char_map.get(c, c)) for c in t_rest) return ''.join(ret) identifier = pp.pyparsing_common.identifier identifier.add_parse_action(make_mixed_font) python_quoted_string = pp.Opt(pp.Char("fF")("f_string_prefix")) + ( pp.quotedString | pp.QuotedString('"""', multiline=True, unquoteResults=False) | pp.QuotedString("'''", multiline=True, unquoteResults=False) )("quoted_string_body") def mix_fstring_expressions(t): if not t.f_string_prefix: return fstring_arg = pp.QuotedString("{", end_quote_char="}") fstring_arg.add_parse_action(lambda tt: "{" + transformer.transform_string(tt[0]) + "}") ret = t.f_string_prefix + fstring_arg.transform_string(t.quoted_string_body) return ret python_quoted_string.add_parse_action(mix_fstring_expressions) any_keyword = pp.MatchFirst(map(pp.Keyword, list(keyword.kwlist) + getattr(keyword, "softkwlist", []))) # quoted strings and keywords will be parsed, but left untransformed transformer = python_quoted_string | any_keyword | identifier def demo(): import textwrap hello_source = textwrap.dedent(""" def hello(): try: hello_ = "Hello" world_ = "World" print(f"{hello_}, {world_}!") except TypeError as exc: print("failed: {}".format(exc)) if __name__ == "__main__": hello() """) source = hello_source transformed = transformer.transform_string(source) print(transformed) # does it really work? code = compile(transformed, source, mode="exec") exec(code) if 0: # pick some code from the stdlib import unittest.util as lib_module import inspect source = inspect.getsource(lib_module) transformed = transformer.transform_string(source) print() print(transformed) if __name__ == '__main__': demo()
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,797
pyparsing/pyparsing
refs/heads/master
/examples/greetingInKorean.py
# # greetingInKorean.py # # Demonstration of the parsing module, on the prototypical "Hello, World!" example # # Copyright 2004-2016, by Paul McGuire # from pyparsing import Word, pyparsing_unicode as ppu koreanChars = ppu.Korean.alphas koreanWord = Word(koreanChars, min=2) # define grammar greet = koreanWord + "," + koreanWord + "!" # input string hello = "안녕, 여러분!" # "Hello, World!" in Korean # parse input string print(greet.parseString(hello))
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,798
pyparsing/pyparsing
refs/heads/master
/examples/adventureEngine.py
# adventureEngine.py # Copyright 2005-2006, Paul McGuire # # Updated 2012 - latest pyparsing API # from pyparsing import * import random import string def aOrAn(item): if item.desc[0] in "aeiou": return "an " + item.desc else: return "a " + item.desc def enumerateItems(l): if len(l) == 0: return "nothing" out = [] if len(l) > 1: out.append(", ".join(aOrAn(item) for item in l[:-1])) out.append("and") out.append(aOrAn(l[-1])) return " ".join(out) def enumerateDoors(l): if len(l) == 0: return "" out = [] if len(l) > 1: out.append(", ".join(l[:-1])) out.append("and") out.append(l[-1]) return " ".join(out) class Room: def __init__(self, desc): self.desc = desc self.inv = [] self.gameOver = False self.doors = [None, None, None, None] def __getattr__(self, attr): return { "n": self.doors[0], "s": self.doors[1], "e": self.doors[2], "w": self.doors[3], }[attr] def enter(self, player): if self.gameOver: player.gameOver = True def addItem(self, it): self.inv.append(it) def removeItem(self, it): self.inv.remove(it) def describe(self): print(self.desc) visibleItems = [it for it in self.inv if it.isVisible] if random.random() > 0.5: if len(visibleItems) > 1: is_form = "are" else: is_form = "is" print("There {} {} here.".format(is_form, enumerateItems(visibleItems))) else: print("You see %s." % (enumerateItems(visibleItems))) class Exit(Room): def __init__(self): super().__init__("") def enter(self, player): player.gameOver = True class Item: items = {} def __init__(self, desc): self.desc = desc self.isDeadly = False self.isFragile = False self.isBroken = False self.isTakeable = True self.isVisible = True self.isOpenable = False self.useAction = None self.usableConditionTest = None self.cantTakeMessage = "You can't take that!" Item.items[desc] = self def __str__(self): return self.desc def breakItem(self): if not self.isBroken: print("<Crash!>") self.desc = "broken " + self.desc self.isBroken = True def isUsable(self, player, target): if self.usableConditionTest: return self.usableConditionTest(player, target) else: return False def useItem(self, player, target): if self.useAction: self.useAction(player, self, target) class OpenableItem(Item): def __init__(self, desc, contents=None): super().__init__(desc) self.isOpenable = True self.isOpened = False if contents is not None: if isinstance(contents, Item): self.contents = [ contents, ] else: self.contents = contents else: self.contents = [] def openItem(self, player): if not self.isOpened: self.isOpened = not self.isOpened if self.contents is not None: for item in self.contents: player.room.addItem(item) self.contents = [] self.desc = "open " + self.desc def closeItem(self, player): if self.isOpened: self.isOpened = not self.isOpened if self.desc.startswith("open "): self.desc = self.desc[5:] class Command: "Base class for commands" def __init__(self, verb, verbProg): self.verb = verb self.verbProg = verbProg @staticmethod def helpDescription(): return "" def _doCommand(self, player): pass def __call__(self, player): print(self.verbProg.capitalize() + "...") self._doCommand(player) class MoveCommand(Command): def __init__(self, quals): super().__init__("MOVE", "moving") self.direction = quals.direction[0] @staticmethod def helpDescription(): return """MOVE or GO - go NORTH, SOUTH, EAST, or WEST (can abbreviate as 'GO N' and 'GO W', or even just 'E' and 'S')""" def _doCommand(self, player): rm = player.room nextRoom = rm.doors[ { "N": 0, "S": 1, "E": 2, "W": 3, }[self.direction] ] if nextRoom: player.moveTo(nextRoom) else: print("Can't go that way.") class TakeCommand(Command): def __init__(self, quals): super().__init__("TAKE", "taking") self.subject = quals.item @staticmethod def helpDescription(): return "TAKE or PICKUP or PICK UP - pick up an object (but some are deadly)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in rm.inv and subj.isVisible: if subj.isTakeable: rm.removeItem(subj) player.take(subj) else: print(subj.cantTakeMessage) else: print("There is no %s here." % subj) class DropCommand(Command): def __init__(self, quals): super().__init__("DROP", "dropping") self.subject = quals.item @staticmethod def helpDescription(): return "DROP or LEAVE - drop an object (but fragile items may break)" def _doCommand(self, player): rm = player.room subj = Item.items[self.subject] if subj in player.inv: rm.addItem(subj) player.drop(subj) else: print("You don't have %s." % (aOrAn(subj))) class InventoryCommand(Command): def __init__(self, quals): super().__init__("INV", "taking inventory") @staticmethod def helpDescription(): return "INVENTORY or INV or I - lists what items you have" def _doCommand(self, player): print("You have %s." % enumerateItems(player.inv)) class LookCommand(Command): def __init__(self, quals): super().__init__("LOOK", "looking") @staticmethod def helpDescription(): return "LOOK or L - describes the current room and any objects in it" def _doCommand(self, player): player.room.describe() class DoorsCommand(Command): def __init__(self, quals): super().__init__("DOORS", "looking for doors") @staticmethod def helpDescription(): return "DOORS - display what doors are visible from this room" def _doCommand(self, player): rm = player.room numDoors = sum([1 for r in rm.doors if r is not None]) if numDoors == 0: reply = "There are no doors in any direction." else: if numDoors == 1: reply = "There is a door to the " else: reply = "There are doors to the " doorNames = [ {0: "north", 1: "south", 2: "east", 3: "west"}[i] for i, d in enumerate(rm.doors) if d is not None ] # ~ print doorNames reply += enumerateDoors(doorNames) reply += "." print(reply) class UseCommand(Command): def __init__(self, quals): super().__init__("USE", "using") self.subject = Item.items[quals.usedObj] if quals.targetObj: self.target = Item.items[quals.targetObj] else: self.target = None @staticmethod def helpDescription(): return "USE or U - use an object, optionally IN or ON another object" def _doCommand(self, player): rm = player.room availItems = rm.inv + player.inv if self.subject in availItems: if self.subject.isUsable(player, self.target): self.subject.useItem(player, self.target) else: print("You can't use that here.") else: print("There is no %s here to use." % self.subject) class OpenCommand(Command): def __init__(self, quals): super().__init__("OPEN", "opening") self.subject = Item.items[quals.item] @staticmethod def helpDescription(): return "OPEN or O - open an object" def _doCommand(self, player): rm = player.room availItems = rm.inv + player.inv if self.subject in availItems: if self.subject.isOpenable: if not self.subject.isOpened: self.subject.openItem(player) else: print("It's already open.") else: print("You can't open that.") else: print("There is no %s here to open." % self.subject) class CloseCommand(Command): def __init__(self, quals): super().__init__("CLOSE", "closing") self.subject = Item.items[quals.item] @staticmethod def helpDescription(): return "CLOSE or CL - close an object" def _doCommand(self, player): rm = player.room availItems = rm.inv + player.inv if self.subject in availItems: if self.subject.isOpenable: if self.subject.isOpened: self.subject.closeItem(player) else: print("You can't close that, it's not open.") else: print("You can't close that.") else: print("There is no %s here to close." % self.subject) class QuitCommand(Command): def __init__(self, quals): super().__init__("QUIT", "quitting") @staticmethod def helpDescription(): return "QUIT or Q - ends the game" def _doCommand(self, player): print("Ok....") player.gameOver = True class HelpCommand(Command): def __init__(self, quals): super().__init__("HELP", "helping") @staticmethod def helpDescription(): return "HELP or H or ? - displays this help message" def _doCommand(self, player): print("Enter any of the following commands (not case sensitive):") for cmd in [ InventoryCommand, DropCommand, TakeCommand, UseCommand, OpenCommand, CloseCommand, MoveCommand, LookCommand, DoorsCommand, QuitCommand, HelpCommand, ]: print(" - %s" % cmd.helpDescription()) print() class AppParseException(ParseException): pass class Parser: def __init__(self): self.bnf = self.makeBNF() def makeBNF(self): invVerb = oneOf("INV INVENTORY I", caseless=True) dropVerb = oneOf("DROP LEAVE", caseless=True) takeVerb = oneOf("TAKE PICKUP", caseless=True) | ( CaselessLiteral("PICK") + CaselessLiteral("UP") ) moveVerb = oneOf("MOVE GO", caseless=True) | empty useVerb = oneOf("USE U", caseless=True) openVerb = oneOf("OPEN O", caseless=True) closeVerb = oneOf("CLOSE CL", caseless=True) quitVerb = oneOf("QUIT Q", caseless=True) lookVerb = oneOf("LOOK L", caseless=True) doorsVerb = CaselessLiteral("DOORS") helpVerb = oneOf("H HELP ?", caseless=True) itemRef = OneOrMore(Word(alphas)).setParseAction(self.validateItemName) nDir = oneOf("N NORTH", caseless=True).setParseAction(replaceWith("N")) sDir = oneOf("S SOUTH", caseless=True).setParseAction(replaceWith("S")) eDir = oneOf("E EAST", caseless=True).setParseAction(replaceWith("E")) wDir = oneOf("W WEST", caseless=True).setParseAction(replaceWith("W")) moveDirection = nDir | sDir | eDir | wDir invCommand = invVerb dropCommand = dropVerb + itemRef("item") takeCommand = takeVerb + itemRef("item") useCommand = ( useVerb + itemRef("usedObj") + Optional(oneOf("IN ON", caseless=True)) + Optional(itemRef, default=None)("targetObj") ) openCommand = openVerb + itemRef("item") closeCommand = closeVerb + itemRef("item") moveCommand = moveVerb + moveDirection("direction") quitCommand = quitVerb lookCommand = lookVerb doorsCommand = doorsVerb helpCommand = helpVerb # attach command classes to expressions invCommand.setParseAction(InventoryCommand) dropCommand.setParseAction(DropCommand) takeCommand.setParseAction(TakeCommand) useCommand.setParseAction(UseCommand) openCommand.setParseAction(OpenCommand) closeCommand.setParseAction(CloseCommand) moveCommand.setParseAction(MoveCommand) quitCommand.setParseAction(QuitCommand) lookCommand.setParseAction(LookCommand) doorsCommand.setParseAction(DoorsCommand) helpCommand.setParseAction(HelpCommand) # define parser using all command expressions return ( invCommand | useCommand | openCommand | closeCommand | dropCommand | takeCommand | moveCommand | lookCommand | doorsCommand | helpCommand | quitCommand )("command") + LineEnd() def validateItemName(self, s, l, t): iname = " ".join(t) if iname not in Item.items: raise AppParseException(s, l, "No such item '%s'." % iname) return iname def parseCmd(self, cmdstr): try: ret = self.bnf.parseString(cmdstr) return ret except AppParseException as pe: print(pe.msg) except ParseException as pe: print( random.choice( [ "Sorry, I don't understand that.", "Huh?", "Excuse me?", "???", "What?", ] ) ) class Player: def __init__(self, name): self.name = name self.gameOver = False self.inv = [] def moveTo(self, rm): self.room = rm rm.enter(self) if self.gameOver: if rm.desc: rm.describe() print("Game over!") else: rm.describe() def take(self, it): if it.isDeadly: print("Aaaagh!...., the %s killed me!" % it) self.gameOver = True else: self.inv.append(it) def drop(self, it): self.inv.remove(it) if it.isFragile: it.breakItem() def createRooms(rm): """ create rooms, using multiline string showing map layout string contains symbols for the following: A-Z, a-z indicate rooms, and rooms will be stored in a dictionary by reference letter -, | symbols indicate connection between rooms <, >, ^, . symbols indicate one-way connection between rooms """ # start with empty dictionary of rooms ret = {} # look for room symbols, and initialize dictionary # - exit room is always marked 'Z' for c in rm: if c in string.ascii_letters: if c != "Z": ret[c] = Room(c) else: ret[c] = Exit() # scan through input string looking for connections between rooms rows = rm.split("\n") for row, line in enumerate(rows): for col, c in enumerate(line): if c in string.ascii_letters: room = ret[c] n = None s = None e = None w = None # look in neighboring cells for connection symbols (must take # care to guard that neighboring cells exist before testing # contents) if col > 0 and line[col - 1] in "<-": other = line[col - 2] w = ret[other] if col < len(line) - 1 and line[col + 1] in "->": other = line[col + 2] e = ret[other] if row > 1 and col < len(rows[row - 1]) and rows[row - 1][col] in "|^": other = rows[row - 2][col] n = ret[other] if ( row < len(rows) - 1 and col < len(rows[row + 1]) and rows[row + 1][col] in "|." ): other = rows[row + 2][col] s = ret[other] # set connections to neighboring rooms room.doors = [n, s, e, w] return ret # put items in rooms def putItemInRoom(i, r): if isinstance(r, str): r = rooms[r] r.addItem(Item.items[i]) def playGame(p, startRoom): # create parser parser = Parser() p.moveTo(startRoom) while not p.gameOver: cmdstr = input(">> ") cmd = parser.parseCmd(cmdstr) if cmd is not None: cmd.command(p) print() print("You ended the game with:") for i in p.inv: print(" -", aOrAn(i)) # ==================== # start game definition roomMap = """ d-Z | f-c-e . | q<b | A """ rooms = createRooms(roomMap) rooms["A"].desc = "You are standing on the front porch of a wooden shack." rooms["b"].desc = "You are in a garden." rooms["c"].desc = "You are in a kitchen." rooms["d"].desc = "You are on the back porch." rooms["e"].desc = "You are in a library." rooms["f"].desc = "You are on the patio." rooms["q"].desc = "You are sinking in quicksand. You're dead..." rooms["q"].gameOver = True # define global variables for referencing rooms frontPorch = rooms["A"] garden = rooms["b"] kitchen = rooms["c"] backPorch = rooms["d"] library = rooms["e"] patio = rooms["f"] # create items itemNames = ( """sword.diamond.apple.flower.coin.shovel.book.mirror.telescope.gold bar""".split( "." ) ) for itemName in itemNames: Item(itemName) Item.items["apple"].isDeadly = True Item.items["mirror"].isFragile = True Item.items["coin"].isVisible = False Item.items["shovel"].usableConditionTest = lambda p, t: p.room is garden def useShovel(p, subj, target): coin = Item.items["coin"] if not coin.isVisible and coin in p.room.inv: coin.isVisible = True Item.items["shovel"].useAction = useShovel Item.items["telescope"].isTakeable = False def useTelescope(p, subj, target): print("You don't see anything.") Item.items["telescope"].useAction = useTelescope OpenableItem("treasure chest", Item.items["gold bar"]) Item.items["chest"] = Item.items["treasure chest"] Item.items["chest"].isTakeable = False Item.items["chest"].cantTakeMessage = "It's too heavy!" OpenableItem("mailbox") Item.items["mailbox"].isTakeable = False Item.items["mailbox"].cantTakeMessage = "It's nailed to the wall!" putItemInRoom("mailbox", frontPorch) putItemInRoom("shovel", frontPorch) putItemInRoom("coin", garden) putItemInRoom("flower", garden) putItemInRoom("apple", library) putItemInRoom("mirror", library) putItemInRoom("telescope", library) putItemInRoom("book", kitchen) putItemInRoom("diamond", backPorch) putItemInRoom("treasure chest", patio) # create player plyr = Player("Bob") plyr.take(Item.items["sword"]) # start game playGame(plyr, frontPorch)
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,799
pyparsing/pyparsing
refs/heads/master
/examples/excelExpr.py
# excelExpr.py # # Copyright 2010, Paul McGuire # # A partial implementation of a parser of Excel formula expressions. # from pyparsing import ( CaselessKeyword, Suppress, Word, alphas, alphanums, nums, Optional, Group, oneOf, Forward, infixNotation, opAssoc, dblQuotedString, delimitedList, Combine, Literal, QuotedString, ParserElement, pyparsing_common as ppc, ) ParserElement.enablePackrat() EQ, LPAR, RPAR, COLON, COMMA = map(Suppress, "=():,") EXCL, DOLLAR = map(Literal, "!$") sheetRef = Word(alphas, alphanums) | QuotedString("'", escQuote="''") colRef = Optional(DOLLAR) + Word(alphas, max=2) rowRef = Optional(DOLLAR) + Word(nums) cellRef = Combine( Group(Optional(sheetRef + EXCL)("sheet") + colRef("col") + rowRef("row")) ) cellRange = ( Group(cellRef("start") + COLON + cellRef("end"))("range") | cellRef | Word(alphas, alphanums) ) expr = Forward() COMPARISON_OP = oneOf("< = > >= <= != <>") condExpr = expr + COMPARISON_OP + expr ifFunc = ( CaselessKeyword("if") - LPAR + Group(condExpr)("condition") + COMMA + Group(expr)("if_true") + COMMA + Group(expr)("if_false") + RPAR ) def stat_function(name): return Group(CaselessKeyword(name) + Group(LPAR + delimitedList(expr) + RPAR)) sumFunc = stat_function("sum") minFunc = stat_function("min") maxFunc = stat_function("max") aveFunc = stat_function("ave") funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc multOp = oneOf("* /") addOp = oneOf("+ -") numericLiteral = ppc.number operand = numericLiteral | funcCall | cellRange | cellRef arithExpr = infixNotation( operand, [ (multOp, 2, opAssoc.LEFT), (addOp, 2, opAssoc.LEFT), ], ) textOperand = dblQuotedString | cellRef textExpr = infixNotation( textOperand, [ ("&", 2, opAssoc.LEFT), ], ) expr <<= arithExpr | textExpr def main(): success, report = (EQ + expr).runTests( """\ =3*A7+5 =3*Sheet1!$A$7+5 =3*'Sheet 1'!$A$7+5 =3*'O''Reilly''s sheet'!$A$7+5 =if(Sum(A1:A25)>42,Min(B1:B25),if(Sum(C1:C25)>3.14, (Min(C1:C25)+3)*18,Max(B1:B25))) =sum(a1:a25,10,min(b1,c2,d3)) =if("T"&a2="TTime", "Ready", "Not ready") """ ) assert success if __name__ == '__main__': main()
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,800
pyparsing/pyparsing
refs/heads/master
/examples/rangeCheck.py
# rangeCheck.py # # A sample program showing how parse actions can convert parsed # strings into a data type or object, and to validate the parsed value. # # Updated to use new addCondition method and expr() copy. # # Copyright 2011,2015 Paul T. McGuire # from pyparsing import Word, nums, Suppress, Optional from datetime import datetime def ranged_value(expr, minval=None, maxval=None): # have to specify at least one range boundary if minval is None and maxval is None: raise ValueError("minval or maxval must be specified") # set range testing function and error message depending on # whether either or both min and max values are given inRangeCondition = { (True, False): lambda s, l, t: t[0] <= maxval, (False, True): lambda s, l, t: minval <= t[0], (False, False): lambda s, l, t: minval <= t[0] <= maxval, }[minval is None, maxval is None] outOfRangeMessage = { (True, False): "value is greater than %s" % maxval, (False, True): "value is less than %s" % minval, (False, False): "value is not in the range ({} to {})".format(minval, maxval), }[minval is None, maxval is None] return expr().addCondition(inRangeCondition, message=outOfRangeMessage) # define the expressions for a date of the form YYYY/MM/DD or YYYY/MM (assumes YYYY/MM/01) integer = Word(nums).setName("integer") integer.setParseAction(lambda t: int(t[0])) month = ranged_value(integer, 1, 12) day = ranged_value(integer, 1, 31) year = ranged_value(integer, 2000, None) SLASH = Suppress("/") dateExpr = year("year") + SLASH + month("month") + Optional(SLASH + day("day")) dateExpr.setName("date") # convert date fields to datetime (also validates dates as truly valid dates) dateExpr.setParseAction(lambda t: datetime(t.year, t.month, t.day or 1).date()) # add range checking on dates mindate = datetime(2002, 1, 1).date() maxdate = datetime.now().date() dateExpr = ranged_value(dateExpr, mindate, maxdate) dateExpr.runTests( """ 2011/5/8 2001/1/1 2004/2/29 2004/2 1999/12/31""" )
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,801
pyparsing/pyparsing
refs/heads/master
/examples/macroExpander.py
# macroExpander.py # # Example pyparsing program for performing macro expansion, similar to # the C pre-processor. This program is not as fully-featured, simply # processing macros of the form: # #def xxx yyyyy # and replacing xxx with yyyyy in the rest of the input string. Macros # can also be composed using other macros, such as # #def zzz xxx+1 # Since xxx was previously defined as yyyyy, then zzz will be replaced # with yyyyy+1. # # Copyright 2007 by Paul McGuire # from pyparsing import * # define the structure of a macro definition (the empty term is used # to advance to the next non-whitespace character) identifier = Word(alphas + "_", alphanums + "_") macroDef = "#def" + identifier("macro") + empty + restOfLine("value") # define a placeholder for defined macros - initially nothing macroExpr = Forward() macroExpr << NoMatch() # global dictionary for macro definitions macros = {} # parse action for macro definitions def processMacroDefn(s, l, t): macroVal = macroExpander.transformString(t.value) macros[t.macro] = macroVal macroExpr << MatchFirst(map(Keyword, macros.keys())) return "#def " + t.macro + " " + macroVal # parse action to replace macro references with their respective definition def processMacroRef(s, l, t): return macros[t[0]] # attach parse actions to expressions macroExpr.setParseAction(processMacroRef) macroDef.setParseAction(processMacroDefn) # define pattern for scanning through the input string macroExpander = macroExpr | macroDef # test macro substitution using transformString testString = """ #def A 100 #def ALEN A+1 char Astring[ALEN]; char AA[A]; typedef char[ALEN] Acharbuf; """ print(macroExpander.transformString(testString)) print(macros)
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,802
pyparsing/pyparsing
refs/heads/master
/tests/test_diagram.py
import unittest from io import StringIO from pathlib import Path from typing import List from examples.jsonParser import jsonObject from examples.simpleBool import boolExpr from examples.simpleSQL import simpleSQL from examples.mozillaCalendarParser import calendars from pyparsing.diagram import to_railroad, railroad_to_html, NamedDiagram import pyparsing as pp import tempfile import os import sys print(f"Running {__file__}") print(sys.version_info) curdir = Path(__file__).parent def is_run_with_coverage(): """Check whether test is run with coverage. From https://stackoverflow.com/a/69812849/165216 """ gettrace = getattr(sys, "gettrace", None) if gettrace is None: return False else: gettrace_result = gettrace() try: from coverage.pytracer import PyTracer from coverage.tracer import CTracer if isinstance(gettrace_result, (CTracer, PyTracer)): return True except ImportError: pass return False def running_in_debug() -> bool: """ Returns True if we're in debug mode (determined by either setting environment var, or running in a debugger which sets sys.settrace) """ return ( os.environ.get("RAILROAD_DEBUG", False) or sys.gettrace() and not is_run_with_coverage() ) class TestRailroadDiagrams(unittest.TestCase): def get_temp(self): """ Returns an appropriate temporary file for writing a railroad diagram """ delete_on_close = not running_in_debug() return tempfile.NamedTemporaryFile( dir=".", delete=delete_on_close, mode="w", encoding="utf-8", suffix=".html", ) def generate_railroad( self, expr: pp.ParserElement, label: str, show_results_names: bool = False ) -> List[NamedDiagram]: """ Generate an intermediate list of NamedDiagrams from a pyparsing expression. """ with self.get_temp() as temp: railroad = to_railroad(expr, show_results_names=show_results_names) temp.write(railroad_to_html(railroad)) if running_in_debug(): print(f"{label}: {temp.name}") return railroad def test_example_rr_diags(self): subtests = [ (jsonObject, "jsonObject", 8), (boolExpr, "boolExpr", 5), (simpleSQL, "simpleSQL", 20), (calendars, "calendars", 13), ] for example_expr, label, expected_rr_len in subtests: with self.subTest(f"{label}: test rr diag without results names"): railroad = self.generate_railroad(example_expr, example_expr) if len(railroad) != expected_rr_len: diag_html = railroad_to_html(railroad) for line in diag_html.splitlines(): if 'h1 class="railroad-heading"' in line: print(line) assert ( len(railroad) == expected_rr_len ), f"expected {expected_rr_len}, got {len(railroad)}" with self.subTest(f"{label}: test rr diag with results names"): railroad = self.generate_railroad( example_expr, example_expr, show_results_names=True ) if len(railroad) != expected_rr_len: print(railroad_to_html(railroad)) assert ( len(railroad) == expected_rr_len ), f"expected {expected_rr_len}, got {len(railroad)}" def test_nested_forward_with_inner_and_outer_names(self): outer = pp.Forward().setName("outer") inner = pp.Word(pp.alphas)[...].setName("inner") outer <<= inner railroad = self.generate_railroad(outer, "inner_outer_names") assert len(railroad) == 2 railroad = self.generate_railroad( outer, "inner_outer_names", show_results_names=True ) assert len(railroad) == 2 def test_nested_forward_with_inner_name_only(self): outer = pp.Forward() inner = pp.Word(pp.alphas)[...].setName("inner") outer <<= inner railroad = self.generate_railroad(outer, "inner_only") assert len(railroad) == 2 railroad = self.generate_railroad(outer, "inner_only", show_results_names=True) assert len(railroad) == 2 def test_each_grammar(self): grammar = pp.Each( [ pp.Word(pp.nums), pp.Word(pp.alphas), pp.pyparsing_common.uuid, ] ).setName("int-word-uuid in any order") railroad = self.generate_railroad(grammar, "each_expression") assert len(railroad) == 2 railroad = self.generate_railroad( grammar, "each_expression", show_results_names=True ) assert len(railroad) == 2 def test_none_name(self): grammar = pp.Or(["foo", "bar"]) railroad = to_railroad(grammar) assert len(railroad) == 1 assert railroad[0].name is not None def test_none_name2(self): grammar = pp.Or(["foo", "bar"]) + pp.Word(pp.nums).setName("integer") railroad = to_railroad(grammar) assert len(railroad) == 2 assert railroad[0].name is not None railroad = to_railroad(grammar, show_results_names=True) assert len(railroad) == 2 def test_complete_combine_element(self): ints = pp.Word(pp.nums) grammar = pp.Combine( ints("hours") + pp.Literal(":") + ints("minutes") + pp.Literal(":") + ints("seconds") ) railroad = to_railroad(grammar) assert len(railroad) == 1 railroad = to_railroad(grammar, show_results_names=True) assert len(railroad) == 1 def test_create_diagram(self): ints = pp.Word(pp.nums) grammar = pp.Combine( ints("hours") + pp.Literal(":") + ints("minutes") + pp.Literal(":") + ints("seconds") ) diag_strio = StringIO() grammar.create_diagram(output_html=diag_strio) diag_str = diag_strio.getvalue().lower() tags = "<html> </html> <head> </head> <body> </body>".split() assert all(tag in diag_str for tag in tags) def test_create_diagram_embed(self): ints = pp.Word(pp.nums) grammar = pp.Combine( ints("hours") + pp.Literal(":") + ints("minutes") + pp.Literal(":") + ints("seconds") ) diag_strio = StringIO() grammar.create_diagram(output_html=diag_strio, embed=True) diag_str = diag_strio.getvalue().lower() tags = "<html> </html> <head> </head> <body> </body>".split() assert not any(tag in diag_str for tag in tags) if __name__ == "__main__": unittest.main()
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,803
pyparsing/pyparsing
refs/heads/master
/examples/holaMundo.py
# escrito por Marco Alfonso, 2004 Noviembre # importamos los símbolos requeridos desde el módulo from pyparsing import ( Word, alphas, oneOf, nums, Group, OneOrMore, pyparsing_unicode as ppu, ) # usamos las letras en latin1, que incluye las como 'ñ', 'á', 'é', etc. alphas = ppu.Latin1.alphas # Aqui decimos que la gramatica "saludo" DEBE contener # una palabra compuesta de caracteres alfanumericos # (Word(alphas)) mas una ',' mas otra palabra alfanumerica, # mas '!' y esos seian nuestros tokens saludo = Word(alphas) + "," + Word(alphas) + oneOf("! . ?") tokens = saludo.parseString("Hola, Mundo !") # Ahora parseamos una cadena, "Hola, Mundo!", # el metodo parseString, nos devuelve una lista con los tokens # encontrados, en caso de no haber errores... for i, token in enumerate(tokens): print("Token %d -> %s" % (i, token)) # imprimimos cada uno de los tokens Y listooo!!, he aquí a salida # Token 0 -> Hola # Token 1 -> , # Token 2-> Mundo # Token 3 -> ! # ahora cambia el parseador, aceptando saludos con mas que una sola palabra antes que ',' saludo = Group(OneOrMore(Word(alphas))) + "," + Word(alphas) + oneOf("! . ?") tokens = saludo.parseString("Hasta mañana, Mundo !") for i, token in enumerate(tokens): print("Token %d -> %s" % (i, token)) # Ahora parseamos algunas cadenas, usando el metodo runTests saludo.runTests( """\ Hola, Mundo! Hasta mañana, Mundo ! """, fullDump=False, ) # Por supuesto, se pueden "reutilizar" gramáticas, por ejemplo: numimag = Word(nums) + "i" numreal = Word(nums) numcomplex = numreal + "+" + numimag print(numcomplex.parseString("3+5i")) # Funcion para cambiar a complejo numero durante parsear: def hace_python_complejo(t): valid_python = "".join(t).replace("i", "j") return complex(valid_python) numcomplex.setParseAction(hace_python_complejo) print(numcomplex.parseString("3+5i")) # Excelente!!, bueno, los dejo, me voy a seguir tirando código...
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,804
pyparsing/pyparsing
refs/heads/master
/examples/cpp_enum_parser.py
# # cpp_enum_parser.py # # Posted by Mark Tolonen on comp.lang.python in August, 2009, # Used with permission. # # Parser that scans through C or C++ code for enum definitions, and # generates corresponding Python constant definitions. # # from pyparsing import * # sample string with enums and other stuff sample = """ stuff before enum hello { Zero, One, Two, Three, Five=5, Six, Ten=10 }; in the middle enum blah { alpha, beta, gamma = 10 , zeta = 50 }; at the end """ # syntax we don't want to see in the final parse tree LBRACE, RBRACE, EQ, COMMA = map(Suppress, "{}=,") _enum = Suppress("enum") identifier = Word(alphas, alphanums + "_") integer = Word(nums) enumValue = Group(identifier("name") + Optional(EQ + integer("value"))) enumList = Group(enumValue + ZeroOrMore(COMMA + enumValue)) enum = _enum + identifier("enum") + LBRACE + enumList("names") + RBRACE # find instances of enums ignoring other syntax for item, start, stop in enum.scanString(sample): id = 0 for entry in item.names: if entry.value != "": id = int(entry.value) print("%s_%s = %d" % (item.enum.upper(), entry.name.upper(), id)) id += 1
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,805
pyparsing/pyparsing
refs/heads/master
/examples/linenoExample.py
# # linenoExample.py # # an example of using the location value returned by pyparsing to # extract the line and column number of the location of the matched text, # or to extract the entire line of text. # # Copyright (c) 2006, Paul McGuire # from pyparsing import * data = """Now is the time for all good men to come to the aid of their country.""" # demonstrate use of lineno, line, and col in a parse action def reportLongWords(st, locn, toks): word = toks[0] if len(word) > 3: print( "Found '%s' on line %d at column %d" % (word, lineno(locn, st), col(locn, st)) ) print("The full line of text was:") print("'%s'" % line(locn, st)) print((" " * col(locn, st)) + " ^") print() wd = Word(alphas).setParseAction(reportLongWords) OneOrMore(wd).parseString(data) # demonstrate returning an object from a parse action, containing more information # than just the matching token text class Token: def __init__(self, st, locn, tokString): self.tokenString = tokString self.locn = locn self.sourceLine = line(locn, st) self.lineNo = lineno(locn, st) self.col = col(locn, st) def __str__(self): return "%(tokenString)s (line: %(lineNo)d, col: %(col)d)" % self.__dict__ def createTokenObject(st, locn, toks): return Token(st, locn, toks[0]) wd = Word(alphas).setParseAction(createTokenObject) for tokenObj in OneOrMore(wd).parseString(data): print(tokenObj)
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,806
pyparsing/pyparsing
refs/heads/master
/tests/test_examples.py
# # test_examples.py # from importlib import import_module import unittest class TestExamples(unittest.TestCase): def _run(self, name): mod = import_module("examples." + name) getattr(mod, "main", lambda *args, **kwargs: None)() def test_numerics(self): self._run("numerics") def test_tap(self): self._run("TAP") def test_roman_numerals(self): self._run("romanNumerals") def test_sexp_parser(self): self._run("sexpParser") def test_oc(self): self._run("oc") def test_delta_time(self): self._run("delta_time") def test_eval_arith(self): self._run("eval_arith") def test_select_parser(self): self._run("select_parser") def test_booleansearchparser(self): self._run("booleansearchparser") def test_rosettacode(self): self._run("rosettacode") def test_excelExpr(self): self._run("excelExpr") def test_delta_time(self): self._run("delta_time")
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,550,807
pyparsing/pyparsing
refs/heads/master
/examples/htmlStripper.py
# # htmlStripper.py # # Sample code for stripping HTML markup tags and scripts from # HTML source files. # # Copyright (c) 2006, 2016, Paul McGuire # from urllib.request import urlopen from pyparsing import ( makeHTMLTags, commonHTMLEntity, replaceHTMLEntity, htmlComment, anyOpenTag, anyCloseTag, LineEnd, replaceWith, ) scriptOpen, scriptClose = makeHTMLTags("script") scriptBody = scriptOpen + scriptOpen.tag_body + scriptClose commonHTMLEntity.setParseAction(replaceHTMLEntity) # get some HTML targetURL = "https://wiki.python.org/moin/PythonDecoratorLibrary" with urlopen(targetURL) as targetPage: targetHTML = targetPage.read().decode("UTF-8") # first pass, strip out tags and translate entities firstPass = ( (htmlComment | scriptBody | commonHTMLEntity | anyOpenTag | anyCloseTag) .suppress() .transformString(targetHTML) ) # first pass leaves many blank lines, collapse these down repeatedNewlines = LineEnd() * (2,) repeatedNewlines.setParseAction(replaceWith("\n\n")) secondPass = repeatedNewlines.transformString(firstPass) print(secondPass)
{"/tests/test_unit.py": ["/examples/jsonParser.py", "/tests/json_parser_tests.py", "/examples/fourFn.py", "/examples/simpleSQL.py"], "/tests/test_diagram.py": ["/examples/jsonParser.py", "/examples/simpleBool.py", "/examples/simpleSQL.py", "/examples/mozillaCalendarParser.py"], "/examples/make_diagram.py": ["/examples/delta_time.py"], "/examples/test_bibparse.py": ["/examples/btpyparse.py"]}
41,621,156
Brandon300055/ChessBot
refs/heads/master
/bot.py
from board import Board from piece import Piece class Bot: def __init__(self, board, botColor = "b", whiteScore=0, blackScore=0, level=0): self.board = board[:] self.setBoard = board[:] self.botColor = botColor # score tracker self.whiteScore = whiteScore self.blackScore = blackScore self.level = level def findMove(self): # max level depth if self.level == 4: return board = self.board[:] # store current board # create new board instance # boardClass = Board(setBoard) # boardClass.printBoard() # get all moves for board for color x = 0 y = 0 movesPerPiece = [] # search over all board for i in board: for j in i: piece = board[x][y] # check side case if str(piece)[0] == self.botColor: # set selectedPiece selectedPiece = [x, y] # get all the moves pieceClass = Piece(board, selectedPiece) moves = pieceClass.getMoves() # print list movesPerPiece += [[str(board[x][y]), moves]] print("-------------" + piece + "-------------") # boardClass.setSelectedPiece(selectedPiece) # print(boardClass.selectedPiece) # create boards for each move for move in moves: print("-------------" + str(move) + "-------------") # # boardClass.setBoard(board) # start with current bord # boardClass.move(move[0], move[1]) # make move # the move space moveSpace = board[move[0]][move[1]] # weight score if moveSpace != False: pass # make the move board[move[0]][move[1]] = str(piece) board[x][y] = False # clear the old space for i in self.setBoard: print(i) # reset board board = self.setBoard[:] # self.board = self.setBoard # board[move[0]][move[1]] = self.board[self.selectedPiece[0]][self.selectedPiece[1]] # board[self.selectedPiece[0]][self.selectedPiece[1]] = False # print(board) # # boardClass.printBoard() # board = Board(setBoard) y += 1 y = 0 x += 1 # self.selectedPiece = False print (movesPerPiece) # allMoves = board.getAllMoves(self.botColor) # # print(allMoves) # # # generate a bord with each move # for i in range(5): # piece = allMoves[i][0] # print(allMoves[i][1]) # # # test all moves for pice # for j in range(allMoves[i][1]): # print(allMoves[i]) # print(board.selectPiece("bn1").moves()) # print(allMoves[i]) # for i in allMoves: # # # boardClass = Board(board) # # # boardClass.printBoard() # # test = boardClass.selectPiece("wn2").moves() # # print(test) # # def bfs(graph, initial): # # visited = [] # # queue = [initial] # # while queue: # # node = queue.pop(0) # if node not in visited: # # visited.append(node) # neighbours = graph[node] # # for neighbour in neighbours: # queue.append(neighbour) # return visited # print(bfs(graph, 'A')) # def testMove(self, board): # board.selectPiece("wp5").move(5, 5) # board.printBoard()
{"/main.py": ["/board.py", "/bot.py"], "/bot.py": ["/board.py", "/piece.py"], "/board.py": ["/piece.py"]}
41,643,178
rowlanja/CSU33012_Github_Visualizer
refs/heads/master
/wsgi.py
from app.main import app import requests if __name__ == "__main__": app.run()
{"/wsgi.py": ["/app/main.py"]}
41,643,179
rowlanja/CSU33012_Github_Visualizer
refs/heads/master
/app/main.py
from flask import Flask, redirect, request, render_template import requests import json import random import dateutil.parser import datetime labels = [] values = [] dates = [] commits= [] colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA", "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1", "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"] app= Flask(__name__) @app.route('/') def home(): return render_template('homePage.html') @app.route('/', methods=['POST']) def my_form_post(): text = request.form.get('username') #GETTING USER PROFILE INFO user_request = requests.get('https://api.github.com/users/'+text, auth=('rowlanja', '72f894a6faa4ee1fd6cee8b51bb722d6587a0601')).json() name = user_request["login"] location = user_request["location"] company = user_request["company"] hireable = user_request["hireable"] email = user_request["email"] bio = user_request["bio"] twitter_username = user_request["twitter_username"] followers = user_request["followers"] following = user_request["following"] created_at = user_request["created_at"] created_at = dateutil.parser.parse(created_at) created_at = created_at.date().strftime("%d/%m/%Y") blog = user_request["blog"] #GETTING Programming LANGUAGES USED INFO #PUTS LANGUAGES IN LABELS LIST #PUT LANGUAGE USED COUNT IN VALUES LIST user_request = requests.get('https://api.github.com/users/'+text+"/repos", auth=('rowlanja', '72f894a6faa4ee1fd6cee8b51bb722d6587a0601')).json() languageDict = {} for val in user_request : if(val["language"] != None) : languageDict[val["language"]] = languageDict.get(val["language"], 0) + 1 random_number = random.randint(0,16777215) hex_number = str(hex(random_number)) hex_number ='#'+ hex_number[2:] colors.append(hex_number) labels = languageDict.keys() values = languageDict.values() #GETTING COMMIT HISTORY #PUTS DATES IN DATES LIST #PUT COMMIT COUNT IN COMMITS LIST user_request = requests.get('https://api.github.com/users/'+text+"/events", auth=('rowlanja', '72f894a6faa4ee1fd6cee8b51bb722d6587a0601')).json() for entry in user_request : x = entry["payload"] if "commits" in x : size = len(x["commits"]) yourdate = dateutil.parser.parse(entry["created_at"]) yourdate = yourdate.date().strftime("%d/%m/%Y") dates.append(yourdate) commits.append(size) maxCommitCount = max(commits) repoLanguages=getLanguages(text) repoLanguages = sorted(repoLanguages.items(), key= lambda x: len(x[1])) repoLanguages = dict(repoLanguages) print("sorted", repoLanguages) #print(getLanguages(text)) return render_template('user.html', name = name, location = location, company = company, hireable = hireable, email = email, bio = bio, twitter_username = twitter_username, followers = followers, following = following, created_at = created_at, blog = blog, title='Bitcoin Monthly Price in USD', max=1, set=zip( values, labels, colors), labelsLine=dates, valuesLine=commits, followersList=getFollowers(text), repoLanguages=repoLanguages ) #GETS THE LIST OF FOLLOWERS OF A USER def getFollowers(userName): user_request = requests.get('https://api.github.com/users/'+userName+"/followers", auth=('rowlanja', '72f894a6faa4ee1fd6cee8b51bb722d6587a0601')).json() followers = {} for user in user_request : followers[user["login"]]= user["html_url"] return followers # GETS THE REPOS % LANGUAGES USED # THE IF STATEMENT CHECK WHETHER THE LANGUAGE KEY IS SET TO A VALUE IN THE REPOS API RESPONSE # IF THE REPO HAS MULTIPLE LANGUAGES THIS VLAUE IS NULL AND THE LANGUAGES ARE STORED AT THE /REPO/LANGUAGES API ENPOINT # IF THE REPO HAS A SINGLE VALUE THEN THE LANGUAGE WILL BE DIRECTLY STORED ON THE /REPOS API ENPOINT def getLanguages(userName): user_request = requests.get('https://api.github.com/users/'+userName+"/repos", auth=('rowlanja', '72f894a6faa4ee1fd6cee8b51bb722d6587a0601')).json() repoLanguages = {} for repo in user_request : if repo["language"] : language_request = requests.get('https://api.github.com/repos/'+repo["full_name"]+"/languages", auth=('rowlanja', '72f894a6faa4ee1fd6cee8b51bb722d6587a0601')).json() repoLanguages[repo["name"]] = language_request elif repo["language"] and not(repo["language"] is None): repoLanguages[repo["name"]] = repo["language"] return repoLanguages @app.route('/linechart') def line(): line_labels=labels line_values=values return render_template('linechart.html', title='Bitcoin Monthly Price in USD', max=17000, labels=line_labels, values=line_values) if __name__ == '__main__': app.run(threaded=True, port=5000)
{"/wsgi.py": ["/app/main.py"]}
41,649,548
chiranjeev11/chints11-microblog
refs/heads/master
/app/main/routes.py
from flask import Blueprint from app import db from datetime import datetime main = Blueprint('main', __name__) @main.before_request def before_request(): if current_user.is_authenticated: current_user.last_seen = datetime.utcnow() db.session.commit()
{"/app/__init__.py": ["/config.py", "/app/users/routes.py", "/app/posts/routes.py", "/app/main/routes.py"], "/app/errors.py": ["/app/__init__.py"], "/app/main/routes.py": ["/app/__init__.py"], "/app/posts/routes.py": ["/app/__init__.py", "/app/posts/forms.py", "/app/models.py"], "/microblog.py": ["/app/__init__.py", "/app/models.py"], "/app/models.py": ["/app/__init__.py"], "/app/users/routes.py": ["/app/posts/forms.py", "/app/__init__.py", "/app/models.py"], "/test.py": ["/app/__init__.py", "/app/models.py"]}
41,649,549
chiranjeev11/chints11-microblog
refs/heads/master
/migrations/versions/66c72bb0f972_new_fields_in_user_model.py
"""new fields in user model Revision ID: 66c72bb0f972 Revises: Create Date: 2021-02-08 12:01:43.512163 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '66c72bb0f972' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('about_me', sa.String(length=140), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'about_me') # ### end Alembic commands ###
{"/app/__init__.py": ["/config.py", "/app/users/routes.py", "/app/posts/routes.py", "/app/main/routes.py"], "/app/errors.py": ["/app/__init__.py"], "/app/main/routes.py": ["/app/__init__.py"], "/app/posts/routes.py": ["/app/__init__.py", "/app/posts/forms.py", "/app/models.py"], "/microblog.py": ["/app/__init__.py", "/app/models.py"], "/app/models.py": ["/app/__init__.py"], "/app/users/routes.py": ["/app/posts/forms.py", "/app/__init__.py", "/app/models.py"], "/test.py": ["/app/__init__.py", "/app/models.py"]}
41,649,550
chiranjeev11/chints11-microblog
refs/heads/master
/app/posts/routes.py
from flask import render_template, flash, redirect, url_for, request, Blueprint, current_app from app import db from flask_login import current_user from app.posts.forms import EmptyForm, PostForm from app.models import User, Post from flask_login import login_required from guess_language import guess_language from flask_babel import _ posts = Blueprint('posts', __name__) # Home page @posts.route('/', methods=['GET', 'POST']) @posts.route('/index', methods=['GET', 'POST']) @login_required def view(): page = request.args.get('page', 1, type=int) # If True, when an out of range page is requested a 404 error will be automatically returned to the client. If False, an empty list will be returned for out of range pages. post = current_user.followed_post().paginate(page, current_app.config['POSTS_PER_PAGE'], False) next_url = None prev_url = None if post.has_next: # Here page is query argument in the url next_url = url_for('posts.view', page=post.next_num) if post.has_prev: prev_url = url_for('posts.view', page=post.prev_num) return render_template('index.html',title='Home Page', posts=post.items, next_url=next_url, prev_url=prev_url) @posts.route('/user/<username>') @login_required def user(username): user = User.query.filter_by(username=username).first_or_404() form = EmptyForm() image_file = url_for('static', filename=f"profile_pics/{current_user.image_file}") page = request.args.get('page', 1, type=int) posts = user.post.order_by(Post.timestamp.desc()).paginate(page, current_app.config['POSTS_PER_PAGE'], False) next_url = None prev_url = None if posts.has_next: next_url = url_for('posts.user', username=username, page=posts.next_num) if posts.has_prev: prev_url = url_for('posts.user', username=username, page=posts.prev_num) return render_template('user.html', user=user, form=form, posts=posts.items, next_url=next_url, prev_url=prev_url, image_file=image_file) @posts.route('/post/new_post/', methods=['GET', 'POST']) @login_required def new_post(): form = PostForm() if form.validate_on_submit(): language = guess_language(form.post.data) if language == 'UNKNOWN' or len(language) > 5: language = '' post = Post(body=form.post.data, author=current_user, language=language) db.session.add(post) db.session.commit() flash(_('Your post is now live !')) return redirect(url_for('posts.view')) return render_template('create_post.html', form=form)
{"/app/__init__.py": ["/config.py", "/app/users/routes.py", "/app/posts/routes.py", "/app/main/routes.py"], "/app/errors.py": ["/app/__init__.py"], "/app/main/routes.py": ["/app/__init__.py"], "/app/posts/routes.py": ["/app/__init__.py", "/app/posts/forms.py", "/app/models.py"], "/microblog.py": ["/app/__init__.py", "/app/models.py"], "/app/models.py": ["/app/__init__.py"], "/app/users/routes.py": ["/app/posts/forms.py", "/app/__init__.py", "/app/models.py"], "/test.py": ["/app/__init__.py", "/app/models.py"]}
41,649,551
chiranjeev11/chints11-microblog
refs/heads/master
/test.py
from app import app, db from app.models import User, Post from datetime import datetime, timedelta import unittest class UserModelCase(unittest.TestCase): def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_password_hashing(self): u = User(username='Chints') u.set_password('123') self.assertFalse(u.check_password('abc')) self.assertTrue(u.check_password('123')) def test_follow(self): u1 = User(username='Chiranjeev', email='chiranjeevkhurana11@gmail.com') u2 = User(username='Shubham', email='shubham@gmail.com') db.session.add(u1) db.session.add(u2) db.session.commit() self.assertEqual(u1.followed.all(), []) self.assertEqual(u1.followers.all(), []) u1.follow(u2) db.session.commit() self.assertTrue(u1.is_following(u2)) self.assertEqual(u1.followed.count(), 1) self.assertEqual(u1.followed.first().username, 'Shubham') self.assertEqual(u2.followers.count(), 1) self.assertEqual(u2.followers.first().username, 'Chiranjeev') u1.unfollow(u2) db.session.commit() self.assertFalse(u1.is_following(u2)) self.assertEqual(u1.followed.count(), 0) self.assertEqual(u2.followers.count(), 0) if __name__ == '__main__': unittest.main(verbosity=2) # def mult(): # return (lambda x: i*x for i in range(4)) # x = [m(2) for m in mult()] # print(x) # # print(x.__next__()) # # print(x.__next__()) # # print(x.__next__()) # # print(x.__next__()) # # for m in []: # # print(m) # # print(m(2)) # def extend(val, list1=[]): # list1.append(val) # return list1 # l1 = extend(10) # l2 = extend(10,[]) # l3 = extend('a') # print(id(l1)) # print(id(l2)) # print(id(l3))
{"/app/__init__.py": ["/config.py", "/app/users/routes.py", "/app/posts/routes.py", "/app/main/routes.py"], "/app/errors.py": ["/app/__init__.py"], "/app/main/routes.py": ["/app/__init__.py"], "/app/posts/routes.py": ["/app/__init__.py", "/app/posts/forms.py", "/app/models.py"], "/microblog.py": ["/app/__init__.py", "/app/models.py"], "/app/models.py": ["/app/__init__.py"], "/app/users/routes.py": ["/app/posts/forms.py", "/app/__init__.py", "/app/models.py"], "/test.py": ["/app/__init__.py", "/app/models.py"]}
41,649,552
chiranjeev11/chints11-microblog
refs/heads/master
/check_flask_sync_or_async.py
from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app, resources = {r'/*':{'origins': '*'}}) import time @app.route('/') def hello(): return 'ok1' @app.route('/bc') def hello2(): print('mc1') time.sleep(50) print('mc2') return 'ok2' @app.route('/bkl') def hello3(): time.sleep(10) return 'ok3'
{"/app/__init__.py": ["/config.py", "/app/users/routes.py", "/app/posts/routes.py", "/app/main/routes.py"], "/app/errors.py": ["/app/__init__.py"], "/app/main/routes.py": ["/app/__init__.py"], "/app/posts/routes.py": ["/app/__init__.py", "/app/posts/forms.py", "/app/models.py"], "/microblog.py": ["/app/__init__.py", "/app/models.py"], "/app/models.py": ["/app/__init__.py"], "/app/users/routes.py": ["/app/posts/forms.py", "/app/__init__.py", "/app/models.py"], "/test.py": ["/app/__init__.py", "/app/models.py"]}
41,796,228
jorgeMunozMartinez/jenkins_ci
refs/heads/master
/script.py
#!/usr/bin/env python3 print ('Script de python')
{"/pruebas.py": ["/script.py"]}
41,805,996
lukashaverbeck/parknet
refs/heads/master
/connection.py
# This module contains entities that are closely related to creating, maintaining and # accessing a local network of agents. # It defines a local webserver handing POST requests that are sent between multiple agents # and a connector that ensures that a connection between the vehicles is created. # it also implements utility funcions that provide information about the network. # # version: 1.0 (4.2.2020) # # TODO simplify code in `AutoConnector` # TODO Remove unused method in SSIDBlock import os import time import logging import traceback from threading import Thread, Event import tornado.web import tornado.ioloop from wifi import Cell import socket as socketlib from wireless import Wireless from contextlib import closing from PyAccessPoint import pyaccesspoint import interaction import constants as const # Enable the debug information for hotspot and tornado webserver to find errors # logging.basicConfig(format="%(asctime)s ::%(levelname)s:: %(message)s", level=logging.DEBUG) def get_local_ip(): """ determines the local IP of the current device Returns: str: local IP of the current device """ f = os.popen('hostname -I') ip = f.read() return ip def check_if_up(ip_address): """ determines if there is a webserver running on a given ip adress Args: ip_address (str): ip4 adress from the local network Returns: bool: Boolean whether the server is running (True) or not (False) """ socket = socketlib.socket(socketlib.AF_INET, socketlib.SOCK_STREAM) socket.settimeout(0.004) try: with closing(socket): socket.connect((str(ip_address), 80)) return True except socketlib.error: return False class TornadoWebserver(tornado.web.RequestHandler): """ custom http server handling POST or GET requests """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.communication = interaction.Communication.instance() def get(self): # print("Request from " + str(self.request.remote_ip)) try: self.write("<h1>Agent</h1> <p>ID: " + self.communication.agent.id + "</p>") except AttributeError: raise AttributeError( "The class `Server` was not provided with a communication instance before a GET request was sent.") def post(self): self.set_header("Content-Type", "text/plain") self.write("<h1>POST</h1>") response = bytes(self.request.body).decode("utf-8") response_data = response.split("=", 1) try: # trigger event callbacks for data in response_data: self.communication.trigger(data) except AttributeError: raise AttributeError( "The class `Server` was not provided with a communication instance before a POST request was sent.") def get_webserver_application(): return tornado.web.Application([ (r"/", TornadoWebserver) ]) class WebThread(Thread): def __init__(self): self.ip = "unset" Thread.__init__(self, name='WebThread') def define_ip(self, ip): self.ip = ip def run(self): ioloop = tornado.ioloop.IOLoop() application = get_webserver_application() #tornado.web.Application http_server_api = tornado.httpserver.HTTPServer(application) try: http_server_api.listen(80) print("Starting webserver on " + str(self.ip)) ioloop.start() except OSError: print("Already connected to this address or address blocked " + str(self.ip)) class SSIDBlock: """ object to block a ssid for a given time """ def __init__(self, ssid, blocktime): self.blocktime = blocktime self.ssid = ssid # TODO Unused? def __repr__(self): return f"SSIDBlock [#{self.ssid} {self.blocktime}]" class AutoConnector(Thread): """ thread that connects to a wlan, if available, or creates a hotspot for other devices """ def __init__(self, event): super().__init__() self.stopped = event self.count = 0 self.wlan_count_found = 0 self.wireless_module = Wireless() self.wlan_name_found_to_connect = "" self.wlan_name_found_to_connect_time = 999999999999 # defines a hotspot object with the ssid "Test Wlan" and the password from the constants, # ssid will be changed later. Because of a known bug, the hotspot is stopped once before the start. self.access_point = pyaccesspoint.AccessPoint(ssid="Test Wlan", password=const.Connection.WLAN_PASSWORD) self.access_point.stop() self.hotspot_status = False self.own_wlan_name_from_hotspot = "parknet" self.own_wlan_time_from_hotspot = 9999999999999 self.last_wlan_connected = "unset" self.block_list = [] def run(self): """ starts scanning for wlan and connects to a wlan or starts a hotspot, if necessary """ while not self.stopped.wait(5): self.wlan_count_found = 0 self.count += 1 print(f"Connected with: {self.wireless_module.current()}") if self.wireless_module.current() is None: if self.last_wlan_connected != "unset": time_for_block = int(time.time()) + 60 self.add_to_block_list(self.last_wlan_connected, time_for_block) self.last_wlan_connected = "unset" else: self.last_wlan_connected = self.wireless_module.current() self.wlan_scan() print(f"Loop Count: {self.count} Wlans: {self.wlan_count_found}") self.connect_to_network_or_create_hotspot() def wlan_scan(self): """ scans for wlan networks and selects the network that is called "parknet" and has existed the longest """ self.wlan_name_found_to_connect = "" self.wlan_name_found_to_connect_time = 999999999999 try: wlan_scans = Cell.all("wlan0") for wlan_scan in wlan_scans: if wlan_scan.ssid.startswith("parknet"): if wlan_scan.ssid != self.own_wlan_name_from_hotspot: try: time_wlan_create = int(wlan_scan.ssid.replace("parknet", "")) if time_wlan_create < self.wlan_name_found_to_connect_time: if not self.is_blocked(str(wlan_scan.ssid)): print( f"{wlan_scan.ssid} Quality: {wlan_scan.quality} Protected: {wlan_scan.encrypted}") self.wlan_count_found += 1 self.wlan_name_found_to_connect = wlan_scan.ssid self.wlan_name_found_to_connect_time = time_wlan_create else: print(f"Blocked Wlan Hotspot Found: {wlan_scan.ssid}") except ValueError: print(f"Wrong Wlan Hotspot Found: {wlan_scan.ssid.replace('parknet', '')}") else: print( f"Found own hotspot {wlan_scan.ssid} Quality: {wlan_scan.quality} Protected: {wlan_scan.encrypted}") if wlan_scan.ssid == "Lukas123": print("Found Lukas Wlan") self.wlan_name_found_to_connect = wlan_scan.ssid self.wlan_name_found_to_connect_time = 1 self.wlan_count_found += 1 break except: print(f"Error while scanning for wifi {traceback.format_exc()}") def start_hotspot(self): """ starts a hotspot with the name "parkent" and the current time""" if not self.hotspot_status: print("Starting hotspot") self.own_wlan_name_from_hotspot = "parknet" + str(int(time.time())) self.own_wlan_time_from_hotspot = int(time.time()) self.access_point.ssid = self.own_wlan_name_from_hotspot self.access_point.start() self.hotspot_status = True def stop_hotspot(self): """ stops the hotspot """ if self.hotspot_status: print("Disabling hotspot") self.access_point.stop() self.hotspot_status = False self.own_wlan_time_from_hotspot = 9999999999999 def connect_to_network_or_create_hotspot(self): """ starts a hotspot if no suitable wlan network was found or connects to a wlan""" if self.wlan_count_found <= 0: print("Hotspot mode") self.start_hotspot() elif self.own_wlan_time_from_hotspot > self.wlan_name_found_to_connect_time: if self.hotspot_status: print("Hotspot mode off") self.stop_hotspot() elif self.wireless_module.current() != self.wlan_name_found_to_connect: print(f"Connecting to network {self.wlan_name_found_to_connect}") print( f"Status: {self.wireless_module.connect(self.wlan_name_found_to_connect, const.Connection.WLAN_PASSWORD)}") time.sleep(2) print(f"Wlan network: {self.wireless_module.current()}") if self.wireless_module.current() is not None: self.last_wlan_connected = self.wireless_module.current() def is_blocked(self, ssid): """ checks whether an SSID is currently blocked Args: ssid(str): The name of the wlan that should be checked for a block Returns: bool: Whether the given ssid is blocked (True) or not (False) """ for block in self.block_list: if block.ssid == ssid and block.blocktime > int(time.time()): return True else: return False return False def add_to_block_list(self, ssid, blocktime): """ blocks a ssid for a given time Args: ssid(str): The name of the wlan that should be blocked blocktime(int): Time how long the wlan name should be blocked """ self.block_list.append(SSIDBlock(ssid, blocktime)) print(f"Blocking {ssid} for {blocktime}") def print_list(self): """ prints a list of WLAN networks that were blocked at some point and whether they are currently blocked""" for block in self.block_list: print(f"{block} Blocked: {self.is_blocked(block.ssid)}") @staticmethod def start_connector(): """ starts the thread for the AutoConnector""" stopFlag = Event() thread = AutoConnector(stopFlag) thread.start()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,805,997
lukashaverbeck/parknet
refs/heads/master
/vision.py
# This module contains entities that collect information about the agent's environment # including sensor data about the measured distances to the vehicle's front, right and back # and visual camera data. It also uses the camera input to provide information about other agents # in the agent's field of view. # # version: 1.0 (29.12.2019) # # TODO improve QR code analysis import time from threading import Thread import picamera import picamera.array from gpiozero import DistanceSensor import pyzbar.pyzbar as pyzbar import constants as const from util import Singleton, threaded def lazy_sensor_update(direction, sensor): """ decorator function that ensures that a distance sensor is only activated in certain time intervals NOTE this decorator should only be used as a decorator for distance sensor data property functions Args: direction (str): direction of the distance sensor sensor (DistanceSensor): sensor capturing distance data Returns: function: decorator wrapper function """ def wrapper(func): """ wrapper function containing the update function Args: func (function): property function for a specific sensor Returns: function: decorator function updating the sensor data """ def update(sensor_manager): """ function that updated a sensor data point if it is being requested and has not been updated for a while Args: sensor_manager (SensorManager): instance of a sensor manager whose distance data is being requested Returns: float: the result of the request being produced by the corresponding property function """ timestamp = time.time() update_data = sensor_manager.updates[direction] # check if the distance value should be updated if update_data["time"] < timestamp - sensor_manager.REFRESH_INTERVAL: # update the distance value and the corresponding timestamp update_data["value"] = sensor.distance * 100 update_data["time"] = timestamp return func(sensor_manager) return update return wrapper @Singleton class SensorManager: """ collects information about the distance to obstacles around the vehicle """ REFRESH_INTERVAL = 0.1 # interval in which new values are calculated # keys for sensor data dictionary FRONT_KEY = "front" RIGHT_KEY = "right" REAR_KEY = "rear" REAR_ANGLED_KEY = "rear_angled" # distance sensors SENSOR_FRONT = DistanceSensor(echo=const.EchoPin.FRONT, trigger=const.TriggerPin.FRONT) SENSOR_RIGHT = DistanceSensor(echo=const.EchoPin.RIGHT, trigger=const.TriggerPin.RIGHT) SENSOR_REAR = DistanceSensor(echo=const.EchoPin.BACK, trigger=const.TriggerPin.BACK) SENSOR_REAR_ANGLED = DistanceSensor(echo=const.EchoPin.BACK_ANGLED, trigger=const.TriggerPin.BACK_ANGLED) def __init__(self): """ initializes the sensor manager by defining a dictionary that keeps track of their last update timestamps and values """ self.updates = { self.FRONT_KEY: { "time": 0, "value": 0 }, self.RIGHT_KEY: { "time": 0, "value": 0 }, self.REAR_KEY: { "time": 0, "value": 0 }, self.REAR_ANGLED_KEY: { "time": 0, "value": 0 } } @property @lazy_sensor_update(FRONT_KEY, SENSOR_FRONT) def front(self): """ determines the distance value of the front sensor NOTE this method can be used as a `property` NOTE this property is being updated automatically (see `lazy_sensor_update`) Returns: float: latest measured distance value """ return self.updates[self.FRONT_KEY]["value"] @property @lazy_sensor_update(RIGHT_KEY, SENSOR_RIGHT) def right(self): """ determines the distance value of the right sensor NOTE this method can be used as a `property` NOTE this property is being updated automatically (see `lazy_sensor_update`) Returns: float: latest measured distance value """ return self.updates[self.RIGHT_KEY]["value"] @property @lazy_sensor_update(REAR_KEY, SENSOR_REAR) def rear(self): """ determines the distance value of the rear sensor NOTE this method can be used as a `property` NOTE this property is being updated automatically (see `lazy_sensor_update`) Returns: float: latest measured distance value """ return self.updates[self.REAR_KEY]["value"] @property @lazy_sensor_update(REAR_ANGLED_KEY, SENSOR_REAR_ANGLED) def rear_angled(self): """ determines the distance value of the rear angled sensor NOTE this method can be used as a `property` NOTE this property is being updated automatically (see `lazy_sensor_update`) Returns: float: latest measured distance value """ return self.updates[self.REAR_ANGLED_KEY]["value"] @Singleton class Camera: """ captures images NOTE this class should be used as a context manager """ def __init__(self): """ initializes the camera """ self.image = None self.uses = 0 def __enter__(self): """ starts the camera as a context manager """ # check if the camera was not used before if self.uses <= 0: self.uses = 1 self.record() else: self.uses += 1 return self def __exit__(self, exc_type, exc_value, traceback): """ leaves the context manager """ self.uses -= 1 @threaded def record(self): """ constanly takes images as long as there is at least one instance accessing the camera """ with picamera.PiCamera() as camera: camera.brightness = 60 while self.uses > 0: with picamera.array.PiRGBArray(camera) as frame: # capture an image and save it locally camera.capture(frame, "rgb") self.image = frame.array @Singleton class FrontAgentScanner: """ analyzes the camera input and extracts agent IDs by scanning QR Codes """ UPDATE_INTERVAL = 3 def __init__(self): """ initializes the FrontAgentScanner """ self.id = None self.uses = 0 def __enter__(self): """ starts the scanner as a context manager """ # check if the scanner was not used before if self.uses <= 0: self.uses = 1 self.update() else: self.uses += 1 return self def __exit__(self, exc_type, exc_value, traceback): """ leaves the context manager """ self.uses -= 1 @threaded def update(self): """ constanly updates the front agent ID based on the current video input as long as there is at least one instance accessing the camera TODO add validation whether a found QR code really represents an agent ID -> check for multiple QR codes and select the most plausible one """ with Camera.instance() as camera: while self.uses > 0: # analyze the camera input with respect to QR Codes representing an agent ID if camera.image is not None: decoded_objects = pyzbar.decode(camera.image) # check if any QR codes have been found if len(decoded_objects) > 0: # decode the first QR code and set the ID accordingly data_bytes = decoded_objects[0].data self.id = data_bytes.decode("utf-8") else: self.id = None time.sleep(self.UPDATE_INTERVAL)
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,805,998
lukashaverbeck/parknet
refs/heads/master
/tests/test_vehicle.py
import sys from pathlib import Path sys.path.append(str(Path(sys.path[0]).parent)) import unittest from vehicle import Agent, Driver class TestVehicle(unittest.TestCase): def setUp(self): self.driver_1 = Driver.instance() self.driver_2 = Driver.instance() self.agent_1 = Agent.instance() self.agent_2 = Agent.instance() return super().setUp() def test_driver(self): self.assertIs(self.driver_1, self.driver_2) self.assertEqual(self.driver_1, self.driver_2) self.assertEqual(self.driver_1.velocity, 0) self.driver_1.accelerate(5) self.assertEqual(self.driver_1.velocity, 5) self.driver_1.accelerate(-10) self.assertEqual(self.driver_1.velocity, -5) self.driver_1.accelerate(100) self.assertEqual(self.driver_1.velocity, 5) self.assertEqual(self.driver_1.angle, 0) self.driver_1.steer(35) self.assertEqual(self.driver_1.angle, 35) self.driver_1.steer(-70) self.assertEqual(self.driver_1.angle, -35) self.driver_1.steer(100) self.assertEqual(self.driver_1.angle, 35) self.driver_1.start_recording() self.assertIsNotNone(self.driver_1.recorder_thread) self.driver_1.stop_recording() self.assertIsNone(self.driver_1.recorder_thread) self.driver_1.start_driving() self.assertIsNotNone(self.driver_1.drive_thread) self.driver_1.stop_driving() self.assertIsNone(self.driver_1.drive_thread) def test_agent(self): self.assertIs(self.agent_1, self.agent_2) self.assertEqual(self.agent_1, self.agent_2) self.assertIsNotNone(self.agent_1.id) self.assertIsNotNone(self.agent_1.length) self.assertIsNotNone(self.agent_1.width) self.assertGreater(len(self.agent_1.id), 0) self.assertGreater(self.agent_1.length, 0) self.assertGreater(self.agent_1.width, 0) if __name__ == "__main__": unittest.main()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,805,999
lukashaverbeck/parknet
refs/heads/master
/scripts/hotspot.py
# This script opens up a standalone wifi network with user determined network information. # # version: 1.0 (31.12.2019) import time import threading import time import logging from PyAccessPoint import pyaccesspoint logging.basicConfig(format="%(asctime)s ::%(levelname)s:: %(message)s", level=logging.DEBUG) access_point = pyaccesspoint.AccessPoint(ssid="Test123" , password="Hallo123") access_point.start() print(access_point.is_running()) print("Creating access point ssid: Test123 and passwort: Hallo123") print("In order to connect to your picar via SSH use network information and standard user information for login.") time.sleep(30) print("3") time.sleep(1) print("2") time.sleep(1) print("1") time.sleep(1) print ("Shutting down!") access_point.stop() # stop potential legacy acces points access_point.stop()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,000
lukashaverbeck/parknet
refs/heads/master
/tests/test_util.py
import sys from pathlib import Path sys.path.append(str(Path(sys.path[0]).parent)) import unittest from util import Singleton @Singleton class Something: pass class TestUtil(unittest.TestCase): def setUp(self): self.something_1 = Something.instance() self.something_2 = Something.instance() return super().setUp() def test_singleton(self): self.assertIs(self.something_1, self.something_2) with self.assertRaises(TypeError): Something() if __name__ == "__name__": unittest.main()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,001
lukashaverbeck/parknet
refs/heads/master
/scripts/pca_controler.py
# This script is used to control any type of pwm-controlled hardware attached to the PCA9685 module. # It allows to send a specific pwm signal to the seperate channels of the # PCA9685 module as well as to one of several modules by specifying a I2C-address. # # version: 1.0 (30.12.2019) import sys import time import curses # keyboard input and UI import Adafruit_PCA9685 screen = curses.initscr() # create new screen curses.echo() # do echo keyboard input curses.cbreak() # do not wait for user to confirm manually screen.keypad(True) # enable special-keys # start values for I2C communication and PCA-module connection pwm = 0 bus = 0 addr = 0x00 chnl = 0 class Controller: def __init__(self): """ collects information on connection and initializes I2C-link """ self.getI2Cinfo() self.pwm = Adafruit_PCA9685.PCA9685(address = self.addr, busnum = self.bus) self.getPCAinfo() self.sendSignal() # start loop for signal input def getI2Cinfo(self): """ collects I2C information from user """ screen.clear() screen.addstr("If you want to use default I2C-values press 'y', otherwise default values are used: ") screen.refresh() answ = screen.getch() # user is supposed to type 'y' to use standard values or any other character to provide them manually if answ == ord('y'): # user confirms to use default values self.addr = 0x40 # default I2C address self.bus = 1 # default I2C busnumber (for Raspberry Pi's newer than model 1) # NOTE do not use this yet, it potentially breaks the script use default I2C data instead elif answ != ord('y'): # user hands over I2C information manually screen.addstr("Please enter the I2C-address of your PCA9685 module: ") screen.refresh() self.addr = screen.getch() # get I2C address from user input screen.clear() screen.addstr("Please enter the I2C-bus of your PCA9685 module: ") screen.refresh() self.bus = screen.getch() # get I2C busnumber from user input def getPCAinfo(self): """get PCA channel from user""" screen.clear() screen.addstr("Please enter the PCA9685 channel you want to send a signal to: ") screen.refresh() val1 = screen.getkey() # first character of portnumber val2 = screen.getkey() # second character of portnumber val0 = val1 + val2 try: chnl = int(val0) # cast string into int if chnl < 0 or chnl > 15: # make sure input fits to boundaries of PCA-channels screen.clear() screen.addstr("Not a valid channel. Ending program.") screen.refresh() time.sleep(2) self.end() self.chnl = chnl except: # if there are any non-int characters in the string screen.clear() screen.addstr("Not a valid channel. Ending program.") #blame the user screen.refresh() time.sleep(2) self.end() def sendSignal(self): """ takes a pwm value from the user and pushes it to the given channel """ screen.clear() screen.addstr("Please enter your pwm value: ") screen.refresh() while True: val1 = screen.getkey() # first character of pwm value if val1 == "q": # stop script when the q key is pressed self.end() break val2 = screen.getkey() # second character of pwm value val3 = screen.getkey() # third character of pwm value val0 = val1 + val2 + val3 # create three digit string try: val = int(val0) self.pwm.set_pwm(self.chnl, 0, val) # push signal to channel screen.clear() screen.addstr(f"Curent value is {val}. Please enter your new pwm value: ") # ask user for new value screen.refresh() except: # if there are any non-int characters in the string screen.clear() screen.addstr("Input is not a valid pwm value! Please enter a valid pwm value: ") screen.refresh() time.sleep(3) def end(self): """ resets terminal settings and ends script """ curses.nocbreak() screen.keypad(0) curses.echo() curses.endwin() sys.exit() if __name__ == "__name__": cotroller = Controller()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,002
lukashaverbeck/parknet
refs/heads/master
/scripts/manual_drive.py
# This script controls a picar with keyboard input via ssh console. # # version: 1.0 (31.12.2019) import curses # keyboard input import Adafruit_PCA9685 # PCA9685-module from time import sleep import threading import RPi.GPIO as GPIO # GPIO-pin control screen = curses.initscr() # create new screen curses.noecho() # do not echo keyboard input curses.cbreak() # disable return-press for input screen.keypad(True) # enable special-keys GPIO.setwarnings(False) # disable GPIO warnings for console convenience GPIO.setmode(GPIO.BCM) # GPIO instance works in broadcom-memory mode GPIO.setup(21, GPIO.OUT) # step pin is an output pwm = Adafruit_PCA9685.PCA9685(address=0x40, busnum=1) # create PCA9685-object at I2C-port steering_left = 35 # steer to maximum left steering_neutral = 0 # steer to neutral position steering_right = -35 # steer to maximum right pulse_freq = 50 # I2C communication frequency pwm.set_pwm_freq(pulse_freq) # set frequency # make sure the car does not run away on start current_rps = 0 # start without stepper movement current_steering = steering_neutral def calc_angle(angle): """ calculates a pwm value for a given angle Args: angle (float): angle to be converted to a pwm value Returns: float: corresponding pwm value """ return 2e-6 * angle ** 4 + 2e-6 * angle ** 3 + .005766 * angle ** 2 - 1.81281 * angle + 324.149 def move_stepper(delay): if delay != 0: try: while True: sleep(1) # wait to keep rps print("test") finally: pass # controls: try: delay = 0 t = threading.Thread(target=move_stepper, args=(delay,)) t.start() while True: screen.refresh() char = screen.getch() # get keyboard input screen.clear() if char == ord('q'): # pressing q stops the script t = None break elif char == ord('w'): # pressing w increases speed # screen.addstr("W pressed") if current_rps < 5: current_rps += 1 move = True elif char == ord('s'): # pressing s decreases speed # screen.addstr("S pressed") if current_rps > 0: current_rps -= 1 move = True elif char == ord('a'): # pressing a steers left # screen.addstr("A pressed") if current_steering < steering_left: current_steering += 7 move = True elif char == ord('d'): # pressing d steers right # screen.addstr("D pressed") if current_steering > steering_right: current_steering -= 7 move = True elif char == ord('e'): # pressing e returns car to start condition # screen.addstr("E pressed") current_rps = 0 current_steering = steering_neutral move = True if move: # move converts input to motor controls pwm_calc = calc_angle(current_steering) # calculate steering pwm value from angle pwm.set_pwm(0, 0, int(pwm_calc)) # set pwm value for steering motor if current_rps > 0: # only calculate if possible delay = (1 / (200 * float(current_rps))) / 2 # delay based on rounds per second elif current_rps == 0: # unable to devide by zero delay = 0 t.join() # updates parameters of thread ????? screen.clear() screen.addstr(f"Velocity: {current_rps}[rps]" + " Steering angle: {current_steering}[degree]") screen.refresh() # leave cleanly to prevent a messed up console finally: curses.nocbreak() screen.keypad(0) curses.echo() curses.endwin() curses.endwin()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,003
lukashaverbeck/parknet
refs/heads/master
/scripts/distance.py
# This script calculates the distance between an HC-SR04 module and the nearest object. # It is capable of handling multiple modules simultaneously. # # version: 1.0 (30.12.2019) import RPi.GPIO as GPIO import time import curses # keyboard input and interface screen = curses.initscr() # create new screen screen.nodelay(True) # .getch() is ignored if no keyboard input is detected curses.noecho() # do not ECHO_1 keyboard input curses.cbreak() # disable return-press for input screen.keypad(True) # enable special-keys GPIO.setmode(GPIO.BCM) # set GPIO mode TRIG_1 = 18 # trigger pin of HC-SR04 module(front) TRIG_2 = 23 # trigger pin of HC-SR04 module(side) TRIG_3 = 25 # trigger pin of HC-SR04 module(back) TRIG_4 = 24 # trigger pin of HC-SR04 module(back-angled) ECHO_1 = 4 # echo pin of HC-SR04 module(front) ECHO_2 = 17 # echo pin of HC-SR04 module(side) ECHO_3 = 22 # echo pin of HC-SR04 module(back) ECHO_4 = 27 # echo pin of HC-SR04 module(back-angled) # define all trigger pins as outputs and all echo pins as inputs # make sure all pins ar free to use to avoid data collision GPIO.setup(TRIG_1, GPIO.OUT) GPIO.setup(ECHO_1, GPIO.IN) GPIO.setup(TRIG_2, GPIO.OUT) GPIO.setup(ECHO_2, GPIO.IN) GPIO.setup(TRIG_3, GPIO.OUT) GPIO.setup(ECHO_3, GPIO.IN) GPIO.setup(TRIG_4, GPIO.OUT) GPIO.setup(ECHO_4, GPIO.IN) def measure_distance(trigpin, echopin): """ gets distance value from the module with the reported pins Args: trigpin (int): pin sending the signal echopin (int): pin sending the signal Returns: float: measured distance in cm rounded to two decimal places """ GPIO.output(trigpin, True) # activate the trigger channel of HC-SR04 module time.sleep(0.00001) # 10µs activate 8 ultrasound bursts at 40 kHz GPIO.output(trigpin, False) # deactivate trigger channel while GPIO.input(echopin) == 0: # measure time in which echo signal is detected pulse_start = time.time() while GPIO.input(echopin) == 1: # measure the time of the echo signal pulse_end = time.time() pulse_duration = pulse_end - pulse_start # time it took the signal to hit the object and return to sensor distance = pulse_duration * 17150 # calculate into cm 34300[cm/s]=Distance[cm]/(Time[s]/2) distance = round(distance, 2) return distance GPIO.output(TRIG_1, False) # pull down trigger pin in case the pin is still activated screen.addstr("Waiting For Sensor To Settle") screen.refresh() # making an output during waiting time time.sleep(2) # wait two seconds to make sure there are no signal fragments which could be detected screen.clear() # clear the output area # cycle with sensordetection while True: char = screen.getch() # get keyboard input if char == ord('q'): # stop script when the q key is pressed break distance_1 = measure_distance(TRIG_1, ECHO_1) # call sensordetection function for front module distance_2 = measure_distance(TRIG_2, ECHO_2) # call sensordetection function for side module distance_3 = measure_distance(TRIG_3, ECHO_3) # call sensordetection function for back module distance_4 = measure_distance(TRIG_4, ECHO_4) # call sensordetection function for back module screen.clear() # clear screen for next output # sho results in the console screen.addstr("Distance_front: " + str(distance_1) + "cm\n") screen.addstr("Distance_side: " + str(distance_2) + "cm\n") screen.addstr("Distance_back: " + str(distance_3) + "cm\n") screen.addstr("Distance_back(angled): " + str(distance_4) + "cm") screen.refresh() # in order to not mess up the console all setting need to be reset to default values GPIO.cleanup() curses.nocbreak() screen.keypad(0) curses.echo() curses.endwin()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,004
lukashaverbeck/parknet
refs/heads/master
/interaction.py
# This module contains entities that handle the communication and interaction between agents # as well as the coordination of their actions. # Therefore it defines a communication interface that allows to subscribe to, send and # receive messages in a local network. # It handles coordination by exchanging information about the arrangement of vehicles in # a parking lot as well as their intention to take certain actions in order to ensure permission # to take an action without one central decision maker. # # version: 1.0 (29.12.2019) import json import time import requests from threading import Thread from http.server import HTTPServer import vehicle import constants as const from util import Singleton, threaded from vision import FrontAgentScanner from connection import get_local_ip, check_if_up,WebThread @Singleton class Communication: """ handles the communication between multiple agents by assigning callback functions to certain events """ def __init__(self): """ initializes a communication object and starts a local HTTP Server """ # intitialize and start web server self.local_ip = "127.0.0.1" self.connection_status = True web_server_thread = WebThread() web_server_thread.define_ip(self.local_ip) web_server_thread.start() self.subscriptions = [] self.agent = vehicle.Agent.instance() def set_local_ip(self , ip_address): self.local_ip = ip_address self.connection_status = True print(f"Restarting Webserver on {self.local_ip}") web_server_thread = WebThread() web_server_thread.define_ip(ip_address) web_server_thread.start() def lost_connection(self): self.connection_status = False def scan_ips_from_network(self): """ determines the used ip addresses in the network Returns: list: list of used ips in the network Raises: IndexError: in case an ip address could not be interpreted """ ips = [] local_ip = self.local_ip ip_parts = local_ip.split(".") try: ip_network = ip_parts[0] + "." + ip_parts[1] + "." + ip_parts[2] + "." except IndexError: raise IndexError("local IP address is invalid") else: for i in range(2, 158): ip = ip_network + str(i) result = check_if_up(ip) if result: ips.append(ip) if local_ip in ips: ips.remove(local_ip) return ips def subscribe(self, topic, callback): """ subscribes to a topic by defining a callback function that is triggered when the event occours Args: topic (str): topic of the event callback (function): the method to run when the event occours """ self.subscriptions.append({ "topic": topic, "callback": callback }) def send(self, topic, content): """ sends a message to all agents in the network Args: topic (str): topic of the message content (object): JSON compatible object to be transferred """ # get JSON representation of the message to be sent message = Message(self.agent, topic, content) json_message = message.dumps() # send message to every agent in the network if self.connection_status: for ip in self.scan_ips_from_network(): requests.post("http://" + ip, data=json_message) requests.post("http://" + self.local_ip, data=json_message) def trigger(self, message): """ triggers every callback with the topic transmitted by the message NOTE if a callback function is triggered the function is provided with the transmitted message Args: message (str): JSON encoded message that triggered an event Raises: TypeError: when trying to call a non-callable callback """ message = Message.loads(message) # check every subscription and trigger the callback if the topics match for subscription in self.subscriptions: if subscription["topic"] == message.topic: try: subscription["callback"](message) except TypeError: raise TypeError("A triggered callback was not callable.") class Message: """ helper class wrapping a transferrable message """ def __init__(self, sender, topic, content, timestamp = time.time()): """ initializes the message Args: sender (Agent or str): sending agent or the agent's ID topic (str): concern of the message content (object): JSON compatible object to be transmited via the message timestamp (float): UNIX timestamp of the creation of the message """ if type(sender).__name__ == "Agent": sender = sender.id self.sender = sender self.topic = topic self.content = content self.timestamp = timestamp # assert that the timestamp is valid assert self.timestamp <= time.time(), "invalid future timestamp" def __repr__(self): return f"Message - #{self.sender} : {self.topic} : {self.content} ({self.timestamp})" def dumps(self): """ creates a JSON representation of the message Returns: str: JSON string containing the encoded information about the message """ return json.dumps({ "sender": self.sender, "topic": self.topic, "content": self.content, "timestamp": self.timestamp }) @staticmethod def loads(json_data): """ creates the Message object of its JSON representation Args: json_data (str): JSON representation of the message Returns: Message: Message object correpsonding to the JSON string Raises: TypeError: in case the content is not JSON serializable KeyError: in case the JSON message is missing a required attribute """ try: # extract data from JSON string if it has been provided data = json.loads(json_data) sender = data["sender"] topic = data["topic"] content = data["content"] timestamp = data["timestamp"] return Message(sender, topic, content, timestamp) except json.JSONDecodeError: raise TypeError("Tried to decode a message with an invalid JSON representation.") except KeyError: raise KeyError("Tried to decode a message with a missing attribute.") @Singleton class ActionManager: """ coordinates the interactive behaviour of multiple agents by determining which agent is allowed to execute which action at what time """ WAIT_ACT = 1 WAIT_SEND_GLOBAL = 0.5 WAIT_FIRST_IN_QUEUE = WAIT_SEND_GLOBAL * 4 WAIT_CHECK_PERMISSION = 0.5 def __init__(self): """ initializes the ActionManager by initializing its attributes and starting continuous tasks """ self.agent = vehicle.Agent.instance() self.global_action = None self.local_actions = [] self.global_verification = False self.communication = Communication.instance() self.formation = Formation.instance() self.driver = vehicle.Driver.instance() # maps modes to the driver methods that are proactive and # require coordniation to execute the corresponding actions self.PROACTIVAE_ACTIONS = { const.Mode.AUTONOMOUS: self.driver.follow_road, const.Mode.ENTER: self.driver.enter_parking_lot, const.Mode.LEAVE: self.driver.leave_parking_lot, const.Mode.MANUAL: self.driver.manual_driving } # ensure that the functions for executing an action exist for mode, action in self.PROACTIVAE_ACTIONS.items(): assert callable(action), f"driver cannot execute action {action} for {mode}" # start executing continuous tasks self.update() self.check_global_permission() self.act() # subscribe to completion and global action messages self.communication.subscribe(const.Topic.GLOBAL_ACTION_COMPLETED, self.receive_completion) self.communication.subscribe(const.Topic.GLOBAL_ACTION_ACTIVE, self.receive_global_action) def __iter__(self): yield from self.local_actions @threaded def update(self): """ continuously checks if the agent is currently taking an action and in this case sends it to every agent in the network """ while True: # share current global action if it is the agent's current action if self.global_action is not None: if self.global_action.is_owner(self.agent): self.send_global_action() time.sleep(self.WAIT_SEND_GLOBAL) @threaded def check_global_permission(self): """ continuously checks if the agent is allowed to make its local agent it intents to take global and in this case executes this action """ while True: local_action = self.local_actions[0] if len(self.local_actions) > 0 else None # skip the loop if the local action cannot be made global if local_action is None: # check if there is a local action time.sleep(self.WAIT_CHECK_PERMISSION) continue if self.global_action is not None: # check if there is already a global action time.sleep(self.WAIT_CHECK_PERMISSION) continue if local_action.mode not in self.PROACTIVAE_ACTIONS: # check if the action does not require coordination time.sleep(self.WAIT_CHECK_PERMISSION) continue # share the agent's action and wait in order to determine whether it is actually the foremost self.global_action = local_action time.sleep(self.WAIT_FIRST_IN_QUEUE) if self.global_action.is_owner(self.agent): self.global_verification = True self.local_actions.pop(0) @threaded def act(self): """ continuously determines which actions to execute and executes them by addressing the driver Raises: KeyError: when trying to execute a non-proactive action in a proactive context """ # continuously determine and take allowed actions while True: # special cases : searching a parking lot and autonomous driving does not require coordination if len(self.local_actions) > 0: local_action = self.local_actions[0] if local_action == const.Mode.SEARCH: self.driver.search_parking_lot() self.local_actions.pop(0) continue if local_action == const.Mode.AUTONOMOUS: self.driver.search_parking_lot() self.local_actions.pop(0) continue if self.global_verification: # permission for every action try: self.PROACTIVAE_ACTIONS[self.global_action.mode]() self.global_verification = False self.send_completion() except KeyError: raise KeyError("Tried to execute an action that is not declared to be proactive in a proactive context.") elif self.global_action is not None: # autonomous reaction to the global action # ensure that an agent does not react to an action it is # trying to execute itself while waiting for permission if self.global_action.is_owner(self.agent): time.sleep(self.WAIT_ACT) continue # determine which reaction corresponds to the current global action # most global actions require other agents not to act at all if self.global_action.mode == const.Mode.LEAVE: # create space self.driver.create_space(self.global_action.agent) else: # do not act time.sleep(self.WAIT_ACT) continue def append(self, mode): """ appends a new action to the list of local action Args: mode (str): type of the action """ assert mode in const.Mode.ALL, "tried to append an unknown mode" action = Action(self.agent, mode) self.local_actions.append(action) def remove(self, mode): """ removes every action with a certain mode from the list of local actions NOTE this method does not effect global actions Args: mode (str): mode of actions to be removed """ self.local_actions = [action for action in self if action.mode != mode] def send_global_action(self): """ sends the current global action to every agent in the nework """ action_data = self.global_action.dumps() self.communication.send(const.Topic.GLOBAL_ACTION_ACTIVE, action_data) def receive_global_action(self, message): """ handles the receivement of the currently globally executed action Args: message (Message): message wrapping the information about the current global action """ action = Action.loads(message.content) self.global_action = Action.choose(self.global_action, action) def send_completion(self): """ informs every agent in the network that the global action the agent was taking has terminated """ self.global_action = None self.communication.send(const.Topic.GLOBAL_ACTION_COMPLETED, None) def receive_completion(self, message): """ handles the receivement of the information that the global action has terminated Args: message (Message): message wrapping the information """ if self.global_action is None: return if not self.global_action.is_owner(message.sender): return self.global_action = None class Action: """ helper class representing the state of an agent's behaviour """ def __init__(self, agent, mode, timestamp = time.time()): """ initializes the action Args: agent (Agent or str): agent taking the action or the agent's ID mode (str): type of the action timestamp (float): UNIX timestamp of the moment the action was registered """ if type(agent).__name__ == "Agent": agent = agent.id self.agent = agent self.mode = mode self.timestamp = timestamp # assert that the timestamp is valid assert self.timestamp <= time.time(), "invalid future timestamp" def __repr__(self): return f"Action[#{self.agent} : {self.mode} ({self.timestamp})]" def dumps(self): """ creates a JSON representation of the action Returns: str: JSON string containing the encoded information about the message """ return json.dumps({ "mode": self.mode, "agent": self.agent, "timestamp": self.timestamp }) def is_owner(self, agent): """ checks if the action is taken by a particular agent Args: agent (Agent or str): agent or agent ID to be checked Returns: bool: True if the agent takes the action - otherwhise False """ if type(agent).__name__ == "Agent": agent = agent.id return agent == self.agent @staticmethod def loads(json_data): """ creates the Action object of its JSON representation NOTE if an action attribute is not provided by the JSON string it will be set to None Args: json_data (str): JSON representation of the action Returns: Action: Action object correpsonding to the JSON string """ try: # extract data from JSON string if it has been provided data = json.loads(json_data) mode = data["mode"] if "mode" in data else None agent = data["agent"] if "agent" in data else None timestamp = data["timestamp"] if "timestamp" in data else None return Action(agent, mode, timestamp) except json.JSONDecodeError: raise TypeError("Tried to decode a message with an invalid JSON representation.") except KeyError: raise KeyError("Tried to decode a message with a missing attribute.") @staticmethod def choose(a, b): """ determines which one to choose out of two actions Args: a (Action): first action to be compared to the other b (Action): second action to be compared to the other Returns: Action: the foremost action out of the two - if the actions have the exact same timestamp the action with alphabetically lower agent ID is returned NOTE if one of the actions is None, the other action is returned in every case Raises: AttributeError: in case one of the object is missing a required attribute """ if a is None: return b if b is None: return a try: if a.timestamp < b.timestamp: return a if b.timestamp > a.timestamp: return b if a.agent < b.agent: return a return b except AttributeError: raise AttributeError("Tried to compare actions with missing attributes.") @Singleton class Formation: """ keeps track of the relative position of multiple agents within an agent network """ UPDATE_INTERVAL = 1 # seconds to wait after sending checking for being the first agent AWAIT_CONFIRMATION = 1 # seconds to wait for the confirmation of the receivement of a backpass def __init__(self): """ initializes the Formation and starts to update its agents """ self.agent = vehicle.Agent.instance() self.agents = [] self.tmp_agents = [] self.max_length = 0.0 self.tmp_max_length = 0.0 self.communication = Communication.instance() self.backpass_confirmed = False self.latest_update = 0.0 self.update() def __len__(self): return len(self.agents) def __repr__(self): agent_ids = "#" + ", #".join(self.agents) if len(self.agents) > 0 else "" return f"Formation[{agent_ids}] (max length: {self.max_length}cm)" def __iter__(self): yield from self.agents def calc_gap(self): """ calculates the minimal gap between two agents so that the longest vehicle can still leave the parking lot NOTE the calculated gap already includes the safety distance that must be kept in any case Returns: float: length of minimal gap """ number_of_agents = len(self) needed_space = self.max_length * const.Driving.LEAVE_PARKING_LOT_PROPORTION needed_space += number_of_agents * const.Driving.SAFETY_DISTANCE try: return needed_space / number_of_agents + const.Driving.SAFETY_DISTANCE except ZeroDivisionError: return 0 @threaded def update(self): """ constantly updates the current formation by exchanging data with other agents within a network """ # subscribe to the relevant event topics self.communication.subscribe(const.Topic.FORMATION_BACKWARD_PASS, self.receive_backward_pass) self.communication.subscribe(const.Topic.FORMATION_FORWARD_PASS, self.receive_forward_pass) self.communication.subscribe(const.Topic.FORMATION_CONFIRMATION, self.receive_confirmation) with FrontAgentScanner.instance() as front_agent_scanner: while True: if front_agent_scanner.id is None: # start sending the formation backwards self.reset_tmp() self.append() self.send_backward_pass() time.sleep(self.UPDATE_INTERVAL) def send_backward_pass(self): """ sends an agent list backwards to other agents within the network """ # send the message in a separate thread thread = Thread(target=lambda: self.communication.send(const.Topic.FORMATION_BACKWARD_PASS, self.data())) thread.start() time.sleep(self.AWAIT_CONFIRMATION) # wait for a possible receiver to confirm the backpass if not self.backpass_confirmed: # last in line -> formation complete -> send forwards self.backpass_confirmed = False self.accept_tmp() self.send_forward_pass() def receive_backward_pass(self, message): """ callback function handling a formation that was sent backwards Args: message (Message): message containing the formation's agent list """ if message.timestamp <= self.latest_update: return # check if the formation was sent to this specific agent with FrontAgentScanner.instance() as front_agent_scanner: if front_agent_scanner.id == message.sender: self.latest_update = message.timestamp self.send_confirmation(message.sender) # update the delivered formation and send it further backwards self.tmp_agents = message.content["agents"] self.tmp_max_length = message.content["longest"] self.append() self.send_backward_pass() def send_forward_pass(self): """ sends an agent list forwards to other agents within the network """ # send the message in a separate thread thread = Thread(target=lambda: self.communication.send(const.Topic.FORMATION_FORWARD_PASS, self.data())) thread.start() def receive_forward_pass(self, message): """ callback function handling a formation that was sent forwards as valid formation Args: message (Message): message containing the formation's agent list """ agents = message.content["agents"] max_length = message.content["longest"] # ensure that the formation contains the agent and that it is up to date if self.agent.id not in message.content["agents"]: return if message.timestamp <= self.latest_update: return self.latest_update = message.timestamp self.tmp_agents = agents self.tmp_max_length = max_length self.accept_tmp() def send_confirmation(self, receiver_id): """ sends a confirmation that a backpass was received Args: receiver_id (str): ID of the agent that sent the backpass """ # send the message in a separate thread thread = Thread(target=lambda: self.communication.send(const.Topic.FORMATION_CONFIRMATION, receiver_id)) thread.start() def receive_confirmation(self, message): """ callback function handling a message confirming that a backpass was received by the addressee Args: message (Message): message confirming a backpass """ self.backpass_confirmed = message.content == self.agent.id def append(self): """ appends the agent to the temporary formation """ self.tmp_agents.append(self.agent.id) if self.tmp_max_length < self.agent.length: self.tmp_max_length = self.agent.length def accept_tmp(self): """ makes the temporary formation the current 'official' formation and resets the temporary """ self.agents = [agent for agent in self.tmp_agents] self.max_length = self.tmp_max_length self.reset_tmp() def data(self): """ creates a dictionary of the current temporary formation to be sent within the agent network Returns: dict: current temporry formation data (agent IDs and length of the longest vehicle) """ return { "agents": self.tmp_agents, "longest": self.tmp_max_length, } def reset_tmp(self): """ sets the temporary formation to its default values """ self.tmp_agents = [] self.tmp_max_length = 0.0 def comes_before(self, a, b): """ determines whether an agent is located further ahead within the formation Args: a (Agent or str): agent or agent ID to check if it is located ahead of b b (Agent or str): agent or agent ID to check if it is located behind a Returns: bool: True if a is located ahead of b - otherwhise False NOTE if neither of the both agents exist in the formation False is returned """ if type(a).__name__ == "Agent": a = a.id if type(b).__name__ == "Agent": b = b.id for agent in self.agents: if agent in [a, b]: return agent == a return False def distance(self, a, b): """ determines the distance distance between two agents in a formation in terms of how many vehicles stand between them Args: a (Agent or str): agent or agent ID to determine the distance to b b (Agent or str): agent or agent ID to determine the distance to a Returns: int: number of vehicles between a and b Raises: ValueError: if at least one of the given agents is not part of the formation """ if type(a).__name__ == "Agent": a = a.id if type(b).__name__ == "Agent": b = b.id return abs(self.agents.index(a) - self.agents.index(b)) - 1
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,005
lukashaverbeck/parknet
refs/heads/master
/scripts/stepper.py
# This script rotates the stepper motor accordingly to user input. # # version: 1.0 (31.12.2019) import sys from time import sleep import RPi.GPIO as GPIO GPIO.setwarnings(False) # disable GPIO warnings for console convenience GPIO.setmode(GPIO.BCM) # GPIO instance works in broadcom-memory mode GPIO.setup(20, GPIO.OUT) # direction pin is an output GPIO.setup(21, GPIO.OUT) # step pin is an output GPIO.setup(26, GPIO.OUT) # sleep pin is an output def menu(): """ main menu lets user chose driving mode """ mode = input("Enter 'd' for distance mode and 'r' for rotation mode ('q' to exit): ") if mode == "q": sys.exit() # stop script when the q key is pressed direction_parameter() # set direction if mode == "r": rps = input("Please type in your rps: ") step_movement(rps) # activate driving with stepper parameters elif mode == "d": distance_movement() # activate driving with distance parameters menu() # if there is no valid user input return to main menu def stepper_sleep(status): """ activates and deactivates controller in order to save energy Args: status (str): motor status (sleep or active) """ if status == "sleep": GPIO.output(26, GPIO.LOW) # put controller to sleep mode if status == "active": GPIO.output(26, GPIO.HIGH) # activate controller def calculate_delay(rps): """ calculates delay time used between steps according to velocity Args: rps (float): rounds per second Returns: float: calculated delay time """ delay = (1 / (200 * float(rps))) / 2 # delay based on rounds per second return delay def calculate_steps(distance): """ calculates steps from distance Args: distance (float): distance in cm to be converted to steps Returns: int: corresponding number of steps """ steps = distance / 0.00865 # one step is about 0.00865cm return int(steps) def calculate_rps(velocity, distance): rps = velocity / 1.729 return int(rps) def direction_parameter(): """ sets direction of stepper """ direction = input("Type 'f' for forward and 'r' for reverse: ") if direction == "f": GPIO.output(20, 0) # direction is set to clockwise elif direction == "r": GPIO.output(20, 1) # direction is set to counterclockwise def rotation_parameter(): """ takes rotation parameter from user """ rotations = input("Type in your number of rotations ('m' for menu): ") if rotations == "m": menu() # return to main menu steps = int(rotations) * 200 # steps calculated from rotation number(one rotation is 200 steps) return steps def distance_parameter(): """ takes distance parameter from user """ distance = input("Type in the distance[cm] you want to drive ('m' for menu): ") if distance == "m": menu() # return to main menu return distance def velocity_parameter(): """ takes velocity from user """ velocity = input("Type the velocity[cm/s] you want to drive with: ") return velocity def step_movement(rps): """ moves stepper provided number of steps with provided rps """ delay = calculate_delay(rps) steps = rotation_parameter() # get number of steps from user move(delay, steps) # move stepper step_movement(rps) # ask for rotation parameter and move again def distance_movement(): """ move stepper provided distance with provided velocity """ distance = distance_parameter() # get distance from user velocity = velocity_parameter() # get velocity from user rps = calculate_rps(float(velocity), distance) # convert velocity to rps delay = calculate_delay(rps) # calculate delay steps = calculate_steps(float(distance)) # convert distance to steps move(delay, steps) # move stepper distance_movement() # ask for new parameters and move again def move(delay, steps): """ moves stepper """ stepper_sleep("active") # activate stepper for i in range(steps): # loop turns stepper one round in two seconds GPIO.output(21, GPIO.HIGH) # make on step sleep(delay) GPIO.output(21, GPIO.LOW) # turn step pin low to prepare next step sleep(delay) stepper_sleep("sleep") # put stepper to sleep menu() # start main menu when script is started
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,006
lukashaverbeck/parknet
refs/heads/master
/scripts/init_esc.py
# This script initializes the ESC built into a picar with an activation pulse. # Run this script before using any other PWM related ESC controls. # # version: 1.0 (30.12.2019) import time import Adafruit_PCA9685 pwm = Adafruit_PCA9685.PCA9685(address=0x40, busnum=1) # assign I2C-address and busnumber pwm.set_pwm_freq(50) init_pwm = 340 # digital treble zero position print("Please make sure to disconnect your ESC from the battery.") input = input("Press Enter to start initialization process: ") print("\nTreble-Zero pulse is send to ESC-port ...", end ="") pwm.set_pwm(1, 0, init_pwm) # sending activation frequency print("done!") print("Now power on your ESC and wait until you hear it beeping.") time.sleep(15) # time to turn on ESC
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,007
lukashaverbeck/parknet
refs/heads/master
/util.py
# This module contains utility classes and functions that may be used # throughout the whole project and cannot be assigned to single modules. # # version: 1.0 (02.01.2019) from threading import Thread class Singleton: """ helper class ensuring that classes decorated with it can only be instantiated one single time so that the same object can be accessed at multiple locations in the code without having to pass it around """ def __init__(self, decorated): """ initializes the Singleton """ self.object = None self.decorated = decorated def instance(self, *args, **kwargs): """ gets the same instance of a particluar class every time it is called returns: object: singleton of the class for which the method is called """ # check if an instance has to be created if self.object is None: self.object = self.decorated(*args, **kwargs) return self.object return self.object def __call__(self): """ ensures a singleton class not initialized directly Raises: TypeError: when trying to directly initialize a singleton class """ raise TypeError("Singletons must be accessed through `instance()`") def __instancecheck__(self, instance): return isinstance(instance, self.decorated) def threaded(func): """ allows to call a function in its own thread by decorating that function with @threaded NOTE this function does not start the thread directly but at the time the decorated function is called Args: func (function): function to be executed in its own thread Returns: function: decorated function """ def start_threaded_function(*args, **kwargs): thread = Thread(target=lambda: func(*args, **kwargs)) thread.start() return start_threaded_function
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,008
lukashaverbeck/parknet
refs/heads/master
/scripts/angle.py
# Script gets user input from commandline and sets this as pwm value. # Calculates the pwm value from an angle with a mathematical function. # # version: 1.0 (30.12.2019) from __future__ import division import time import Adafruit_PCA9685 pwm = Adafruit_PCA9685.PCA9685(address=0x40, busnum=1) # create PCA9685 object at I2C-port pwm.set_pwm_freq(50) def calc_angle(angle): """ calculates a pwm value for a given angle Args: angle (float): angle to be converted to a pwm value Returns: float: corresponding pwm value """ return 2e-6 * angle ** 4 + 2e-6 * angle ** 3 + .005766 * angle ** 2 - 1.81281 * angle + 324.149 while True: pwm_val = input("Please enter your angle: ") # get user input from commandline (as string) if pwm_val == "q": break # stop script when the q key is pressed pwm_calc = calc_angle(int(pwm_val)) # get pwm value for user input pwm.set_pwm(0, 0, int(pwm_calc)) # cast pwm value to integer and set it on pwm object print(f"pwm value is: {pwm_calc}") # echo user input
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,009
lukashaverbeck/parknet
refs/heads/master
/constants.py
# This module is a collection of global constants divided into multiple classes # that represent a separate concern. # # version: 1.0 (28.12.2019) class Connection: WLAN_PASSWORD = "Hallo1234" class Driving: CAUTIOUS_VELOCITY = 8 # cm/s STOP_VELOCITY = 0 # cm/s MAX_VELOCITY = 9 # cm/s MIN_VELOCITY = -9 # cm/s MIN_STEERING_ANGLE = -25 # ° MAX_STEERING_ANGLE = 25 # ° NEUTRAL_STEERING_ANGLE = 0 # ° SAFETY_DISTANCE = 3 # cm LEAVE_PARKING_LOT_PROPORTION = 0.4 class EchoPin: FRONT = 4 RIGHT = 17 BACK = 22 BACK_ANGLED = 27 class Mode: ENTER = "parking/enter" LEAVE = "parking/leave" SEARCH = "parking/search" STANDBY = "parking/standby" AUTONOMOUS = "drive/follow-road" MANUAL = "drive/manual" MOVE_UP = "react/move-up" MOVE_BACK = "react/move-back" ALL = [ENTER, LEAVE, SEARCH, STANDBY, AUTONOMOUS, MANUAL, MOVE_UP, MOVE_BACK] DEFAULT = MANUAL class Stepper: DIRECTION_PIN = 20 STEP_PIN = 21 SLEEP_PIN = 26 class Storage: ATTRIBUTES = "./attributes.json" DATA = "./data/" CHECKPOINTS = "./checkpoints/" DEFAULT_STEERING_MODEL = "./model.h5" class Topic: GLOBAL_ACTION_ACTIVE = "action/active-global" GLOBAL_ACTION_COMPLETED = "action/completed-global" FORMATION_CONFIRMATION = "formation/confirm-backward-pass" FORMATION_FORWARD_PASS = "formation/forward-pass" FORMATION_BACKWARD_PASS = "formation/backward-pass" class TriggerPin: FRONT = 18 RIGHT = 23 BACK = 25 BACK_ANGLED = 24
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,010
lukashaverbeck/parknet
refs/heads/master
/vehicle.py
# This module contains entities that are closely related to the vehicle itself. # It defines Agents which are a general representation of an acting protagonist and # a Driver controling the movement of the vehicle. Therefore a DriveThread applying this # behaviour to the hardware and a RecorderThread handling the collecting of driving data # is defined. # # version: 1.0 (4.1.2020) # # TODO implement Driver.leave_parking_lot # TODO test everything # TODO compensate for lopsided driving with a general approach import os import csv import json import time from threading import Thread from datetime import datetime import numpy as np import RPi.GPIO as GPIO import Adafruit_PCA9685 import interaction import constants as const from ai import SteeringNet from util import Singleton, threaded from ui.interface import WebInterface from vision import Camera, SensorManager from connection import AutoConnector, get_local_ip assert os.path.isfile(const.Storage.ATTRIBUTES), "required attributes file missing" assert os.path.isdir(const.Storage.DATA), "required data directory missing" @Singleton class Agent: """ general representation of an acting protagonist """ def __init__(self): """ initializes an agent by reading its attributes from the according file Raises: AssertionError: in case the attributes file is missing """ try: # read attributes from attributes file with open(const.Storage.ATTRIBUTES) as attributes_file: # read the file and parse it to JSON data json_data = attributes_file.read() attributes = json.loads(json_data) # set attributes self.id = str(attributes["id"]) self.length = float(attributes["length"]) self.width = float(attributes["width"]) except OSError: raise OSError("The attributes file could not be opened.") def __repr__(self): return f"Agent #{self.id} [length: {self.length}cm ; width: {self.width}]" @Singleton class Driver: """ controling the movement of the vehicle """ def __init__(self): """ initializes the Driver """ self.drive_thread = None self.recorder_thread = None self.velocity = const.Driving.STOP_VELOCITY self.angle = const.Driving.NEUTRAL_STEERING_ANGLE self.distance = 0 self.agent = Agent.instance() self.formation = interaction.Formation.instance() self.sensor_manager = SensorManager.instance() def start_driving(self): """ starts the thread that moves the vehicle """ self.stop_driving() self.drive_thread = DriveThread() self.drive_thread.start() def stop_driving(self): """ stops and deletes the thread that moves the vehicle it also sets the velocity and steering angle to 0 """ self.velocity = const.Driving.STOP_VELOCITY self.angle = const.Driving.NEUTRAL_STEERING_ANGLE if self.drive_thread is not None: self.drive_thread.stop() self.drive_thread = None def accelerate(self, velocity_diff): """ changes the velocity of the vehicle NOTE this method does not move the vehicle but instead changes the internal velocity variable Args: velocity_diff (float): desired velocity change Raises: TypeError: when trying to change the velocity by a non-numerical value """ try: velocity = self.velocity + velocity_diff # ensure that the velocity stays within the limits if velocity > const.Driving.MAX_VELOCITY: velocity = const.Driving.MAX_VELOCITY if velocity < const.Driving.MIN_VELOCITY: velocity = const.Driving.MIN_VELOCITY self.velocity = velocity except TypeError: raise TypeError("Tried to change the velocity by a non-numerical value.") def steer(self, angle_diff): """ changes the steering angle of the vehicle NOTE this method does not move the vehicle's steering axle but instead changes the steering internal angle variable Args: angle_diff (float): desired angle change Raises: TypeError: when trying to change the steering angle by a non-numerical value """ try: angle = self.angle + angle_diff # ensure that the angle stays within the limits if angle > const.Driving.MAX_STEERING_ANGLE: angle = const.Driving.MAX_STEERING_ANGLE elif angle < const.Driving.MIN_STEERING_ANGLE: angle = const.Driving.MIN_STEERING_ANGLE self.angle = angle except TypeError: raise TypeError("Tried to change the steering angle by a non-numerical value.") def enter_parking_lot(self): """ parallel parking from a provided starting position NOTE the method assumes that the vehicle stands parallel to the front vehicle or obstacle in the correct starting position """ self.start_driving() time.sleep(2) # drive back into gap with strong angle self.angle = 25 self.velocity = -8 self.drive_thread.driven_distance = 0 self.distance = 35 while self.drive_thread.driven_distance < self.distance: time.sleep(1) # drive back until close to wall self.angle = 0 self.velocity = -8 self.distance = 150 self.drive_thread.driven_distance = 0 while self.sensor_manager.rear > 60: time.sleep(0.2) # get into straight position self.angle = -25 self.velocity = -8 self.distance = 40 self.drive_thread.driven_distance = 0 while self.drive_thread.driven_distance < self.distance: time.sleep(1) # drive backwards up to end of gap self.angle = 0 self.velocity = -8 self.drive_thread.driven_distance = 0 while self.sensor_manager.rear >= 10: print(self.sensor_manager.rear) time.sleep(0.5) self.stop_driving() def leave_parking_lot(self): """ steers the vehicle out of the parking lot TODO implement method """ print("leave parking lot") time.sleep(5) def search_parking_lot(self): """ drives forward while identifying possible parking lots and evaluating whether such a parking lot would fit the vehicle's dimensions for parallel parking NOTE after identifying a parking lot, the vehicle drives further until it reaches the start of the parking lot TODO compensate for lopsided driving with a more general approach """ self.start_driving() self.velocity = 8 self.distance = 250 # maximum searching distance self.angle = 1.5 # TODO self.drive_thread.reset() vacant_distance = 0 while self.drive_thread.driven_distance < self.distance: time.sleep(0.1) if self.sensor_manager.right > 25: vacant_distance += 1 else: vacant_distance = 0 if vacant_distance >= 35: while self.sensor_manager.right > 25: time.sleep(0.1) distance_right = self.sensor_manager.right if 14 <= distance_right <= 18: self.angle = 0 self.distance = 35 self.drive_thread.reset() while self.drive_thread.driven_distance < self.distance: time.sleep(0.1) elif distance_right > 18: self.adjust_starting_position("left") elif distance_right < 14: self.adjust_starting_position("right") break self.stop_driving() def adjust_starting_position(self, direction): """ ensures that the vehicle enters a parking lot from a reasonable starting position by adjusting the space on the right side of the vehicle Args: direction (string or int): direction in which to adjust the space (either "left" / 1 or "right" / 0) """ direction = 1 if direction in ["left", 1] else -1 self.angle = direction * 25 self.distance = 12 self.drive_thread.reset() while self.drive_thread.driven_distance < self.distance: time.sleep(0.1) self.angle = 0 self.distance = 12 self.drive_thread.reset() while self.drive_thread.driven_distance < self.distance: time.sleep(0.1) self.angle = direction * -25 self.distance = 12 self.drive_thread.reset() while self.drive_thread.driven_distance < self.distance: time.sleep(0.1) def follow_road(self): """ drives autonomously without explicit instructions by propagating the camera input through a convolutional neural network that predicts a steering angle NOTE this mode has no particular destination and therfore does not terminate unless the driver is stopped explicitly """ steering_net = SteeringNet() steering_net.load(const.Storage.DEFAULT_STEERING_MODEL) self.start_driving() with Camera.instance() as camera: while self.recorder_thread is not None: image = camera.image predicted_angle = steering_net.predict(image, self.angle) self.angle = predicted_angle time.sleep(0.25) self.stop_driving() def create_space(self, agent_id): """ creates space for an agent leaving the parking lot by moving up in the according direction until the agent has left the formation Args: agent_id (str): ID of the agent leaving the formation """ if agent_id not in self.formation: return # determine direction to drive in direction = -1 if self.formation.comes_before(self.agent, agent_id) else 1 self.velocity = direction * const.Driving.CAUTIOUS_VELOCITY # the distance between the vehicles corrsponds to the # seconds to wait after the vehicle left the parking lot wait_time = self.formation.distance(self.agent, agent_id) self.distance = 0 self.start_driving() update_interval = 0.5 # move up / back to create space until the vehicle left the parking lot while agent_id in self.formation: # TODO add working condition self.distance += abs(self.velocity * update_interval) time.sleep(update_interval) self.distance = 0 # wait for vehicles that were located nearer to the leaving agent to move # and then close the gap gap = self.formation.calc_gap() time.sleep(wait_time) if direction == 1: self.velocity = -1 * const.Driving.CAUTIOUS_VELOCITY else: self.velocity = const.Driving.CAUTIOUS_VELOCITY while self.sensor_manager.front < gap: self.distance += abs(self.velocity * update_interval) time.sleep(update_interval) self.stop_driving() def move_up(self): """ drives as close to the front vehicle or obstacle as possible for the current vehicle formation """ # slowly drive backwards self.velocity = const.Driving.MAX_VELOCITY self.angle = const.Driving.NEUTRAL_STEERING_ANGLE # drive as long there is enough space to the next vehicle or obstacle gap = self.formation.calc_gap() self.start_driving() while self.sensor_manager.front > gap: continue self.stop_driving() def move_back(self): """ drives as close to the rear vehicle or obstacle as possible for the current vehicle formation """ # slowly drive backwards self.velocity = -1 * const.Driving.CAUTIOUS_VELOCITY self.angle = const.Driving.NEUTRAL_STEERING_ANGLE # drive as long there is enough space to the next vehicle or obstacle gap = self.formation.calc_gap() self.start_driving() while self.sensor_manager.rear > gap: continue self.stop_driving() def manual_driving(self): """ allows the user to steer manually and therefore solely starts driving without specifing the concrete movement """ self.start_driving() def start_recording(self): """ starts a thread that saves a continuos stream image of the current camera input and logs the corresponding steering angle and velocity """ self.stop_recording() self.recorder_thread = RecorderThread() self.recorder_thread.start() def stop_recording(self): """ stops the thread that captures the data """ if self.recorder_thread is not None: self.recorder_thread.stop() self.recorder_thread = None class RecorderThread(Thread): """ thread that captures the current video input, saves it to memory and creates a log of the corresponding steering angle and velocity """ CAPTURE_INTERVAL = 0.25 # seconds to wait after saving a data point def __init__(self): """ initializes the thread without starting to capture the data """ super().__init__() self.active = True self.driver = Driver.instance() self.camera = Camera.instance() # define directories and file paths date_str = datetime.today().strftime("%Y-%m-%d-%H-%M-%S") self.log_dir = f"{const.Storage.DATA}/{date_str}" self.img_dir = f"{self.log_dir}/img/" self.log_path = f"{self.log_dir}/log.csv" self.img_extension = "npy" # ensure that the necessary directories exist os.mkdir(self.log_dir) os.mkdir(self.img_dir) assert os.path.isdir(self.log_dir), "data directory could not be created" assert os.path.isdir(self.img_dir), "image directory could not be created" def run(self): """ starts capturing the data (image, angle, previous angle) Raises: OSError: in case the log file cannot be created OSError: in case the log file cannot be opened after being created """ with Camera.instance() as camera: try: # create log file and write headers with open(self.log_path, "w+") as log: writer = csv.writer(log) writer.writerow(["image", "angle", "previous_angle"]) except OSError: raise OSError("The log file could not be created.") previous_angle = 0.0 while self.active: if camera.image is None: continue # skip loop if no image provided # save image img_filename = datetime.today().strftime("%H-%M-%S-%f") + "." + self.img_extension np.save(self.img_dir + img_filename, camera.image) try: # write data to csv file with open(self.log_path, "a") as log: writer = csv.writer(log) angle = str(round(self.driver.angle, 3)) previous_angle = str(previous_angle) writer.writerow([img_filename, angle, previous_angle]) except OSError: raise OSError("The log file could not be opened.") previous_angle = angle # update previous angle for next loop time.sleep(self.CAPTURE_INTERVAL) def stop(self): """ stops capturing the data """ self.active = False class DriveThread(Thread): """ thread that moves the vehicle """ DISTANCE_PER_STEP = 0.0072 def __init__(self): """ initializes the thread without starting to move the vehicle """ super().__init__() self.active = True self.driver = Driver.instance() self.sensor_manager = SensorManager.instance() self.pwm = Adafruit_PCA9685.PCA9685(address=0x40, busnum=1) # create PCA9685-object at I2C-port self.pwm.set_pwm_freq(50) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.OUT) GPIO.setup(21, GPIO.OUT) GPIO.setup(26, GPIO.OUT) self.driven_distance = 0 def run(self): """ other than Driver.accelerate() or Driver.steer(), this method indeedly moves the vehicle according to the driver's steering angle and velocity by starting the threads that address the vehicle's hardware """ self.steer() self.drive() @threaded def drive(self): self.change_stepper_status(True) while self.active: velocity = self.driver.velocity if velocity < 0: GPIO.output(20, 0) elif velocity > 0: GPIO.output(20, 1) delay = self.calculate_delay(abs(velocity)) # ensures that there is enough space in front of or behind the vehicle by skipping the current # driving loop if the minimal front distance is assumed to be exceeded front_distance = self.sensor_manager.front rear_distance = self.sensor_manager.rear distance = front_distance if velocity > 0 else rear_distance predicted_distance = distance - self.DISTANCE_PER_STEP if predicted_distance < const.Driving.SAFETY_DISTANCE: continue if delay > 0: GPIO.output(21, GPIO.HIGH) time.sleep(delay) GPIO.output(21, GPIO.LOW) time.sleep(delay) self.driven_distance += self.DISTANCE_PER_STEP self.change_stepper_status(False) def calculate_delay(self, velocity): """calculates delay time used between steps according to velocity""" if velocity > 0: rps = velocity / 1.444 delay = (1 / (200 * float(rps))) / 2 return delay else: return 0 def change_stepper_status(self, status): """activates and deactivates controller in order to save energy""" if status: GPIO.output(26, GPIO.HIGH) else: GPIO.output(26, GPIO.LOW) def reset(self): self.driven_distance = 0 @threaded def steer(self): """calculates and sets steering angle""" while self.active: angle = self.driver.angle steering_pwm_calc = self.angle_to_pmw(angle) self.pwm.set_pwm(0, 0, steering_pwm_calc) def angle_to_pmw(self, angle): """ converts the current steering angle to a pulse width modulation value that can be processed by the hardware Args: angle (int): angle in degrees to be converted to pwm Returns: int: pwm value for the steering angle """ #val = 2e-6 * angle ** 4 + 2e-6 * angle ** 3 + 0.005766 * angle ** 2 - 1.81281 * angle + 324.149 val = -2.82492*angle+406 return int(round(val, 0)) def stop(self): """ stops the movement of the vehicle TODO implement method """ self.active = False angle_pwm = self.angle_to_pmw(const.Driving.NEUTRAL_STEERING_ANGLE) self.pwm.set_pwm(0, 0, angle_pwm) @threaded def start_interface(): """checks for new ip addresses of picar and starts interface-webserver on new ip""" last_ip = None while True: time.sleep(5) current_ips = get_local_ip().split() # check if a network address was found if len(current_ips) == 0: communication = interaction.Communication.instance() communication.lost_connection() continue elif len(current_ips) == 1: if not current_ips[0][:3] == "192": communication = interaction.Communication.instance() communication.lost_connection() continue else: current_ip = current_ips[0] else: if current_ips[0][:3] == "192": current_ip = current_ips[0] else: current_ip = current_ips[1] # restar webservers if the IP is new if not current_ip == last_ip: last_ip = current_ip print(f"Found new ip: {current_ip}") agent = Agent.instance() communication = interaction.Communication.instance() communication.set_local_ip(current_ip) driver = Driver.instance() sensor_manager = SensorManager.instance() action_manager = interaction.ActionManager.instance() interface = WebInterface(agent, driver, sensor_manager, action_manager) interface.start(current_ip) if __name__ == "__main__": interaction.Communication.instance() start_interface()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,011
lukashaverbeck/parknet
refs/heads/master
/ai.py
# This module contains entities that provide the necessary functionality for the behaviour of a # vehicle in complex situations that cannot be described by a set of simple rules. # Therefore it defines a neural that takes in an image and the current steering angle # and predicts a new steering angle for autnonomous driving under various traffic conditions. # It also implements necessary utility functions (e.g. data preparation, augmentation, training, # testing etc.) # # version: 1.0 (31.12.2019) # # TODO midterm motion planning # TODO image segmentation for identifying pedestrians, traffic signs, traffic lights etc. import os import json import math import random from datetime import datetime import numpy as np import pandas as pd import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers from tensorflow.keras.callbacks import ModelCheckpoint import constants as const KEY_IMG = "image" KEY_ANGLE = "angle" KEY_PREVIOUS = "previous_angle" INPUT_SHAPE = (100, 200, 3) def calc_steps(data_path, batch_size): """ calculates the number of steps per epoch Args: data_path (str): path to the file storing the data batch_size (int): number of samples being considered per iteration Returns: int: number of steps """ with open(data_path, "r") as data_file: lines = data_file.readlines() num_lines = len([l for l in lines if l.strip(" \n") != ""]) return math.ceil(num_lines / batch_size) def save_history(history, version): """ saves the training progress to disk by storing it in a JSON file Args: history (keras.callbacks.History): training history providing information about the training progress version (int or float or string): name of the training """ with open(f"./v{version}_mae.json", mode="w+") as log: data = [float(x) for x in history.history["mae"]] json.dump(data, log, ensure_ascii=True, indent=4) with open(f"./{version}_val_mae.json", mode="w+") as log: data = [float(x) for x in history.history["val_mae"]] json.dump(data, log, ensure_ascii=True, indent=4) def disply_image(image): """ shows an image on screen as a pyplot figure Args: image numpy.ndarray: numpy representation of an image """ import matplotlib.pyplot as pyplot pyplot.figure() pyplot.imshow(image) pyplot.show() def load_image(image_path): """ creates a numpy array of an image that is being stored on disk Args: image_path (str): path to a .jpg, .jpeg or .numpy image Returns: numpy.ndarray: numpy representation of the image Raises: TypeError: when trying to load an image that is not a JPEG or NPY file """ extension = image_path.split(".")[-1] if extension == "npy": image = np.load(image_path) elif extension in ["jpg", "jpeg"]: from PIL import Image image = Image.open(image_path) image.load() image = np.asarray(image) else: raise TypeError("Tried to load an image with an invalid extension.") return image def center_crop_image(image, target_shape): """ cuts out a part of the center of an image Args: image (numpy.ndarray): numpy representation of the image target_shape (tuple): desired dimensions of the cropped image part Returns: numpy.ndarray: numpy representation of the cropped center of the image """ # ensure that the image is big enough assert image.shape[0] >= target_shape[0], "image does not match input dimensions" assert image.shape[1] >= target_shape[1], "image does not match input dimensions" assert image.shape[2] == target_shape[2], "image does not match input dimensions" # calculate corner coordinates where to start cropping corner_x = int((image.shape[1] - target_shape[1]) / 2) corner_y = int((image.shape[0] - target_shape[0]) / 2) image = image[corner_y : corner_y + target_shape[0], corner_x : corner_x + target_shape[1]] # crop image return image def shift_image(image, x_max, y_max): """ translates the content of an image randomly in x and y direction NOTE overflowing pixels are relocated to the other side of the image Args: image (numpy.ndarray): numpy representation of the image x_max (int): maximal translation in x direction y_max (int): maximal translation in y direction """ # determine translation expanse and direction randomly shift_x = int(round(random.uniform(-x_max, x_max), 0)) shift_y = int(round(random.uniform(-y_max, y_max), 0)) # shift image image = np.roll(image, shift_x, axis=1) image = np.roll(image, shift_y, axis=0) return image def add_noise_to_image(image): """ adds random noise to an image Args: image (numpy.ndarray): numpy representation of the image Returns: numpy.ndarray: numpy representation of the noised image """ # determine additional pixel values and apply them to the image noise = np.random.randint(2, size=image.shape) - np.random.randint(2, size=image.shape) image = image + noise return image class SteeringData: """ wrapper class for data used for trainign the `SteeringModel` """ def __init__(self, image_directory, csv_path, batch_size, is_training): """ initializes the `SteeringData` Args: image_directory (str): path to the directory storing the training / testing images csv_path (str): path to the csv file storing the data points batch_size (int): number of data points considered per batch is_training (bool): boolean whether data is used for training (augment data in this case) """ self.image_directory = image_directory self.csv_path = csv_path self.batch_size = batch_size self.is_training = is_training if self.image_directory[-1] != "/": self.image_directory += "/" def generate(self): """ continously iterates over the data points Yields: tuple: input and target batches """ data = pd.read_csv(self.csv_path) # get data points from csv file while True: data = data.sample(frac=1) # randomly shuffle data points batch_image = [] batch_angle = [] batch_previous_angle = [] for image_name, previous_angle, angle in zip(data[KEY_IMG], data[KEY_PREVIOUS], data[KEY_ANGLE]): # prepare image, angle and previous angle image_path = self.image_directory + image_name image = load_image(image_path) image, angle, previous_angle = SteeringData.prepare_data(image, previous_angle, angle, self.is_training) # add data point to the corresponding batches batch_image.append(image) batch_angle.append(angle) batch_previous_angle.append(previous_angle) if len(batch_image) == self.batch_size: # ensure that the data is yielded in the required format target = np.array(batch_angle) inputs = { KEY_IMG: np.array(batch_image), KEY_PREVIOUS: np.array(batch_previous_angle) } yield inputs, target # clear batches batch_image = [] batch_angle = [] batch_previous_angle = [] @staticmethod def random_mirror_image(image, previous_angle, angle): """ flips an image and the corresponding angles with a 50% probability Args: image (numpy.ndarray): numpy representation of the image previous_angle (float): input angle angle (float): target angle Returns: tuple: image, input angle and target angle (might be flipped) """ if random.random() < 0.5: # mirror data in 50% of the cases image = np.flip(image, axis=1) previous_angle *= -1 angle *= -1 return image, previous_angle, angle @staticmethod def alter_previous_angle(previous_angle): """ slightly changes an angle randomly Args: previous_angle (float): input angle to be adjusted Returns: float: adjusted angle """ return np.random.uniform(0.85, 1.15) * previous_angle @staticmethod def prepare_data(image, previous_angle, angle=None, is_training=False): """ prepares data for training and testing Args: image (numpy.ndarray): numpy representation of an image previous_angle (float): input angle angle (float): target angle is_training (bool): boolean whether data is used for training (augment data in this case) """ image = center_crop_image(image, INPUT_SHAPE) # extract center if is_training: # augment data i training mode image = add_noise_to_image(image) image, previous_angle, angle = SteeringData.random_mirror_image(image, previous_angle, angle) image = shift_image(image, 6, 2) previous_angle = SteeringData.alter_previous_angle(previous_angle) # normalize and round angle values previous_angle = round(previous_angle, 5) if angle is not None: angle = round(angle, 5) image = image / 127.5 - 1 # normalize pixel values return image, previous_angle, angle class SteeringModel(keras.Model): """ deep learning model predicting steering angles based on an image input and the current steering angle NOTE this model is based on the architecture proposed by NVIDIA researchers for autnonomous driving """ def __init__(self): """ initializes the model by defining its layers """ super().__init__() regulizer = keras.regularizers.l2(0.001) # convolution layers and pooling layer self.conv1 = layers.Conv2D(filters=24, kernel_size=(5, 5), strides=(2, 2), kernel_regularizer=regulizer, activation="elu") self.conv2 = layers.Conv2D(filters=36, kernel_size=(5, 5), strides=(2, 2), kernel_regularizer=regulizer, activation="elu") self.conv3 = layers.Conv2D(filters=48, kernel_size=(5, 5), strides=(2, 2), kernel_regularizer=regulizer, activation="elu") self.conv4 = layers.Conv2D(filters=64, kernel_size=(3, 3), kernel_regularizer=regulizer, activation="elu") self.conv5 = layers.Conv2D(filters=64, kernel_size=(3, 3), kernel_regularizer=regulizer, activation="elu") self.flat1 = layers.Flatten() # fully connected layers self.flcn1 = layers.Dense(units=100, kernel_regularizer=regulizer, activation="elu") self.flcn2 = layers.Dense(units=50, kernel_regularizer=regulizer, activation="elu") self.flcn3 = layers.Dense(units=10, activation="linear") self.flcn4 = layers.Dense(units=1, activation="linear") def __repr__(self): try: print(self.summary()) except ValueError: self.predict({ KEY_IMG: np.array([np.zeros(INPUT_SHAPE)]), KEY_PREVIOUS: np.array([0.0]) }) print(self.summary()) return "" def call(self, inputs): """ propagates through the neural net Args: inputs (dict): dictionary providing the image and steering angle batches Returns: numpy.ndarray: numpy array containing the predicted angles """ images = inputs[KEY_IMG] angles = inputs[KEY_PREVIOUS] # convolutions x = self.conv1(images) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) x = self.conv5(x) # flatten and add current steering angle x = self.flat1(x) x = tf.concat([x, angles], 1) # fully connected x = self.flcn1(x) x = self.flcn2(x) x = self.flcn3(x) x = self.flcn4(x) return x class SteeringNet: """ wrapper class simlifying accessing the `SteeringModel` """ IMG_DIRECTORY = "./data/steering/images/" CSV_TRAIN = "./data/steering/train.csv" CSV_VALIDATION = "./data/steering/validation.csv" def __init__(self): """ initializes the model by loading the default weights """ self.model = SteeringModel() self.load(const.Storage.DEFAULT_STEERING_MODEL) def __repr__(self): return self.model.__repr__() def predict(self, image, current_angle): """ predicts a steering angle based on the current image input and the current steering angle Args: image (str or numpy.ndarray): absolute path to the image or array representing the image's pixels current_angle (float): the vehicle's current steering angle Returns: float: predicted steering angle """ if isinstance(image, str): # load image if it is not a numpy array yet image = load_image(image) # ensure that the data is provided in the required format image, current_angle, _ = SteeringData.prepare_data(image, current_angle) image = np.array([image]) current_angle = np.array([current_angle]) inputs = {"image": image, "previous_angle": current_angle} angle = self.model.predict(inputs)[0][0] # predict steering angle value return angle def load(self, model_path): """ loads an existing model from a weights file Args: model_path (str): path to a representation of the model's weights """ self.predict(np.zeros(INPUT_SHAPE), 0.0) self.model.load_weights(model_path) def train(self, version, epochs=50, batch_size=256, loss="mae", lr=0.001, optimizer="adam"): """ trains the deep learning model Args: version (int or float or string): name of the training epochs (int): number of training iterations over the whole data set """ if not os.path.isdir(const.Storage.CHECKPOINTS): os.mkdir(const.Storage.CHECKPOINTS) if not os.path.isdir(f"{const.Storage.CHECKPOINTS}/v{version}"): os.mkdir(f"{const.Storage.CHECKPOINTS}/v{version}") # get training and validation data train_data = SteeringData(self.IMG_DIRECTORY, self.CSV_TRAIN, batch_size, True).generate() validation_data = SteeringData(self.IMG_DIRECTORY, self.CSV_VALIDATION, batch_size, False).generate() train_steps = calc_steps(self.CSV_TRAIN, batch_size) validation_steps = calc_steps(self.CSV_VALIDATION, batch_size) # define callbacks checkpoint = ModelCheckpoint(const.Storage.CHECKPOINTS + "/v" + str(version) + "/{epoch:03d}.h5", verbose=0) # compile and train the model self.model.compile(loss=loss, optimizer=optimizer, metrics = ["mae"]) history = self.model.fit_generator( generator=train_data, steps_per_epoch=train_steps, epochs=epochs, callbacks=[checkpoint], validation_data=validation_data, validation_steps=validation_steps, verbose=1 ) save_history(history, version) # save training process to disk def evaluate(self): """ measures the inaccuracy of the model Returns: float: mean absolute deviation float: proportion between the mean absolute deviation and the average target angle """ data = SteeringData(self.IMG_DIRECTORY, self.CSV_VALIDATION, 1, False) # get evaluation data samples = calc_steps(self.CSV_VALIDATION, 1) average_target = 0.0 absolute_deviation = 0.0 marginal_deviation = 0 steps = 0 # iterate over evaluation dataa for inputs, target in data: # get input and target values image = inputs[KEY_IMG][0] previous_angle = inputs[KEY_PREVIOUS][0] target = target[0] prediction = self.predict(image, previous_angle) deviation = abs(prediction - target) average_target += abs(target) absolute_deviation += deviation steps += 1 if deviation < 1: marginal_deviation += 1 print(f"{round(prediction, 2)} \t\t {round(target, 2)} \t\t {round(target - prediction, 2)}") if steps >= samples: break # calculate average average_target /= steps absolute_deviation /= steps # calculate proportion relative_deviation = absolute_deviation / average_target marginal_deviation /= steps # print evaluation results print(f"absolute deviation of {round(absolute_deviation, 2)}°") print(f"relative deviation of {100 * round(relative_deviation, 4)}%") print(f"{100 * round(marginal_deviation, 4)}% of the predictions deviated minimally") return absolute_deviation, relative_deviation, marginal_deviation if __name__ == "__main__": net = SteeringNet() net.train( version=1, epochs=100, batch_size=64, loss="mae", lr=0.00075, optimizer="adam" )
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,012
lukashaverbeck/parknet
refs/heads/master
/tests/test_interaction.py
import sys from pathlib import Path sys.path.append(str(Path(sys.path[0]).parent)) import unittest from vehicle import Agent from connection import Server from interaction import Communication, Message, ActionManager, Action class TestInteraction(unittest.TestCase): def setUp(self): self.agent = Agent.instance() self.communication_1 = Communication.instance() self.communication_2 = Communication.instance() self.message = Message(self.agent, "topic", None) self.action_manager_1 = ActionManager.instance() self.action_manager_2 = ActionManager.instance() self.action = Action(self.agent, "parking/enter") return super().setUp() def test_communication(self): self.assertEqual(self.communication_1, self.communication_2) self.assertIs(self.communication_1, self.communication_2) self.assertIsNotNone(Server.communication) self.assertIsNotNone(self.communication_1.agent) self.communication_1.subscribe("topic", None) self.assertGreater(len(self.communication_1.subscriptions), 0) def test_message(self): self.assertEqual(self.agent.id, self.message.sender) def test_action_manager(self): self.assertEqual(self.action_manager_1, self.action_manager_2) self.assertIs(self.action_manager_1, self.action_manager_2) self.action_manager_1.append("parking/enter") self.action_manager_1.append("parking/enter") self.action_manager_1.append("parking/enter") self.action_manager_1.append("parking/leave") self.action_manager_1.append("parking/enter") self.action_manager_1.append("parking/leave") self.action_manager_1.remove("parking/enter") self.assertEqual(len(self.action_manager_1.local_actions), 2) def test_action(self): self.assertEqual(self.action.agent, self.agent.id) self.assertTrue(self.action.is_owner(self.agent)) if __name__ == "__main__": unittest.main()
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,013
lukashaverbeck/parknet
refs/heads/master
/ui/interface.py
from flask import Flask, request, jsonify, render_template app = Flask(__name__) agent = None driver = None sensor_manager = None action_manager = None class WebInterface: def __init__(self, agent_instance, driver_instance, sensor_manager_instance, action_manager_instance): global agent, driver, sensor_manager, action_manager agent = agent_instance driver = driver_instance sensor_manager = sensor_manager_instance action_manager = action_manager_instance def start(self, ip_address, debug=False): port = "5000" app.run(host=ip_address, port=port, debug=debug) print(f"Starting Webserver(Interface) at: {ip_address}") @app.route("/") @app.route("/UI") def ui(): return render_template("UI.html") @app.route("/data-interval") def data(): data = [ { "id": "velocity", "value": driver.velocity, "unit": "cm/s" }, { "id": "steering-angle", "value": driver.angle, "unit": "°" }, { "id": "distance-front", "value": sensor_manager.front, "unit": "cm" }, { "id": "distance-right", "value": sensor_manager.right, "unit": "cm" }, { "id": "distance-back", "value": sensor_manager.rear, "unit": "cm" }, ] return jsonify(data) @app.route("/start-recording", methods=["POST"]) def start_recording(): driver.start_recording() return "" @app.route("/stop-recording", methods=["POST"]) def stop_recording(): driver.stop_recording() return "" @app.route("/emergency-stop", methods=["POST"]) def emergency_stop(): driver.stop_recording() driver.stop_driving() return "" @app.route("/change-mode", methods=["POST"]) def change_mode(): data = request.get_json(silent=True) if "mode" in data: action_manager.append(data["mode"]) return "" @app.route("/accelerate-forward", methods=["POST"]) def accelerate_forward(): driver.accelerate(1) return "" @app.route("/accelerate-backward", methods=["POST"]) def accelerate_backward(): driver.accelerate(-1) return "" @app.route("/steer-left", methods=["POST"]) def steer_left(): driver.steer(-1) return "" @app.route("/steer-right", methods=["POST"]) def steer_right(): driver.steer(1) return ""
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,806,014
lukashaverbeck/parknet
refs/heads/master
/scripts/calculate_pwm.py
# This script tests the relation between pwm and steering angles or velocities. # It gets user inputs and calculates the corresponding pwm values. # # NOTE This script is based on angle.py version: 2.0 (30.12.2019) # # version: 1.0 (13.12.2019) import sys import time import Adafruit_PCA9685 mode = "" # global value for mode chosen by user pwm = Adafruit_PCA9685.PCA9685(address=0x40, busnum=1) # create PCA9685-object at I2C-port pwm.set_pwm_freq(50) # set frequency def setup(): """ can be seen as 'home menu' """ global mode # change mode based on user input mode = input("To set a steering angle please press 'a'\nIn order to set a velocity press 'v'" + '\n' + "Press 'r' to return to start menu\nPress 'q' to quit: ") if mode == "q": # stop script when the q key is pressed sys.exit() elif mode == "a" or mode == "v": # pass this in case mode is nonsense input_value() setup() # restart "home menu" def calc_steering_pwm(angle): """ calculates a pwm value for a given angle Args: angle (float): angle to be converted to a pwm value Returns: float: corresponding pwm value """ return 2e-6 * angle ** 4 + 2e-6 * angle ** 3 + .005766 * angle ** 2 - 1.81281 * angle + 324.149 def calc_velocity_pwm(velocity): """ calculates a pwm value from velocity NOTE this function does not work yet TODO implement function Args: velocity (float): velocity to be converted to a pmw value Returns: float: corresponding pwm value """ return velocity def input_value(): """ uses user input to set values according to mode """ global mode # repeat until user quits while True: if mode == "a": # user wants to set steering angle user_input = input("\nPlease enter your angle[degree]: ") if user_input == "q": # stop script when the q key is pressed sys.exit() elif user_input == "r": # return to "home menu" setup() elif user_input == "e": # emergency stop option pwm.set_pwm(0, 0, 325) # set steering neutral pwm.set_pwm(1, 0, 340) # set esc to zero print("Emergency stopped vehicle!") input_value() # restart input method input_int = int(user_input) # cast user input to int for further processing if 35 >= input_int >= -35: # check if input is in range pwm_calc = calc_steering_pwm(input_int) # calculate pwm from angle pwm.set_pwm(0, 0, int(pwm_calc)) # cast calculated value to integer and set as pwm value print(f"pwm value is: {pwm_calc}") # echo for user and repeat else: # warn user and repreat print("Your angle is out of range! Please use angle between 35 and -35 degrees.") elif mode == "v": # user wants to set velocity user_input = input("'\n'Please enter your velocity[m/s]: ") if user_input == "q": # stop script when the q key is pressed sys.exit() elif user_input == "r": # return to "home menu" setup() elif user_input == "e": # emergency stop option pwm.set_pwm(0, 0, 325) # set steering neutral pwm.set_pwm(1, 0, 340) # set esc to zero print("Emergency stopped vehicle!") input_value() # restart input method input_int = int(user_input) # cast user input into int for further processing pwm_calc = calc_velocity_pwm(input_int) # returns untouched input for now pwm.set_pwm(0, 0, int(pwm_calc)) # cast calculated value to integer and set as pwm value print(f"pwm value is: {pwm_calc}") # echo for user and repeat setup() # start the script
{"/interaction/formation.py": ["/attributes/__init__.py", "/interaction.py", "/sensing/__init__.py", "/util.py"], "/util/concurrent.py": ["/util.py"], "/sensing/__init__.py": ["/sensing/distance.py", "/sensing/scanner.py"], "/attributes/agent.py": ["/util.py"], "/control/driver.py": ["/attributes/__init__.py", "/sensing/__init__.py", "/util.py"], "/interaction/communication.py": ["/attributes/__init__.py", "/interaction.py", "/util.py"], "/main.py": ["/control/__init__.py"], "/interaction/__init__.py": ["/interaction/communication.py", "/interaction/formation.py", "/interaction/message.py"], "/attributes/__init__.py": ["/attributes/agent.py"], "/tests/integration/test_interaction.py": ["/interaction.py"], "/control/agent.py": ["/attributes/__init__.py", "/control/__init__.py", "/interaction.py", "/util.py"], "/tests/integration/test_control.py": ["/control/__init__.py"], "/tests/integration/__init__.py": ["/tests/integration/test_attributes.py"], "/sensing/scanner.py": ["/util.py"], "/tests/integration/test_attributes.py": ["/attributes/__init__.py"], "/interaction/message.py": ["/util.py"], "/util/__init__.py": ["/util.py", "/util/assertions.py", "/util/concurrent.py", "/util/single.py", "/util/threaded.py", "/util/time_measurement.py"], "/control/__init__.py": ["/control/agent.py", "/control/driver.py"], "/connection.py": ["/interaction.py", "/constants.py"], "/vision.py": ["/constants.py", "/util.py"], "/tests/test_vehicle.py": ["/vehicle.py"], "/tests/test_util.py": ["/util.py"], "/interaction.py": ["/vehicle.py", "/constants.py", "/util.py", "/vision.py", "/connection.py"], "/vehicle.py": ["/interaction.py", "/constants.py", "/ai.py", "/util.py", "/ui/interface.py", "/vision.py", "/connection.py"], "/ai.py": ["/constants.py"], "/tests/test_interaction.py": ["/vehicle.py", "/connection.py", "/interaction.py"]}
41,810,299
VannieryFernandes/loja-de-carros
refs/heads/main
/app/v1/veiculos/veiculosRecursos.py
from fastapi import APIRouter router = APIRouter() @router.get("/lista-de-veiculos") def lista_carros(): return []
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,300
VannieryFernandes/loja-de-carros
refs/heads/main
/app/v1/usuarios/usuariosModels.py
from sqlalchemy import Boolean, Column, Integer, String from sqlalchemy.orm import relationship from app.core.db import Base class Usuario(Base): __tablename__ = 'usuarios' id = Column(Integer, primary_key=True, index=True) full_name = Column(String, index=True) email = Column(String, unique=True, index=True) is_active = Column(Boolean(), default=True) is_superuser = Column(Boolean(), default=False) password = Column(String, index=True)
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,301
VannieryFernandes/loja-de-carros
refs/heads/main
/app/v1/autenticacao/autenticacaoRecursos.py
from fastapi import APIRouter router = APIRouter() @router.post("/entrar") def entrar(): return "Autenticando"
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,302
VannieryFernandes/loja-de-carros
refs/heads/main
/app/v1/routers.py
from fastapi import APIRouter from app.v1.veiculos import veiculosRecursos from app.v1.autenticacao import autenticacaoRecursos from app.v1.usuarios import usuariosRecursos api_router = APIRouter() api_router.include_router(autenticacaoRecursos.router, tags=["autenticacao"]) api_router.include_router(veiculosRecursos.router, prefix="/veiculos", tags=["veiculos"]) api_router.include_router(usuariosRecursos.router, prefix="/usuarios", tags=["usuarios"])
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,303
VannieryFernandes/loja-de-carros
refs/heads/main
/app/v1/clientes/clientesRecursos.py
from fastapi import APIRouter router = APIRouter() @router.get("/lista-de-clientes") def lista_clientes(): return {"Hello":"Clientes"}
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,304
VannieryFernandes/loja-de-carros
refs/heads/main
/app/core/db.py
import os from sqlalchemy import create_engine from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from starlette.requests import Request from dotenv import find_dotenv, load_dotenv load_dotenv(find_dotenv()) SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL") engine = create_engine( SQLALCHEMY_DATABASE_URL, pool_pre_ping=True ) # db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base: DeclarativeMeta = declarative_base() def get_db(request: Request): print(request) return request.state.db
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,305
VannieryFernandes/loja-de-carros
refs/heads/main
/tests/test_gerenciador.py
from core.main import app from fastapi.testclient import TestClient def test_quando_listar_carros_deve_ter_como_retorno_codigo_de_status_200(): cliente = TestClient(app) resposta = cliente.get("/veiculos/lista-de-veiculos") assert resposta.status_code == 200 # assert resposta.json() == {"msg": "Hello World"} def test_quando_listar_carros_formato_de_retorno_deve_ser_json(): cliente = TestClient(app) resposta = cliente.get("/carros") assert resposta.headers["Content-Type"] == "application/json" def test_quando_listar_carros_retorno_deve_ser_uma_lista(): cliente = TestClient(app) resposta = cliente.get("/carros") assert isinstance(resposta.json(), list)
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,306
VannieryFernandes/loja-de-carros
refs/heads/main
/app/v1/usuarios/usuariosController.py
from typing import Optional from sqlalchemy.orm import Session from app.v1.usuarios.usuariosModels import Usuario from app.v1.usuarios.usuariosSchema import UserCreate, UserUpdate class UserController(Usuario): def get_by_email( db_session: Session, email: str) -> Optional[Usuario]: return db_session.query(Usuario).filter(Usuario.email == email).first() def create(db_session: Session, obj_in: UserCreate) -> Usuario: db_obj = Usuario( email=obj_in.email, full_name=obj_in.full_name, is_superuser=obj_in.is_superuser, password=obj_in.password ) db_session.add(db_obj) db_session.commit() db_session.refresh(db_obj) return db_obj
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,307
VannieryFernandes/loja-de-carros
refs/heads/main
/main.py
from fastapi import FastAPI, Response, Request from app.v1 import routers from app.core.db import engine,SessionLocal app = FastAPI( title="Minha loja de veículos", description="Autor: Vanniery Fernandes", version="0.1" ) @app.middleware("http") async def db_session_middleware(request: Request, call_next): response = Response("Internal server error", status_code=500) try: request.state.db = SessionLocal() response = await call_next(request) finally: request.state.db.close() return response app.include_router(routers.api_router)
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,810,308
VannieryFernandes/loja-de-carros
refs/heads/main
/app/v1/usuarios/usuariosRecursos.py
from fastapi import APIRouter, Body, Depends, HTTPException from app.v1.usuarios.usuariosController import UserController from app.v1.usuarios.usuariosSchema import User, UserCreate from app.core.db import get_db from sqlalchemy.orm import Session router = APIRouter() @router.post("/criar-usuario", response_model=User) def create_user( *, db: Session = Depends(get_db), user_in: UserCreate # current_user: DBUser = Depends(get_current_active_superuser), ): """ Create new user. """ user = UserController.get_by_email(db, email=user_in.email) if user: raise HTTPException( status_code=400, detail="Usuário já cadastrado.", ) user = UserController.create(db, obj_in=user_in) return user
{"/app/v1/usuarios/usuariosModels.py": ["/app/core/db.py"], "/tests/test_gerenciador.py": ["/core/main.py"], "/app/v1/usuarios/usuariosController.py": ["/app/v1/usuarios/usuariosModels.py"], "/main.py": ["/app/core/db.py"], "/app/v1/usuarios/usuariosRecursos.py": ["/app/v1/usuarios/usuariosController.py", "/app/core/db.py"]}
41,853,684
LoafBurger/ChainVote
refs/heads/main
/tiktokScraper.py
from os import link from bs4 import BeautifulSoup from urllib.request import urlopen as uReq #grab from the page from bs4 import BeautifulSoup as soup #parse html text from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from urllib.request import urlopen as uReq #grab from the page from bs4 import BeautifulSoup as soup #parse html text options = Options() options.headless = False options.add_argument("--window-size=1920,1200") DRIVER_PATH = '/Users/idanlau/Downloads/chromedriver' driver = webdriver.Chrome(options=options, executable_path=DRIVER_PATH) driver.get('https://www.google.com/') sub = "Lil Dicky" search = driver.find_element_by_xpath("//input [@name = 'q']") search.send_keys(sub) search.send_keys(Keys.RETURN) my_url = driver.current_url #instagramUser = [] #while len(instagramUser) == 0: # try: # instagramUser = driver.find_elements_by_xpath("//g-link[@class='fl']/a") # #instagramUser = driver.find_element_by_tag_name('a') # instagramUser = instagramUser.get_attribute('href') # instagramUser = driver.find_elements_by_xpath("//div[@class='S6VXfe']/a")get_attribute(href) #instagramUser = instagramUser.text # print("user") # print(instagramUser) lnks=driver.find_elements_by_tag_name("g-link") lnks=lnks[2].find_elements_by_tag_name("a") # traverse list for lnk in lnks: # if "instagram" in str(lnk): # print(lnk.get_attribute("href")) print(lnk.get_attribute("href")) #print(lnk.get_attribute("href")) driver.quit() # except: # pass # firstRes = instagramUser[0] # firstRes.click() # username = "bot404sugondeez" # password = "3.1415926" # search = driver.find_element_by_xpath("//input [@name = 'username']") # search.send_keys(username) # search.send_keys(Keys.RETURN) # uClient = uReq(my_url) #opening up connection, grabbing the page # page_html = uClient.read()#stores all content into a variable # uClient.close() # page_soup = soup(page_html, "html.parser")#html parsing # #print(page_soup.h1) # containers = page_soup.findAll("section", {"class":"zwlfE"}) #grabs each product # #print(len(containers)) # for i in containers: # brand = div.h2 # print("Insta Name: " + brand)
{"/Election/models.py": ["/Election/makeshiftHashNew.py", "/Election/initVoters.py", "/Election/globalValsGenerator.py"], "/Election/views.py": ["/Election/models.py", "/Election/makeshiftHashNew.py", "/Election/initVoters.py"], "/Election/blockchain.py": ["/Election/makeshiftHashNew.py", "/Election/block.py"], "/Election/initVoters.py": ["/Election/voterVerifier.py", "/Election/makeshiftHashNew.py"], "/Election/admin.py": ["/Election/models.py"], "/Home/views.py": ["/Election/models.py"]}
41,853,685
LoafBurger/ChainVote
refs/heads/main
/rovtest.py
# from inputs import devices # from inputs import get_gamepad import pygame import socket import serial import sys # for device in devices: # print(device) pygame.init() display = pygame.display.set_mode((600, 600)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(socket.gethostbyname(socket.gethostname())) s.bind(('192.168.68.102', 5050)) print(socket.gethostbyname(socket.gethostname())) #s.bind(('10.81.15.219', 5050)) def netcat(content): clientsocket.send(content.encode()) s.listen(1) clientsocket , address = s.accept() print("passe") while 1: pressed_keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: netcat('foward') elif event.key == pygame.K_s: netcat('backward') if event.key == pygame.K_d: netcat('right') elif event.key == pygame.K_a: netcat('left') if event.key == pygame.K_UP: netcat('up') if event.key == pygame.K_DOWN: netcat('down') if event.key == pygame.K_RIGHT: netcat('up1') elif event.key == pygame.K_LEFT: netcat('up2') if event.key == pygame.K_SPACE: netcat('open') elif event.key == pygame.K_m: netcat('close') if event.type == pygame.KEYUP: if event.key == pygame.K_w and pressed_keys[pygame.K_s] == False: netcat('zstop') if event.key == pygame.K_s and pressed_keys[pygame.K_w] == False: netcat('zstop') if event.key == pygame.K_d and pressed_keys[pygame.K_a] == False: netcat('xstop') if event.key == pygame.K_a and pressed_keys[pygame.K_d] == False: netcat('xstop') if event.key == pygame.K_UP and pressed_keys[pygame.K_DOWN] == False: netcat('ystop') if event.key == pygame.K_DOWN and pressed_keys[pygame.K_UP] == False: netcat('ystop') if event.key == pygame.K_RIGHT and pressed_keys[pygame.K_LEFT] == False: netcat('ystop') if event.key == pygame.K_LEFT and pressed_keys[pygame.K_RIGHT] == False: netcat('ystop') # for event in events: # if event.code == "ABS_Y": # if(event.state < 20): # netcat('192.168.2.2', 40000, 'foward') # elif(event.state > 150): # netcat('192.168.2.2', 40000, 'backward') # else: # netcat('192.168.2.2', 40000, 'zstop') # if event.code == "ABS_X": # if(event.state < 20): # netcat('192.168.2.2', 40000, 'left') # elif(event.state > 150): # netcat('192.168.2.2', 40000, 'right') # else: # netcat('192.168.2.2', 40000, 'xstop') # if event.code == "ABS_RZ": # if(event.state < 20): # netcat('192.168.2.2', 40000, 'up') # elif(event.state > 150): # netcat('192.168.2.2', 40000, 'down') # else: # netcat('192.168.2.2', 40000, 'ystop')
{"/Election/models.py": ["/Election/makeshiftHashNew.py", "/Election/initVoters.py", "/Election/globalValsGenerator.py"], "/Election/views.py": ["/Election/models.py", "/Election/makeshiftHashNew.py", "/Election/initVoters.py"], "/Election/blockchain.py": ["/Election/makeshiftHashNew.py", "/Election/block.py"], "/Election/initVoters.py": ["/Election/voterVerifier.py", "/Election/makeshiftHashNew.py"], "/Election/admin.py": ["/Election/models.py"], "/Home/views.py": ["/Election/models.py"]}
41,853,686
LoafBurger/ChainVote
refs/heads/main
/wInsta.py
import pandas as pd pd.read_csv()
{"/Election/models.py": ["/Election/makeshiftHashNew.py", "/Election/initVoters.py", "/Election/globalValsGenerator.py"], "/Election/views.py": ["/Election/models.py", "/Election/makeshiftHashNew.py", "/Election/initVoters.py"], "/Election/blockchain.py": ["/Election/makeshiftHashNew.py", "/Election/block.py"], "/Election/initVoters.py": ["/Election/voterVerifier.py", "/Election/makeshiftHashNew.py"], "/Election/admin.py": ["/Election/models.py"], "/Home/views.py": ["/Election/models.py"]}
41,923,053
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/migrations/0020_auto_20210508_1734.py
# Generated by Django 3.1.7 on 2021-05-08 13:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0019_auto_20210508_1704'), ] operations = [ migrations.AlterField( model_name='task', name='title', field=models.TextField(verbose_name='Basliq:'), ), ]
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,054
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/models.py
from django.db import models from django.db.models.deletion import CASCADE from django.contrib.auth.models import User # Create your models here. class Task(models.Model): author = models.ForeignKey(User ,on_delete=models.CASCADE ,null=True ,verbose_name="Yazan:",blank=True ,default=None) title = models.TextField(verbose_name="Basliq:") created_date = models.DateTimeField(auto_now_add=True,verbose_name="Yazilma Tarixi:") confirm = models.BooleanField(default=False,verbose_name="Tamamlanilib?:") def __str__(self): return self.title
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,055
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/views.py
from django.shortcuts import render,redirect from . import models from .forms import * from django.contrib.auth.decorators import login_required # Create your views here. @login_required(login_url="user:login") def index(request): tasks = models.Task.objects.filter(confirm="False",author=request.user).order_by('-id') form = TaskForm() if request.method == "POST": form = TaskForm(request.POST) if form.is_valid: instance=form.save(commit=False) instance.author = request.user instance.save() return redirect("/") context = { "tasks":tasks, "form":form, } return render(request,"index.html",context) @login_required(login_url="user:login") def updateTask(request,id): task = models.Task.objects.get(id=id) form = TaskForm(instance=task) if request.user == task.author: if request.method == "POST": form = TaskForm(request.POST,instance=task) if form.is_valid: form.save() return redirect("/") else: raise ValueError("Bu Task Sizin Deyil!") context = { "form":form, } return render(request,"update_task.html",context) @login_required(login_url="user:login") def deleteTask(request,id): task = models.Task.objects.get(id=id) if request.user == task.author: task.delete() return redirect("/") else: raise ValueError("Bu Task Sizin Deyil!") context = { "task":task, } return render(request,"delete_task.html",context) @login_required(login_url="user:login") def complededTasks(request): tasks = models.Task.objects.filter(confirm="True",author=request.user) context = { "tasks":tasks, } return render(request,"completeds.html",context)
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,056
MustafayevMohammed/To-Do
refs/heads/nihad
/user/views.py
from django.core.exceptions import ValidationError from django.contrib.auth import authenticate, login, logout from django.shortcuts import render,redirect from .forms import * # Create your views here. def registerPage(request): form = RegisterForm() if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect("tasks:index") context = {"form":form} return render(request,"register.html",context) def loginPage(request): form = LoginForm() if request.method == "POST": form = LoginForm(request.POST) username = request.POST.get("username") password = request.POST.get("password") account = authenticate(username=username,password=password) if account is None: raise ValidationError(request,"Parol Ya Da Istifadeci Adi Uygun Deyil!") else: login(request,account) return redirect("tasks:index") context = { "form":form, } return render(request,"login.html",context) def logoutPage(request): logout(request) return redirect("tasks:index")
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,057
MustafayevMohammed/To-Do
refs/heads/nihad
/user/forms.py
from django.forms.forms import Form from tasks.views import deleteTask from django import forms from django.db.models import fields from django.forms import ModelForm, widgets from django.forms.fields import CharField from . import models from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): password1 = CharField( widget=forms.PasswordInput(attrs={'class':'passfields','style':'text-align:center; margin-left:100px; width:75%; border-radius:3px;'}) ) password2 = CharField( widget=forms.PasswordInput(attrs={'class':'passfields','style':'text-align:center; margin-left:100px; width:75%; border-radius:3px;'}) ) class Meta(UserCreationForm.Meta): model = User widgets = { 'username': forms.TextInput(attrs={'class':'fields'}), 'email': forms.TextInput(attrs={'class':'fields'}), } fields = ["password1","password2","username","email"] class LoginForm(forms.Form): username = forms.CharField(required=True,widget=forms.TextInput(attrs={ 'class':"login-fields" })) password = forms.CharField(required=True,widget=forms.PasswordInput(attrs={ "class":"login-fields" }))
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,058
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/forms.py
from django import forms from django.db.models import fields from django.forms import ModelForm, widgets from . import models # Forms class TaskForm(forms.ModelForm): class Meta: model = models.Task widgets = { 'title': forms.Textarea(attrs={'class':'addbar','spellcheck':'false','cols':81,'rows':4,'style':'resize:none;'}), } fields = "__all__"
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,059
MustafayevMohammed/To-Do
refs/heads/nihad
/user/urls.py
from django.conf.urls import include from django.contrib import admin from django.urls import path from . views import * app_name = "user" urlpatterns = [ path("register/",registerPage,name="register"), path("login/",loginPage,name="login"), path("logout/",logoutPage,name="logout"), ]
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,060
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/migrations/0019_auto_20210508_1704.py
# Generated by Django 3.1.7 on 2021-05-08 13:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0018_auto_20210508_1703'), ] operations = [ migrations.AlterField( model_name='task', name='title', field=models.TextField(blank=True, verbose_name='Basliq:'), ), ]
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,061
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/migrations/0017_auto_20210508_1648.py
# Generated by Django 3.1.7 on 2021-05-08 12:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0016_task_author'), ] operations = [ migrations.AlterField( model_name='task', name='title', field=models.TextField(blank=True, verbose_name='Basliq:'), ), ]
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,062
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/admin.py
from django.contrib import admin from . import models # Register your models here. @admin.register(models.Task) class TaskAdmin(admin.ModelAdmin): list_display = ["id","title","author"] list_display_links = ["id","title"] class Meta: model = models.Task
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,923,063
MustafayevMohammed/To-Do
refs/heads/nihad
/tasks/urls.py
from django.contrib import admin from django.urls import path from . import views app_name = "tasks" urlpatterns = [ path("",views.index,name="index"), path("updatetask/<str:id>/",views.updateTask,name="update_task"), path("delete_task<str:id>/",views.deleteTask,name="delete_task"), path("completed",views.complededTasks,name="completed_tasks"), ]
{"/user/urls.py": ["/user/views.py"], "/tasks/views.py": ["/tasks/forms.py"], "/user/views.py": ["/user/forms.py"], "/user/forms.py": ["/tasks/views.py"]}
41,948,519
cszdzr/CITS-5505-Project2
refs/heads/master
/migrations/versions/7b4aa852b80c_ass_enrollments_table.py
"""ass enrollments table Revision ID: 7b4aa852b80c Revises: 356d5ec3bf71 Create Date: 2021-05-14 11:56:46.042334 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7b4aa852b80c' down_revision = '356d5ec3bf71' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('enrollment', sa.Column('id', sa.Integer(), nullable=False), sa.Column('course_id', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('time_of_completion', sa.DateTime(), nullable=True), sa.Column('score', sa.Float(), nullable=True), sa.ForeignKeyConstraint(['course_id'], ['user.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('enrollment') # ### end Alembic commands ###
{"/app/routes.py": ["/app/forms.py"]}
41,948,520
cszdzr/CITS-5505-Project2
refs/heads/master
/app/routes.py
from datetime import datetime from flask import render_template, flash, redirect, url_for, request from flask_login import login_user, logout_user, current_user, login_required from werkzeug.urls import url_parse from app import app, db from app.forms import LoginForm, RegistrationForm, \ ResetPasswordRequestForm, ResetPasswordForm, RPPForm from app.models import User, Course, Enrollment from app.email import send_password_reset_email @app.before_request def before_request(): if current_user.is_authenticated: current_user.last_seen = datetime.utcnow() db.session.commit() @app.route('/', methods=['GET']) @app.route('/index', methods=['GET']) def index(): if current_user.is_authenticated: return redirect(url_for('explore')) return render_template('index.html', title='Home') @app.route('/explore') @login_required def explore(): courses = Course.query.all() return render_template('explore.html', title='Explore', courses=courses) @app.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', title='Sign In', form=form) @app.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @app.route('/register', methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form) @app.route('/reset_password_request', methods=['GET', 'POST']) def reset_password_request(): if current_user.is_authenticated: return redirect(url_for('index')) form = ResetPasswordRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: send_password_reset_email(user) flash('Check your email for the instructions to reset your password') return redirect(url_for('login')) return render_template('reset_password_request.html', title='Reset Password', form=form) @app.route('/reset_password/<token>', methods=['GET', 'POST']) def reset_password(token): if current_user.is_authenticated: return redirect(url_for('index')) user = User.verify_reset_password_token(token) if not user: return redirect(url_for('index')) form = ResetPasswordForm() if form.validate_on_submit(): user.set_password(form.password.data) db.session.commit() flash('Your password has been reset.') return redirect(url_for('login')) return render_template('reset_password.html', form=form) @app.route('/course/<coursename>') @login_required def course(coursename): course = Course.query.filter_by(name=coursename).first_or_404() return render_template('course.html', course=course) @app.route('/assessment/<coursename>', methods=['GET']) @login_required def assessment(coursename): course = Course.query.filter_by(name=coursename).first_or_404() form = None if course.assessment_file == 'rpp_test.html': form = RPPForm() return render_template('assessment.html', form=form, course=course) @app.route('/result/<coursename>', methods=['POST']) @login_required def result(coursename): course = Course.query.filter_by(name=coursename).first_or_404() form = None if course.assessment_file == 'rpp_test.html': form = RPPForm() result = 0 if form.question1.data == "2": result+=1 if form.question2.data == "2": result+=1 if form.question3.data == "1": result+=1 if form.question4.data == "1": result+=1 if form.question5.data == "3": result+=1 score = int(result/5*100) new = Enrollment(course_id = course.id, user_id = current_user.id, score = score, course_name = course.name) db.session.add(new) db.session.commit() return render_template('result.html', result = score) @app.route('/overall_results', methods = ['GET']) @login_required def overall_results(): results = Enrollment.query.filter_by(user_id=current_user.id).all() return render_template('overall_results.html', results=results)
{"/app/routes.py": ["/app/forms.py"]}
41,948,521
cszdzr/CITS-5505-Project2
refs/heads/master
/app/setup.py
from app.models import Course from app import db u = Course(name="Reverse Parallel Park", content_url='https://www.youtube.com/embed/l4LcfZeS4qw', assessment_file="rpp_test.html", thumbnail='https://i.ytimg.com/vi/l4LcfZeS4qw/hqdefault.jpg') db.session.add(u) db.session.commit()
{"/app/routes.py": ["/app/forms.py"]}
41,948,522
cszdzr/CITS-5505-Project2
refs/heads/master
/migrations/versions/1358ad741915_update_course_table.py
"""update course table Revision ID: 1358ad741915 Revises: 2c8fa162f9f7 Create Date: 2021-05-11 15:47:41.090608 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1358ad741915' down_revision = '2c8fa162f9f7' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('course', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=128), nullable=True), sa.Column('content_url', sa.String(length=128), nullable=True), sa.Column('assessment_file', sa.String(length=128), nullable=True), sa.Column('youtube_id', sa.String(length=128), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_course_name'), 'course', ['name'], unique=True) op.drop_index('ix_courses_name', table_name='courses') op.drop_table('courses') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('courses', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('name', sa.VARCHAR(length=128), nullable=True), sa.Column('content_url', sa.VARCHAR(length=128), nullable=True), sa.Column('assessment_file', sa.VARCHAR(length=128), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index('ix_courses_name', 'courses', ['name'], unique=False) op.drop_index(op.f('ix_course_name'), table_name='course') op.drop_table('course') # ### end Alembic commands ###
{"/app/routes.py": ["/app/forms.py"]}
41,948,523
cszdzr/CITS-5505-Project2
refs/heads/master
/migrations/versions/12aef4ff4368_add_course_name_to_enrollments.py
"""add course_name to enrollments Revision ID: 12aef4ff4368 Revises: 7b4aa852b80c Create Date: 2021-05-14 12:54:44.110236 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '12aef4ff4368' down_revision = '7b4aa852b80c' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('enrollment', sa.Column('course_name', sa.String(length=128), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('enrollment', 'course_name') # ### end Alembic commands ###
{"/app/routes.py": ["/app/forms.py"]}
41,948,524
cszdzr/CITS-5505-Project2
refs/heads/master
/app/forms.py
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, \ TextAreaField, RadioField from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, \ Length from app.models import User class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) remember_me = BooleanField('Remember Me') submit = SubmitField('Sign In') class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) password2 = PasswordField( 'Repeat Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Register') def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if user is not None: raise ValidationError('Please use a different username.') def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user is not None: raise ValidationError('Please use a different email address.') class ResetPasswordRequestForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) submit = SubmitField('Request Password Reset') class ResetPasswordForm(FlaskForm): password = PasswordField('Password', validators=[DataRequired()]) password2 = PasswordField( 'Repeat Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Request Password Reset') class RPPForm(FlaskForm): question1 = RadioField('How big must the parking spot be for you to be able to fit into it easily?', choices=[(1,'A) 1 times the length of your car'),(2,'B) 1.5 times the length of your car'),(3,'C) 2 times the length of your car')], validators=[DataRequired()]) question2 = RadioField('When should you initially start turning into the parking space?', choices=[(1,'A) Before the back end of the front car is visible in the triangular window'),(2,'B) When the back end of the front car is visible in the triangular window'),(3,'C) After the back end of the front car has completely left the triangular window')], validators=[DataRequired()]) question3 = RadioField('When should you return the steering wheel to straight?', choices=[(1,'A) When the right hand corner of the back car appears in the left hand mirror'),(2,'B) When the middle of the back car appears in the left hand mirror'),(3,'C) When you feel the wheels hit the curb')], validators=[DataRequired()]) question4 = RadioField('When should you turn the steering wheel to the left?', choices=[(1,'A) When the right hand mirror covers the left hand tail light of the car in front'),(2,'B) When the right hand mirror covers the number plate of the car in front'),(3,'C) When the back of your car is about 50 cm from the curb')], validators=[DataRequired()]) question5 = RadioField('When should you return the steering wheel to a straight position?', choices=[(1,'A) When your car is within 10 cm of the curb'),(2,'B) When your car is about 30 cm behind the car in front'),(3,'C) When your right hand mirror shows that you are parallel to the curb')], validators=[DataRequired()]) submit = SubmitField('Submit')
{"/app/routes.py": ["/app/forms.py"]}
41,948,525
cszdzr/CITS-5505-Project2
refs/heads/master
/migrations/versions/2c8fa162f9f7_courses_table.py
"""courses table Revision ID: 2c8fa162f9f7 Revises: ae346256b650 Create Date: 2021-05-11 13:06:32.935452 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2c8fa162f9f7' down_revision = 'ae346256b650' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('courses', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=128), nullable=True), sa.Column('content_url', sa.String(length=128), nullable=True), sa.Column('assessment_file', sa.String(length=128), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_courses_name'), 'courses', ['name'], unique=True) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_courses_name'), table_name='courses') op.drop_table('courses') # ### end Alembic commands ###
{"/app/routes.py": ["/app/forms.py"]}
41,948,526
cszdzr/CITS-5505-Project2
refs/heads/master
/migrations/versions/356d5ec3bf71_change_youtube_id_to_thumbnail_url.py
"""change youtube id to thumbnail url Revision ID: 356d5ec3bf71 Revises: 1358ad741915 Create Date: 2021-05-11 16:11:40.009867 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '356d5ec3bf71' down_revision = '1358ad741915' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('course', sa.Column('thumbnail', sa.String(length=128), nullable=True)) op.drop_column('course', 'youtube_id') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('course', sa.Column('youtube_id', sa.VARCHAR(length=128), nullable=True)) op.drop_column('course', 'thumbnail') # ### end Alembic commands ###
{"/app/routes.py": ["/app/forms.py"]}
42,007,602
PlugRS/SharkFin
refs/heads/main
/config.py
TWITTER_CONSUMER_KEY = "PDhjzY9bX15cLkN4r6gdKPqdw" TWITTER_CONSUMER_SECRET = "BtWpjw9JkLsgNW30qXQosZUtG5DwAtJh5nt6O6wDs1CJaRFd6S" TWITTER_ACCESS_TOKEN = "1303281499714646016-GkZ3D456tvsGy3NbLT8spvJMyuOI3k" TWITTER_ACCESS_TOKEN_SECRET = "VJ5vuhGLJCGJYoWNG1BnM3HN7XiCZa6qDGJD8FbtkYK74" TWITTER_USERNAMES = [ "livemint", "EconomicTimes", "moneycontrolcom", 'Reutersindia', "FinancialTimes", "NDTVProfit{" ] IEX_API_TOKEN = "pk_b76493230b804970a25340b18bd8f83b"
{"/dashboard.py": ["/config.py"]}
42,007,603
PlugRS/SharkFin
refs/heads/main
/dashboard.py
import streamlit as st import pandas as pd import numpy as np import requests import config import tweepy from datetime import datetime, timedelta import json import yfinance as yf import pandas as pd auth = tweepy.OAuthHandler(config.TWITTER_CONSUMER_KEY, config.TWITTER_CONSUMER_SECRET) auth.set_access_token(config.TWITTER_ACCESS_TOKEN, config.TWITTER_ACCESS_TOKEN_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) option = st.sidebar.selectbox("Select Dashboard:", ('News', 'Twitter','Global','Stock Chart')) if option == 'Twitter': for username in config.TWITTER_USERNAMES: user = api.get_user(username) tweets = api.user_timeline(username, tweet_mode="extended") st.write("___________________________") st.image(user.profile_image_url) st.header("**_Source:_** "+ username) st.write("___________________________") for tweet in tweets: st.write(tweet.full_text) #full trext of tweets st.write("__________") if option == 'Global': symbol = st.sidebar.text_input('Symbol',value = 'TSLA', max_chars=5) st.subheader("Global Stock Tweets") r = requests.get(f"https://api.stocktwits.com/api/2/streams/symbol/{symbol}.json") data = r.json() for message in data['messages']: st.image(message['user']['avatar_url']) st.write("User: ",message['user']['username']) st.write("Time: ",message['created_at']) st.write("->",message['body']) st.write("___________________________________________________") if option == 'Stock Chart': st.write('Put .NS suffix to any indian stock name for its chart.') stocksymbol = st.text_input("stock name: NS => NSE | BO => BSE", 'RELIANCE.NS') opendate = st.text_input("open date (yyyy-mm-dd) : (make sure it's less than close date, duh..)", '2021-1-1') closedate = st.text_input("close date (yyyy-mm-dd)", '2021-4-12') #screen = st.sidebar.selectbox("View", ('Overview', 'Fundamentals', 'News', 'Ownership', 'Technicals'), index=1) stockdata = yf.Ticker(stocksymbol) tickerDf = stockdata.history(period='1d', start=opendate, end=closedate) st.write('Price fluctuations:-') st.line_chart(tickerDf.Close) st.write('Share volume movement:-') st.line_chart(tickerDf.Volume) stockinfo = stockdata.info st.header('Stock Overview:-') holders = stockdata.major_holders st.write('BALANCE SHEET') st.write(stockdata.balance_sheet) st.write('MAJOR HOLDERS') st.write(holders) for key,value in stockinfo.items(): st.subheader(key) st.write(value) if option == 'News': newstype = st.sidebar.selectbox("Select:", ('Top Headlines', 'Business', 'Technology')) if newstype == 'Business': st.header('Business News') r = requests.get('API KEY FROM NEWS API') data = json.loads(r.content) for i in range(15): news = data['articles'][i]['title'] st.header(news) image = data['articles'][i]['urlToImage'] try: st.image(image) except: pass else: pass content = data['articles'][i]['content'] st.write(content) url = data['articles'][i]['url'] st.write(url) if newstype == 'Top Headlines': st.header('Top Headlines') r = requests.get('') data = json.loads(r.content) for i in range(15): news = data['articles'][i]['title'] #branching in st.subheader(news) image = data['articles'][i]['urlToImage'] try: st.image(image) except: pass else: pass content = data['articles'][i]['content'] st.write(content) url = data['articles'][i]['url'] st.write(url) if newstype == 'Technology': st.header('Technology News') r = requests.get('') data = json.loads(r.content) for i in range(15): news = data['articles'][i]['title'] #branching in st.subheader(news) image = data['articles'][i]['urlToImage'] try: st.image(image) except: pass else: pass content = data['articles'][i]['content'] st.write(content) url = data['articles'][i]['url'] st.write(url)
{"/dashboard.py": ["/config.py"]}
42,035,517
phtvo/yolo
refs/heads/master
/Experiments/voc2012/voc_data.py
# test from torch.utils.data import DataLoader # import sys import os sys.path.insert(0, os.getcwd()) PATH = os.path.dirname(__file__) from Yolov3.Dataset.dataformat import ReadXML_VOC_Format, readTxt from Yolov3.Dataset.dataset import yoloCoreDataset, cv2, np class VOC_data(yoloCoreDataset): def __init__(self, path, labels, img_size=416, # fixed size image debug=False, argument=True, draw=False, max_objects=15, is_train=True, split = None ): super(VOC_data, self).__init__(path, labels, debug=debug, is_train=is_train, split=split) self.debug = debug self.argument = argument self.draw = draw self.max_objects = max_objects def InitDataset(self): """Use preset data set in './ImageSets/Main' contains [train.txt, val.txt] +data root: + /ImageSets/Main: + train.txt + val.txt + Annotations + JPEGImages """ annotations = "Annotations" jpegimages = "JPEGImages" if self.split is None: train_txt = 'ImageSets/Main/train.txt' val_txt = 'ImageSets/Main/val.txt' images_path = train_txt if (self.is_train) else val_txt images_path = readTxt(os.path.join(self.path, images_path)) images_path.pop(-1) elif self.split < 1. and self.split > 0: trainval = 'ImageSets/Main/trainval.txt' images_path = readTxt(os.path.join(self.path, trainval)) images_path.pop(-1) n_imgs = len(images_path) ratio = int(n_imgs*self.split) if self.is_train: images_path = images_path[:ratio] else: images_path = images_path[ratio:] else: raise f'Wrong split data {self.split}' # rawdata format: [path_2_image, path_2_xml] rawData = list() for each in images_path: xml = os.path.join(self.path, annotations, each + '.xml') jpeg = os.path.join(self.path, jpegimages, each + '.jpg') rawData.append([jpeg, xml]) return rawData def GetData(self, index, **kwargs): path_2_image, path_2_xml = self.rawData[index] if self.debug: print(f"image path {path_2_image} || xml path {path_2_xml}") bboxes, fname = ReadXML_VOC_Format(path_2_xml) image = cv2.imread(path_2_image) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) return image, bboxes, fname if __name__ == '__main__': import torch labels = readTxt(os.path.join(PATH, 'config', 'class.names')) path_2_root = r"E:\ProgrammingSkills\python\DEEP_LEARNING\DATASETS\PASCALVOC\VOCdevkit\VOC2012" #path_2_root = r"D:\Code\Dataset\PASCAL-VOOC\VOCtrainval_11-May-2012\VOCdevkit\VOC2012" voc = VOC_data(path= path_2_root,split=0.8, is_train=True, labels=labels, debug=True, draw=1, argument=True) for i, (inp, tar) in enumerate(voc): print('INP max {} min {}'.format(torch.max(inp), torch.min(inp))) print('TAR max {} min {}'.format(torch.max(tar), torch.min(tar))) print(f'{i} / {len(voc)}')
{"/Experiments/voc2012/data.py": ["/Yolov3/Dataset/dataformat.py", "/Yolov3/Dataset/dataset.py"], "/Experiments/voc2012/model.py": ["/Yolov3/Model/yolov3.py"], "/Experiments/voc2012/visualize_data.py": ["/Yolov3/Dataset/dataformat.py"], "/Experiments/voc2012/voc_data.py": ["/Yolov3/Dataset/dataformat.py", "/Yolov3/Dataset/dataset.py"], "/Yolov3/Dataset/dataset.py": ["/Yolov3/Dataset/data_argument.py"], "/Yolov3/Model/yolov3.py": ["/Yolov3/Model/headv3.py"], "/Experiments/simple/debug_network.py": ["/Yolov3/Model/yolov3.py", "/Yolov3/Utils/train_module.py"], "/Experiments/simple/train.py": ["/Yolov3/Utils/train.py"], "/Yolov3/Utils/create_model.py": ["/Yolov3/Model/yolov3.py"], "/Yolov3/Utils/train.py": ["/Yolov3/Utils/train_module.py", "/Yolov3/Utils/args_train.py", "/Yolov3/Dataset/dataset.py", "/Yolov3/Utils/create_model.py"]}
42,035,518
phtvo/yolo
refs/heads/master
/Yolov3/Model/headv3.py
from torchvision import transforms from torch.autograd import Variable import torch.nn as nn import torch from Yolov3.Utils.utils import build_targets from Yolov3.Utils.focal_loss import focal_loss class yoloHeadv3(nn.Module): def __init__(self, anchor, num_classes, img_size, lb_noobj=1.0, lb_obj=1.0, lb_class=1.0, lb_pos=1.0, ignore_thresh = 0.5, use_focal_loss=False, device='cuda' ): """Yolo detection layer Args: anchor ([list]): [list of anchor box] num_classes ([int]): [number of training classes] img_size ([int]): [fixed size image] lb_noobj (float, optional): [No function at this moment]. Defaults to 1.0. lb_obj (float, optional): [No function at this moment]. Defaults to 1.0. lb_class (float, optional): [No function at this moment]. Defaults to 1.0. lb_pos (float, optional): [No function at this moment]. Defaults to 1.0. ignore_thresh (float, optional): [threshold of objecness score]. Defaults to 0.5. """ super(yoloHeadv3, self).__init__() self.anchor = anchor self.num_anchor = len(self.anchor) self.num_classes = num_classes self.img_size = img_size self.grid_info = num_classes + 5 self.ignore_thres = ignore_thresh self.lb_noobj = lb_noobj self.lb_obj = lb_obj self.lb_class = lb_class self.lb_pos = lb_pos self.mse_loss = nn.MSELoss().to(device=device) self.bce_loss = nn.BCELoss().to(device=device) self.class_loss = nn.CrossEntropyLoss().to( device=device) if not use_focal_loss else focal_loss( device=device) if use_focal_loss: print('Compute classification loss by ',self.class_loss.__class__.__name__) self.confidence_points = [0.5, 0.75, 0.85] def calculate_precision(self, nCorrect, _tensor) -> dict: """ Returns: * {rangeA : value , rangeB: value, ...} """ precision = {} for each in self.confidence_points: nProposals = float((_tensor.cpu() > each).sum()) if nProposals > 0: precision.update({ 'P_'+str(each): float(nCorrect/ nProposals)}) else: precision.update({'P_'+str(each): 0}) return precision def forward(self, X, targets=None): """[Feed forward function] Args: X ([tensor]): [input tensor shape (batch_size, 3, img_size, img_size)] targets ([tensor], optional): [tensor shape (batch_size, max_objects, 5 + number of classes)]. Defaults to None. Returns: [{ "mask" : mask, "x" : [x, tx], "y" : [y, ty], "w" : [w, tw], "h" : [h, th], "conf" : [conf, tconf], "class" : [clss, tcls], "recall" : recall, "precision" : precision }]: [Pairs of value to calculate loss function] """ isTrain = True if targets != None else False numBatches = X.size(0) numGrids = X.size(2) ratio = self.img_size / numGrids FloatTensor = torch.cuda.FloatTensor if X.is_cuda else torch.FloatTensor LongTensor = torch.cuda.LongTensor if X.is_cuda else torch.LongTensor BoolTensor = torch.cuda.BoolTensor if X.is_cuda else torch.BoolTensor predict = X.view(numBatches, self.num_anchor, self.grid_info, numGrids, numGrids).permute(0, 1, 3, 4, 2).contiguous() # x = torch.sigmoid(predict[..., 0]) y = torch.sigmoid(predict[..., 1]) w = predict[..., 2] h = predict[..., 3] conf = torch.sigmoid(predict[..., 4]) #clss = torch.sigmoid(predict[..., 5:]) clss = predict[..., 5:] #print(clss) coor_x = torch.arange(numGrids).repeat(numGrids, 1).view( [1, 1, numGrids, numGrids]).type(FloatTensor) coor_y = torch.arange(numGrids).repeat(numGrids, 1).t().view( [1, 1, numGrids, numGrids]).type(FloatTensor) scale_anchors = FloatTensor([(aw/ratio, ah/ratio) for aw, ah in self.anchor]) anchor_x = scale_anchors[:, 0:1].view((1, self.num_anchor, 1, 1)) anchor_y = scale_anchors[:, 1:2].view((1, self.num_anchor, 1, 1)) pred_boxes = FloatTensor(predict[..., :4].shape) pred_boxes[..., 0] = x + coor_x pred_boxes[..., 1] = y + coor_y pred_boxes[..., 2] = torch.exp(w).clamp(max=1E3) * anchor_x pred_boxes[..., 3] = torch.exp(h).clamp(max=1E3) * anchor_y if torch.isnan(conf).any(): print(f'predict size {predict.size()}') print(f'X size {X.size()}') #print(clss) #print(predict[..., 4]) if isTrain: #if x.is_cuda: # self.mse_loss.cuda() # self.class_loss.cuda() # self.bce_loss.cuda() nGT, nCorrect, mask, noobj_mask, tx, ty, tw, th, tconf, tcls = build_targets( pred_boxes=pred_boxes, pred_conf=conf, pred_cls=clss, target=targets, anchors=scale_anchors, num_anchors=self.num_anchor, num_classes=self.num_classes, grid_size=numGrids, ignore_thres=self.ignore_thres, ) recall = float(nCorrect / nGT) if nGT else 1 precision = self.calculate_precision(nCorrect, conf) # Handle masks mask = Variable(mask.type(BoolTensor)) noobj_mask = Variable(noobj_mask.type(BoolTensor)) # Handle target variables tx = Variable(tx.type(FloatTensor), requires_grad=False) ty = Variable(ty.type(FloatTensor), requires_grad=False) tw = Variable(tw.type(FloatTensor), requires_grad=False) th = Variable(th.type(FloatTensor), requires_grad=False) tconf = Variable(tconf.type(FloatTensor), requires_grad=False) tcls = Variable(tcls.type(LongTensor), requires_grad=False) # Mask outputs to ignore non-existing objects loss_x = self.mse_loss(x[mask], tx[mask]) loss_y = self.mse_loss(y[mask], ty[mask]) loss_w = self.mse_loss(w[mask], tw[mask]) loss_h = self.mse_loss(h[mask], th[mask]) loss_conf = self.bce_loss(conf[mask], tconf[mask])*self.lb_obj +\ self.bce_loss(conf[noobj_mask], tconf[noobj_mask])*self.lb_noobj loss_cls = self.class_loss(clss[mask], torch.argmax(tcls[mask], 1)) loss_pos = (loss_x + loss_y + loss_w + loss_h) loss = loss_pos * self.lb_pos + loss_conf + loss_cls*self.lb_class if torch.sum(mask) == 0 or torch.isnan(loss_conf) or torch.isinf(loss_conf): print( f'Target tensor max {torch.max(targets)} | min {torch.min(targets)}') return ( loss, { "total" : loss.item(), "loss_pos": loss_pos.item(), "loss_x" : loss_x.item(), "loss_y" : loss_y.item(), "loss_w" : loss_w.item(), "loss_h" : loss_h.item(), "loss_conf" : loss_conf.item(), "loss_class" : loss_cls.item(), "recall" : recall, **precision } ) else: output = torch.cat( ( pred_boxes.view(numBatches, -1, 4)*ratio, conf.view(numBatches, -1, 1), clss.view(numBatches, -1, self.num_classes), ), -1, ) return output from PIL import Image from Yolov3.Utils.utils import non_max_suppression import numpy as np def detect_image(model, img, classes=80, conf_thres=0.8, nms_thres=0.4, img_size=416, cuda=True): # scale and pad image Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor if isinstance(img, str): img = Image.open(str) w,h = img.size elif isinstance(img, np.ndarray): h, w = img.shape[:2] img = Image.fromarray(img) else: try: w, h = img.size except Exception as e: raise 'Error {} , invalid image type '.format(e.args[-1]) ratio = min(img_size/w, img_size/h) imw = round(w * ratio) imh = round(h * ratio) img_transforms = transforms.Compose([ transforms.Resize((imh, imw)), transforms.Pad((max(int((imh-imw)/2), 0), max(int((imw-imh)/2), 0), max(int((imh-imw)/2), 0), max(int((imw-imh)/2), 0)), (0, 0, 0)), transforms.ToTensor(), ]) image_tensor = img_transforms(img).float() image_tensor = image_tensor.unsqueeze_(0) input_img = Variable(image_tensor.type(Tensor)) with torch.no_grad(): detections = model(input_img) detections = non_max_suppression( detections, classes, conf_thres, nms_thres) img = np.asarray(img) try: pad_x = max(img.shape[0] - img.shape[1], 0) * \ (img_size / max(img.shape)) pad_y = max(img.shape[1] - img.shape[0], 0) * \ (img_size / max(img.shape)) unpad_h = img_size - pad_y unpad_w = img_size - pad_x detections = detections[0] result = detections result[..., 3] = ((detections[..., 3] - pad_y // 2) / unpad_h) * img.shape[0] result[..., 2] = ((detections[..., 2] - pad_x // 2) / unpad_w) * img.shape[1] result[..., 1] = ((detections[..., 1] - pad_y // 2) / unpad_h) * img.shape[0] result[..., 0] = ((detections[..., 0] - pad_x // 2) / unpad_w) * img.shape[1] result = result.data.cpu().tolist() return result except: return None
{"/Experiments/voc2012/data.py": ["/Yolov3/Dataset/dataformat.py", "/Yolov3/Dataset/dataset.py"], "/Experiments/voc2012/model.py": ["/Yolov3/Model/yolov3.py"], "/Experiments/voc2012/visualize_data.py": ["/Yolov3/Dataset/dataformat.py"], "/Experiments/voc2012/voc_data.py": ["/Yolov3/Dataset/dataformat.py", "/Yolov3/Dataset/dataset.py"], "/Yolov3/Dataset/dataset.py": ["/Yolov3/Dataset/data_argument.py"], "/Yolov3/Model/yolov3.py": ["/Yolov3/Model/headv3.py"], "/Experiments/simple/debug_network.py": ["/Yolov3/Model/yolov3.py", "/Yolov3/Utils/train_module.py"], "/Experiments/simple/train.py": ["/Yolov3/Utils/train.py"], "/Yolov3/Utils/create_model.py": ["/Yolov3/Model/yolov3.py"], "/Yolov3/Utils/train.py": ["/Yolov3/Utils/train_module.py", "/Yolov3/Utils/args_train.py", "/Yolov3/Dataset/dataset.py", "/Yolov3/Utils/create_model.py"]}
42,035,519
phtvo/yolo
refs/heads/master
/Yolov3/Dataset/dataset.py
import os import random import cv2 import numpy as np import torch import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import Dataset from .data_argument import custom_aug import matplotlib.pyplot as plt def random_random(v=0.5): if random.random() > 0.5: return True else: return False class yoloCoreDataset(Dataset): def __init__(self, path, labels, # List of labels name img_size= 416, # fixed size image debug=False, argument=True, draw=False, max_objects=10, is_train=True, save_draw_images = False, split=None, ): self.image_aug = custom_aug() self.img_size = img_size self.img_shape = (img_size, img_size) self.argument = argument self.max_objects = max_objects self.debug = debug self.draw = draw self.labels = labels self.path = path self.is_train = is_train self.split = split self.transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) self.denormalize = transforms.Compose([ transforms.Normalize( mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225], std=[1/0.229, 1/0.224, 1/0.255]), ]) self._file = os.path.dirname(__file__) self.rawData = self.InitDataset() self.save_draw_images = save_draw_images def InitDataset(self, **kwargs): """ Init and Read all file names Args: path (str): path to dataset Raises: NotImplementedError: [description] Return: self.rawData -> List:[[image_data, label]] """ raise NotImplementedError() def GetData(self, index, **kwargs): """ Abstract method to get single data with yolo data Args: index ([int]): index element Raises: NotImplementedError: Need to implement in child class Returns: image: np.ndarray bboxes: list fname: name of xml file """ raise NotImplementedError() def content(self, idx, draw): ''' input: idx of self.pairData output: img:np, bbox:np, name:list ''' img, bbox, fname = self.GetData(idx) if self.debug: print(f'file {fname}') print('-> origin: {}'.format(bbox)) Name = [each[0] for each in bbox] name = [self.labels.index(each[0]) for each in bbox] bbox = [each[1:] for each in bbox] #bbox = np.asarray(bbox).astype('float32') if self.is_train: #img, bbox, name = self.image_aug(img, bbox, name) if random_random(0.6): img, bbox, name = self.image_aug(img, bbox, name) else: bbox = np.asarray(bbox) else: bbox = np.asarray(bbox) if self.debug: print(f' ---> after aug: {bbox} {type(bbox)}') h, w = img.shape[:2] # dim_diff = np.abs(h - w) # Upper (left) and lower (right) padding pad1, pad2 = dim_diff // 2, dim_diff // 2 # Determine padding pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ( (0, 0), (pad1, pad2), (0, 0)) # Add padding input_img = np.pad(img.copy(), pad, 'constant', constant_values=0) padded_h, padded_w, _ = input_img.shape img = cv2.resize(input_img, self.img_shape) H, W = img.shape[:2] # new image shape bbox[:, 0] = (bbox[:, 0] + pad[1][0]) * 1 / (padded_w / W) bbox[:, 2] = (bbox[:, 2] + pad[1][0]) * 1 / (padded_w / W) bbox[:, 1] = (bbox[:, 1] + pad[0][0]) * 1 / (padded_h / H) bbox[:, 3] = (bbox[:, 3] + pad[0][0]) * 1 / (padded_h / H) bbox = np.asarray(bbox).astype(float) _bbox = bbox.copy() bbox[:, 0] = ((_bbox[:, 0] + _bbox[:, 2]) / 2) * 1 / W # xc bbox[:, 1] = ((_bbox[:, 1] + _bbox[:, 3]) / 2) * 1 / H # yc bbox[:, 2] = (_bbox[:, 2] - _bbox[:, 0]) * 1 / W # w bbox[:, 3] = (_bbox[:, 3] - _bbox[:, 1]) * 1 / H # h name = np.asarray(name).astype('float32') name = np.expand_dims(name, axis=0) label = np.concatenate((name.T, bbox), axis=1) if self.debug: print(f' ---> cvt label: {label}') if self.draw: self.drawConvertedAnnotation(img, label, fname, save=self.save_draw_images) return img, label, Name def __getitem__(self, index): img, labels, name = self.content(index, draw=self.draw) input_img = self.transform(img.copy()/255.0).float() labels = labels.reshape(-1, 5) # Fill matrix filled_labels = np.zeros((self.max_objects, 5)) if labels is not None: filled_labels[range(len(labels))[:self.max_objects] ] = labels[:self.max_objects] filled_labels = torch.from_numpy(filled_labels) if self.debug: print('final label ', filled_labels) return input_img, filled_labels def __len__(self): return len(self.rawData) def drawConvertedAnnotation(self, image, labels, fname, save=False): H, W = image.shape[:2] t_image = image.copy() for i in range(len(labels)): name, xc, yc, w, h = labels[i] x1 = int((xc - w/2)*W) y1 = int((yc - h/2)*H) x2 = int((xc + w/2)*W) y2 = int((yc + h/2)*H) print(f'pseudo {(x1, y1, x2, y2)}') cv2.rectangle(t_image, (x1, y1), (x2, y2), (0, 255, 255), 2, 1) cv2.putText(t_image, str(self.labels[int(name)]), (x1+10, y1+10 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 5), 2) if not save: plt.imshow(t_image) plt.show() else: t_image = cv2.cvtColor(t_image, cv2.COLOR_RGB2BGR) cv2.imwrite(os.path.join(self._file, "Test", "data", fname+'.jpg'))
{"/Experiments/voc2012/data.py": ["/Yolov3/Dataset/dataformat.py", "/Yolov3/Dataset/dataset.py"], "/Experiments/voc2012/model.py": ["/Yolov3/Model/yolov3.py"], "/Experiments/voc2012/visualize_data.py": ["/Yolov3/Dataset/dataformat.py"], "/Experiments/voc2012/voc_data.py": ["/Yolov3/Dataset/dataformat.py", "/Yolov3/Dataset/dataset.py"], "/Yolov3/Dataset/dataset.py": ["/Yolov3/Dataset/data_argument.py"], "/Yolov3/Model/yolov3.py": ["/Yolov3/Model/headv3.py"], "/Experiments/simple/debug_network.py": ["/Yolov3/Model/yolov3.py", "/Yolov3/Utils/train_module.py"], "/Experiments/simple/train.py": ["/Yolov3/Utils/train.py"], "/Yolov3/Utils/create_model.py": ["/Yolov3/Model/yolov3.py"], "/Yolov3/Utils/train.py": ["/Yolov3/Utils/train_module.py", "/Yolov3/Utils/args_train.py", "/Yolov3/Dataset/dataset.py", "/Yolov3/Utils/create_model.py"]}