repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
arkangel-dev/blender-universal-file-import
ImportAllFiles.py
<gh_stars>0 # SPDX-License-Identifier: GPL-2.0-or-later # <pep8 compliant> bl_info = { "name": "Import All File Types", "author": "Sambo", "version": (0, 0, 1), "blender": (3, 0, 1), "location": "File > Import > Import File", "description": "Import files into the scene based on the file format", "warning": "", "support": 'OFFICIAL', "category": "Import-Export", } from cProfile import label from cgitb import text from email.policy import default from msilib.schema import Icon from operator import iconcat from unicodedata import name from wsgiref import validate import bpy from bpy_extras.io_utils import ImportHelper def read_some_data(context, filepath, ): file_extension = filepath.split('.')[-1] bpy.types.Scene.targeted_file = filepath if (file_extension.lower() in ['dae']): bpy.ops.wm.uni_import_collada('INVOKE_DEFAULT') if (file_extension.lower() in ['abc']): bpy.ops.wm.uni_import_alembic('INVOKE_DEFAULT') if (file_extension.lower() in ['usd', 'usda', 'usdc']): bpy.ops.wm.uni_import_usd('INVOKE_DEFAULT') if (file_extension.lower() in ['svg']): bpy.ops.wm.uni_import_svggp('INVOKE_DEFAULT') return {'FINISHED'} class WM_OT_ImportCollada(bpy.types.Operator): bl_label = "Import Collada File" bl_idname = "wm.uni_import_collada" def execute(self, context): print("Importing " + bpy.types.Scene.targeted_file) bpy.ops.wm.collada_import( filepath=bpy.types.Scene.targeted_file, import_units=context.scene.collada_import_units, fix_orientation=context.scene.collada_fix_leaf_bones, auto_connect=context.scene.collada_auto_correct, min_chain_length=context.scene.collada_minimum_chain_length, find_chains=context.scene.collada_find_bone_chains) return {'FINISHED'} def invoke(self, context, event): return context.window_manager.invoke_props_dialog(self) def draw(self, context): layout = self.layout import_data_options = layout.box() import_data_options.label(text='Import Data Options', icon='MESH_DATA') import_data_options.prop(context.scene, 'collada_import_units') armature_options = layout.box() armature_options.label(text="Armature Options", icon='ARMATURE_DATA') col = armature_options.column() col.prop(context.scene, 'collada_fix_leaf_bones') col.prop(context.scene, 'collada_find_bone_chains') col.prop(context.scene, 'collada_auto_correct') col.prop(context.scene, 'collada_minimum_chain_length') last_box = layout.box() last_box.prop(context.scene, 'collada_keep_bind_info') class WM_OT_ImportAlembic(bpy.types.Operator): bl_label = "Import Alembic File" bl_idname = "wm.uni_import_alembic" def execute(self, context): bpy.ops.wm.alembic_import( filepath=context.scene.targeted_file, relative_path=context.scene.alembic_relative_path, set_frame_range=context.scene.alembic_set_frame_range, is_sequence=context.scene.alembic_is_sequence, validate_meshes=context.scene.alembic_validate_meshes, always_add_cache_reader=context.scene.alembic_always_add_cache_reader ) return {'FINISHED'} def invoke(self, context, event): return context.window_manager.invoke_props_dialog(self) def draw(self, context): layout = self.layout manual_transform_box = layout.box() manual_transform_box.label(text="Manual Transform") manual_transform_box.prop(context.scene, 'alembic_scale') options_box = layout.box() options_box.label(text='Options') options_box_col = options_box.column() options_box_col.prop(context.scene, 'alembic_relative_path') options_box_col.prop(context.scene, 'alembic_set_frame_range') options_box_col.prop(context.scene, 'alembic_is_sequence') options_box_col.prop(context.scene, 'alembic_validate_meshes') options_box_col.prop(context.scene, 'alembic_always_add_cache_reader') class WM_OT_ImportUniversalSceneDescription(bpy.types.Operator): bl_label = "Import USD File" bl_idname = "wm.uni_import_usd" def execute(self, context): bpy.ops.wm.usd_import( filepath=context.scene.targeted_file, import_cameras=context.scene.usd_dt_camera, import_curves=context.scene.usd_dt_curves, import_lights=context.scene.usd_dt_lights, import_materials=context.scene.usd_dt_materials, import_meshes=context.scene.usd_dt_meshes, import_volumes=context.scene.usd_dt_volumes, prim_path_mask=context.scene.usd_path_mask, scale=context.scene.usd_scale, read_mesh_uvs=context.scene.usd_md_uv_coords, read_mesh_colors=context.scene.usd_md_vertex_colors, import_subdiv=context.scene.usd_md_incl_subdivision, import_instance_proxies=context.scene.usd_md_incl_import_instance_proxies, import_visible_only=context.scene.usd_md_incl_visible_primitives_only, import_guide=context.scene.usd_md_incl_guide, import_proxy=context.scene.usd_md_incl_proxy, import_render=context.scene.usd_md_incl_render, set_frame_range=context.scene.usd_md_opt_set_frame_range, relative_path=context.scene.usd_md_opt_relative_path, create_collection=context.scene.usd_md_opt_collection, light_intensity_scale=context.scene.usd_md_light_intensity_scale, import_usd_preview=context.scene.usd_md_exp_import_usd_preview, set_material_blend=context.scene.usd_md_exp_set_material_blend ) return {'FINISHED'} def invoke(self, context, event): return context.window_manager.invoke_props_dialog(self) def draw(self, context): layout = self.layout first_box = layout.box() first_box_first_row = first_box.row() data_types_label_col = first_box_first_row.column() data_types_checkbox_col = first_box_first_row.column() data_types_label_col.label(text='Data Type') data_types_checkbox_col.prop(context.scene, 'usd_dt_camera') data_types_checkbox_col.prop(context.scene, 'usd_dt_curves') data_types_checkbox_col.prop(context.scene, 'usd_dt_lights') data_types_checkbox_col.prop(context.scene, 'usd_dt_materials') data_types_checkbox_col.prop(context.scene, 'usd_dt_meshes') data_types_checkbox_col.prop(context.scene, 'usd_dt_volumes') first_box.prop(context.scene, 'usd_path_mask') first_box.prop(context.scene, 'usd_scale') second_box = layout.box() mesh_data_row = second_box.row() mesh_data_label_col = mesh_data_row.column() mesh_data_checkbox_col = mesh_data_row.column() mesh_data_label_col.label(text='Mesh Data') mesh_data_checkbox_col.prop(context.scene, 'usd_md_uv_coords') mesh_data_checkbox_col.prop(context.scene, 'usd_md_vertex_colors') include_row = second_box.row() include_label_col = include_row.column() include_checkbox_col = include_row.column() include_label_col.label(text='Include') include_checkbox_col.prop(context.scene, 'usd_md_incl_subdivision') include_checkbox_col.prop(context.scene, 'usd_md_incl_import_instance_proxies') include_checkbox_col.prop(context.scene, 'usd_md_incl_visible_primitives_only') include_checkbox_col.prop(context.scene, 'usd_md_incl_guide') include_checkbox_col.prop(context.scene, 'usd_md_incl_proxy') include_checkbox_col.prop(context.scene, 'usd_md_incl_render') options_row = second_box.row() options_row_label_col = options_row.column() options_row_checkbox_col = options_row.column() options_row_label_col.label(text='Options') options_row_checkbox_col.prop(context.scene, 'usd_md_opt_set_frame_range') options_row_checkbox_col.prop(context.scene, 'usd_md_opt_relative_path') options_row_checkbox_col.prop(context.scene, 'usd_md_opt_collection') second_box.prop(context.scene, 'usd_md_light_intensity_scale') # Third Box third_box = layout.box() experimental_row = third_box.row() experimental_row_label_col = experimental_row.column() experimental_row_checkbox_col = experimental_row.column() experimental_row_label_col.label(text='Experimental') experimental_row_checkbox_col.prop(context.scene, 'usd_md_exp_import_usd_preview') experimental_row_checkbox_col.prop(context.scene, 'usd_md_exp_set_material_blend') class WM_OT_ImportSVGAsGreasePencil(bpy.types.Operator): bl_label = "Import SVG as Grease Pencil" bl_idname = "wm.uni_import_svggp" def execute(self, context): bpy.ops.wm.gpencil_import_svg( filepath=context.scene.targeted_file, resolution=context.scene.svg_gp_resolution, scale=context.scene.svg_gp_scale) return {'FINISHED'} def invoke(self, context, event): return context.window_manager.invoke_props_dialog(self) def draw(self, context): layout = self.layout layout.prop(context.scene, 'svg_gp_resolution') layout.prop(context.scene, 'svg_gp_scale') class TEST_OT_ImportSomeData(bpy.types.Operator, ImportHelper): bl_label = "Import Some Data" bl_idname = "import_test.some_data" def execute(self, context): return read_some_data(context, self.filepath, ) def view3d_menu_add(self, context, ): self.layout.separator() self.layout.operator("import_test.some_data", text='Import File', icon='FILEBROWSER') def register(): bpy.utils.register_class(TEST_OT_ImportSomeData) bpy.utils.register_class(WM_OT_ImportCollada) bpy.utils.register_class(WM_OT_ImportAlembic) bpy.utils.register_class(WM_OT_ImportUniversalSceneDescription) bpy.utils.register_class(WM_OT_ImportSVGAsGreasePencil) bpy.types.TOPBAR_MT_file_import.append(view3d_menu_add) bpy.types.Scene.targeted_file = "" # Collada bpy.types.Scene.collada_import_units = bpy.props.BoolProperty(name = 'Import Units', description="If disabled match import to Blender's current Unit settings, otherwise use the settings from the Imported scene", default=False) bpy.types.Scene.collada_fix_leaf_bones = bpy.props.BoolProperty(name="Fix Leaf Bones", description="Fix Orientation of Leaf Bones (Collada does only support joints)") bpy.types.Scene.collada_find_bone_chains = bpy.props.BoolProperty(name="Find Bone Chains", description="Find best matching Bone Chains and ensure bones in chain are connected") bpy.types.Scene.collada_auto_correct = bpy.props.BoolProperty(name="Auto Correct", description="set use_connect for parent bones which have exactly one child bone") bpy.types.Scene.collada_minimum_chain_length = bpy.props.IntProperty(name="Minimum Chain Length", description="When searching Bone Chains disregard chains of length below this value") bpy.types.Scene.collada_keep_bind_info = bpy.props.BoolProperty(name="Keep Bind Info", description="Sotre Bindpose information in custom bone properties for later use during Collada export") # Alembic bpy.types.Scene.alembic_scale = bpy.props.FloatProperty(name = 'Scale', description='Value by which to enlarge or shrink the objects with respect to the worlds origin') bpy.types.Scene.alembic_relative_path = bpy.props.BoolProperty(name = 'Relative Path', description='Select the relative to the blend file') bpy.types.Scene.alembic_set_frame_range = bpy.props.BoolProperty(name='Set Frame Range', description='If checked, update scenes start and end frame to match those of the Alembic archive') bpy.types.Scene.alembic_is_sequence = bpy.props.BoolProperty(name='Is Sequence', description='Set to true if the cache is split into separate files') bpy.types.Scene.alembic_validate_meshes = bpy.props.BoolProperty(name='Validate Meshes', description='Check imported mesh objects for invalid data (slow)') bpy.types.Scene.alembic_always_add_cache_reader = bpy.props.BoolProperty(name='Always Add Cache Reader', description='Add cache modifiers and constraints to imported objects even if they are not animated so they can be updated when reloading the Alembic archive') # Universal Scene Description bpy.types.Scene.usd_dt_camera = bpy.props.BoolProperty(name='Cameras', default=True) bpy.types.Scene.usd_dt_curves = bpy.props.BoolProperty(name='Curves', default=True) bpy.types.Scene.usd_dt_lights = bpy.props.BoolProperty(name='Lights', default=True) bpy.types.Scene.usd_dt_materials = bpy.props.BoolProperty(name='Materials', default=True) bpy.types.Scene.usd_dt_meshes = bpy.props.BoolProperty(name='Meshes', default=True) bpy.types.Scene.usd_dt_volumes = bpy.props.BoolProperty(name='Volume', default=True) bpy.types.Scene.usd_path_mask = bpy.props.StringProperty(name='Path Mask', description='Import only the subset of the USD scene rooted at the given primitive') bpy.types.Scene.usd_scale = bpy.props.FloatProperty(name='Scale', description='Value by which to enlarge or shrink the objects with respect to the worlds origin') bpy.types.Scene.usd_md_uv_coords = bpy.props.BoolProperty(name='UV Coordinates', description='Read mesh UV coordinates', default=True) bpy.types.Scene.usd_md_vertex_colors = bpy.props.BoolProperty(name='Vertex Colors', description='Read mesh vertex colors') bpy.types.Scene.usd_md_incl_subdivision = bpy.props.BoolProperty(name='Visible Primitives Only', description='') bpy.types.Scene.usd_md_incl_import_instance_proxies = bpy.props.BoolProperty(name='Import Instance Proxies', description='Create unique Blender objects for USd instances', default=True) bpy.types.Scene.usd_md_incl_visible_primitives_only = bpy.props.BoolProperty(name='Visible primitives only', description='Do not import invisible USD primitives. Only applies to primitives with a non-animated visibility attribute. Primitives with animated visibility will always be imported', default=True) bpy.types.Scene.usd_md_incl_guide = bpy.props.BoolProperty(name='Guide', description='Import guide geometry') bpy.types.Scene.usd_md_incl_proxy = bpy.props.BoolProperty(name='Proxy', description='Import proxy geometry', default=True) bpy.types.Scene.usd_md_incl_render = bpy.props.BoolProperty(name='Render', description='Import final render geometry', default=True) bpy.types.Scene.usd_md_opt_set_frame_range = bpy.props.BoolProperty(name='Set Frame range', description='Update the scenes start and end frame to match those of hte USD archive', default=True) bpy.types.Scene.usd_md_opt_relative_path = bpy.props.BoolProperty(name='Relative Path', description='Select the file relative to the blend file', default=True) bpy.types.Scene.usd_md_opt_collection = bpy.props.BoolProperty(name='Create Collection', description='Add all objects to a new collection') bpy.types.Scene.usd_md_light_intensity_scale = bpy.props.FloatProperty(name='Light Intensity Scale', description='Scale for the intensity of imported lights', default=1) bpy.types.Scene.usd_md_exp_import_usd_preview = bpy.props.BoolProperty(name='Import USD Preview', description='Convert UsdPreviewSurface shaders to Principled BSDF shader networks') bpy.types.Scene.usd_md_exp_set_material_blend = bpy.props.BoolProperty(name='Set Material Blender', description='If the Import USD Preview option is enabled, the material blender method will automatically be set based on the shaders opacity and opacityThreshold inputs', default=True) # Import SVG as Grease Pencil bpy.types.Scene.svg_gp_resolution = bpy.props.IntProperty(name='Resolution', description='Resolution of the generated strokes', default=10) bpy.types.Scene.svg_gp_scale = bpy.props.FloatProperty(name='Scale', description='Scale of the final strokes', default=10.0) def unregister(): bpy.types.TOPBAR_MT_file_import.remove(view3d_menu_add) bpy.types.VIEW3D_MT_add.remove(view3d_menu_add) bpy.utils.unregister_class(TEST_OT_ImportSomeData) bpy.utils.unregister_class(WM_OT_ImportCollada) bpy.utils.unregister_class(WM_OT_ImportAlembic) bpy.utils.unregister_class(WM_OT_ImportUniversalSceneDescription) bpy.utils.unregister_class(WM_OT_ImportSVGAsGreasePencil) if __name__ == "__main__": register()
Duologic/ansible-role-uwsgi
molecule/default/tests/test_installation.py
""" Role tests """ import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): """ Check if packages are installed """ packages = [] if host.system_info.distribution in ('debian', 'ubuntu'): packages = ['uwsgi', 'uwsgi-plugin-python', 'uwsgi-plugin-python3'] for package in packages: assert host.package(package).is_installed def test_configuration_file(host): """ Check configuration files properties """ if host.system_info.distribution not in ('debian', 'ubuntu'): pytest.skip('Not apply to %s' % host.system_info.distribution) config_file = host.file('/etc/uwsgi/apps-available/default.yml') assert config_file.exists assert config_file.is_file config_link = host.file('/etc/uwsgi/apps-enabled/default.yml') assert config_link.exists assert config_link.is_symlink assert config_link.linked_to == '/etc/uwsgi/apps-available/default.yml' def test_run_files(host): """ Check run files properties """ if host.system_info.distribution not in ('debian', 'ubuntu'): pytest.skip('Not apply to %s' % host.system_info.distribution) pid_file = host.file('/var/run/uwsgi/app/default/pid') assert pid_file.exists assert pid_file.is_file socket_file = host.file('/var/run/uwsgi/app/default/socket') assert socket_file.exists assert socket_file.is_socket assert socket_file.mode == 0o660 def test_service(host): """ Test service started and enabled """ service = '' if host.system_info.distribution in ('debian', 'ubuntu'): service = host.service('uwsgi') assert service.is_enabled assert service.is_running
V3LKR0W/CScouter
CScouter.py
import requests, time, os from colorit import * from dotenv import load_dotenv, dotenv_values init_colorit() load_dotenv() Config = dotenv_values('.env') Players = [] kills = [] deaths = [] wins = [] surrenders = [] w = [] s = [] cs = [] a = [] try: Req = requests.get('https://127.0.0.1:2999/liveclientdata/allgamedata', verify=False).json() except Exception: print(color('Couldn\'t find a connection to the local server.', Colors.red)) for Player in Req['allPlayers']: getSummonerUsername = requests.get(f'https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/{Player["summonerName"]}?api_key={Config["API_KEY"]}').json() Players.append(dict( name=getSummonerUsername['name'], id=getSummonerUsername['puuid'], current_champion=Player['championName'], level=0, games=[], kill_arry=[], avg_kills=0, death_arry=[], avg_deaths=0, wins_arry=[], avg_wins=0, surrenders_arry=[], avg_surrenders=0, cs_arry=[], avg_cs=0, assists_arry=[], avg_assists=0, )) for x in range(len(Players)): games = requests.get(f'https://americas.api.riotgames.com/lol/match/v5/matches/by-puuid/{Players[x]["id"]}/ids?type=normal&start=0&count={Config["Count"]}&api_key={Config["API_KEY"]}').json() Players[x]['games'] = games def find_avg(table,store): for x in range(len(Players)): tble = Players[x][str(table)] ans = sum(tble) / int(Config['Count']) Players[x][str(store)] = int(ans) def total(table, store): for x in range(len(Players)): tble = Players[x][str(table)] ans = sum(tble) Players[x][str(store)] = int(ans) for i in range(len(Players)): for Games in Players[i]['games']: Match = requests.get(f'https://americas.api.riotgames.com/lol/match/v5/matches/{Games}?api_key={Config["API_KEY"]}').json() try: for z in range(len(Match['info']['participants'])): if Match['info']['participants'][z]['summonerName'] == Players[i]['name']: kills.append(Match['info']['participants'][z]['kills']) a.append(Match['info']['participants'][z]['assists']) deaths.append(Match['info']['participants'][z]['deaths']) wins.append(Match['info']['participants'][z]['win']) surrenders.append(Match['info']['participants'][z]['gameEndedInSurrender']) cs.append(Match['info']['participants'][z]['totalMinionsKilled']) Players[i]['level'] = Match['info']['participants'][z]['summonerLevel'] Players[i]['kill_arry'] = kills.copy() Players[i]['assists_arry'] = kills.copy() Players[i]['death_arry'] = deaths.copy() Players[i]['wins_arry'] = wins.copy() Players[i]['surrenders_arry'] = surrenders.copy() Players[i]['cs_arry'] = cs.copy() except: print(color('Ratelimit hit. Retrying in 40 seconds..', Colors.red)) time.sleep(40) pass deaths.clear() wins.clear() kills.clear() wins.clear() surrenders.clear() cs.clear() a.clear() find_avg('kill_arry','avg_kills') find_avg('death_arry','avg_deaths') find_avg('cs_arry', 'avg_cs') find_avg('assists_arry', 'avg_assists') total('wins_arry', 'avg_wins') total('surrenders_arry', 'avg_surrenders') # Final Output os.system('cls') for x in range(len(Players)): print(color(f'{Players[x]["current_champion"]} - {Players[x]["name"]} - Level ({Players[x]["level"]}) \n Averages {Players[x]["avg_kills"]} kills per game. \n Averages {Players[x]["avg_deaths"]} deaths per game. \n Averages {Players[x]["avg_assists"]} assists per game. \n {Players[x]["avg_wins"]}/{Config["Count"]} have games been wins and {Players[x]["avg_surrenders"]} games were ended early by FF. \n They have an average CS score of {Players[x]["avg_cs"]}', Colors.blue)) print(color('--------------------', Colors.purple)) print(color(f'All stats are based off the players last {Config["Count"]}. You Can change this in the ".env" file.', Colors.red))
bhamlin/tripping-octo-nemesis
make-pyimg.py
#!/usr/bin/env python import argparse import os import zipfile parser = argparse.ArgumentParser() parser.add_argument('output', help='Name of executable to create') parser.add_argument('source', help='Path to find sources') args = parser.parse_args() IMG = os.path.abspath(args.output) with open(IMG, 'w') as fh: fh.write('#!/usr/bin/env python\n') os.chdir(args.source) with zipfile.ZipFile(IMG, 'a', zipfile.ZIP_DEFLATED) as fh: for raw_path, _, names in os.walk('./'): if raw_path == '.': path = '' else: path = raw_path[2:] for name in names: file = os.path.join(path, name) fh.write(file) os.chmod(IMG, 0755)
bhamlin/tripping-octo-nemesis
src/__main__.py
<reponame>bhamlin/tripping-octo-nemesis #!/usr/bin/env python import argparse import sys LIST_MODULES = 'list-modules' AP = argparse.ArgumentParser('ffxi-tools', description='Tools for modifying the Darkstar database') AP.add_argument('-c', '--config', default='/etc/darkstar/', dest='config', metavar='PATH', help='Path for Darkstar config (Default: /etc/darkstar/)') AP.add_argument('module', nargs='?', help='Module to use, or "%s" to see a list of available modules' % (LIST_MODULES)) AP.add_argument('options', nargs='*', help='Module options, or --help to get help on that module') help = False raw_args = list() for arg in sys.argv[1:]: if arg.lower() in ('--help', '-h'): help = True else: raw_args.append(arg) args = AP.parse_args(raw_args) if not args.module: AP.print_help() exit() import modules import db db.load_config(args.config) if modules.has_module(args.module): module = modules.get_module(args.module) if help: module.START(db, '--help', *args.options) else: module.START(db, *args.options) else: print 'Module named "%s" not found.' % (args.module)
bhamlin/tripping-octo-nemesis
src/modules/set_position.py
MODULE_NAME = 'set-position' MODULE_DESC = 'Move a character to its homepoint, or to another set location' MODULE_VER = '1.0' def START(db, *args): """Remove Darkstar account sessions""" class Position(object): def __init__(self, rot, x, y, z, zone): self.rot = rot self.x = x self.y = y self.z = z self.zone = zone NATIONS = ['sandoria', 'bastok', 'windurst'] LOCATIONS = { NATIONS[0]: Position( 18, 151.910, -2.212, 156.489, 230), NATIONS[1]: Position( 63, -189.633, -8.000, -25.075, 235), NATIONS[2]: Position( 38, -95.999, -5.001, 63.763, 241), 'jeuno': Position(176, 339.849, 20.522, 583.528, 110), # LOL 'jormungand': Position(220, -203.895, -175.281, 144.767, 5), } CHOICES = ['home', 'by-nation'] CHOICES += LOCATIONS.keys() import argparse AP = argparse.ArgumentParser('ffxi-tools ' + MODULE_NAME, description='Move a character to its homepoint, or to another set location') AP.add_argument('character', metavar='character_name', help='The character to move') AP.add_argument('location', metavar='location', choices=CHOICES, default=CHOICES[0], help='Locations must be one of: "%s". Default is "%s".' % ('", "'.join(CHOICES), CHOICES[0])) args = AP.parse_args(args=args) charid = db.get(''' select charid, charname from chars where lower(charname) = '%s' ''' % (args.character.lower(),)) if not charid: print 'No character found by name', args.character return else: charname = charid[0][1] charid = charid[0][0] session = db.get(''' select charid from accounts_sessions sess where charid = %s '''.strip() % (charid,)) if session: print 'Character', charname, 'has a current session, not modifying position' return # If there is a character with that name, # and no existing session for that character, # proceed with the move location = CHOICES[0] if args.location == CHOICES[1]: nationid = int((db.get(''' select nation from chars where charid = '%s' ''' % (charid,)))[0][0]) if nationid > len(NATIONS): print 'Unknown nation value', nationid return location = NATIONS[nationid] else: location = args.location if location == 'home': sql = ''' update chars set pos_rot=home_rot, pos_zone=home_zone, pos_x=home_x, pos_y=home_y, pos_z=home_z where charid = %s '''.strip() % (charid,) db.run(sql) print charname, 'sent to home point' elif location in CHOICES[2:]: pos = LOCATIONS[location] sql = ''' update chars set pos_rot=%s, pos_zone=%s, pos_x=%s, pos_y=%s, pos_z=%s where charid = %s '''.strip() % (pos.rot, pos.zone, pos.x, pos.y, pos.z, charid,) db.run(sql) print charname, 'sent to', location else: # How did you even get here? print 'There is no', args.location
bhamlin/tripping-octo-nemesis
src/db/__init__.py
import MySQLdb as __M __CONFIG = dict() def load_config(path): import os conf_dir = os.path.abspath(os.path.expanduser(path)) for filename in os.listdir(conf_dir): conf_file, _ = filename.split('.') CURRENT = dict() with open(os.path.join(conf_dir, filename), 'r') as fh: for line in fh: line = line.strip() if line.startswith('#') or line.startswith('//'): line = None if line and ':' in line: key, value = line.split(':', 1) key = key.strip().lower() value = value.strip() try: value = int(value) except: pass CURRENT[key] = value if CURRENT: __CONFIG[conf_file] = CURRENT def get(query, columns=None): _L = __CONFIG['login_darkstar'] host = _L['mysql_host'] port = _L['mysql_port'] user = _L['mysql_login'] passwd = _L['<PASSWORD>'] dbname = _L['mysql_database'] pass db = __M.connect(host=host, port=port, user=user, passwd=<PASSWORD>, db=dbname, conv={ __M.FIELD_TYPE.LONG: int }) cur = db.cursor() cur.execute(query) if not columns: output = cur.fetchall() else: output = list() for row in cur.fetchall(): output.append(dict(zip(columns, row))) cur.close() db.close() return output def run(query, columns=None): _L = __CONFIG['login_darkstar'] host = _L['mysql_host'] port = _L['mysql_port'] user = _L['mysql_login'] passwd = _L['<PASSWORD>'] dbname = _L['mysql_database'] pass db = __M.connect(host=host, port=port, user=user, passwd=<PASSWORD>, db=dbname, conv={ __M.FIELD_TYPE.LONG: int }) cur = db.cursor() cur.execute(query) cur.close() db.close()
bhamlin/tripping-octo-nemesis
src/modules/list_accounts.py
MODULE_NAME = 'list-accounts' MODULE_DESC = 'List accounts on server' MODULE_VER = '1.0' def START(db, *args): """List FFXI accounts in the database""" import argparse AP = argparse.ArgumentParser('ffxi-tools ' + MODULE_NAME, description='Lists accounts') args = AP.parse_args(args=args) logins = db.get('select id, login from accounts order by login', ('accid', 'login')); if logins: print 'accid login' print '----- -----' for login in logins: print '%-16s %s' % (login['accid'], login['login']) else: print 'No accounts found'
bhamlin/tripping-octo-nemesis
src/modules/close_session.py
MODULE_NAME = 'close-session' MODULE_DESC = "Remove an account's session" MODULE_VER = '1.0' def START(db, *args): """Remove Darkstar account sessions""" import argparse AP = argparse.ArgumentParser('ffxi-tools ' + MODULE_NAME, description='Removes a session') AP.add_argument('login', metavar='login_name', help='The login for the account') args = AP.parse_args(args=args) sessions = db.get(''' select acc.login, c.charname from accounts_sessions sess left join accounts acc on sess.accid = acc.id left join chars c on sess.charid = c.charid '''.strip(), ('login', 'character')) if sessions and args.login in str(sessions): print 'Removing session for', args.login, '...', db.run(''' delete from accounts_sessions where accid = (select id from accounts where login = '%s') '''.strip() % (args.login,)) print 'Removed' else: print 'No session found for account', args.login
bhamlin/tripping-octo-nemesis
src/modules/__init__.py
<gh_stars>0 import pkgutil as __p import sys as __s __self = __s.modules['modules'] # Find self; very zen __available = dict() def _get_all_modules(): """Return all modules found""" return __available def get_module(name): """Return the named module""" return __available[name] def has_module(name): """Returns True if module exists""" return name in __available # Harrass python into finding all submodules of the module 'modules' for _, modname, ispkg in __p.iter_modules(__self.__path__): # Attempt to import the found module q = __import__('modules.' + modname, globals(), locals(), ['MODULE_NAME', 'MODULE_DESC', 'MODULE_VER'], -1) # If it's one of our modules we've found... if 'MODULE_NAME' in dir(q) and q.MODULE_NAME: if 'MODULE_DESC' in dir(q) and 'MODULE_VER' in dir(q): # Add it to the list of available ones __available[q.MODULE_NAME] = q del modname del ispkg del q
bhamlin/tripping-octo-nemesis
src/modules/list_modules_desc.py
<filename>src/modules/list_modules_desc.py MODULE_NAME = 'list-modules' MODULE_DESC = 'List available modules' MODULE_VER = '1.0' def START(db, *args): """List modules found by python""" import argparse AP = argparse.ArgumentParser('ffxi-tools ' + MODULE_NAME, description='List available modules') args = AP.parse_args(args=args) import sys modules = sys.modules['modules']._get_all_modules() mlist = modules.keys() mlist.sort() print for name in mlist: module = modules[name] print name, '-', module.MODULE_DESC, '[ version:', module.MODULE_VER, ']' print
bhamlin/tripping-octo-nemesis
src/modules/list_sessions.py
<filename>src/modules/list_sessions.py MODULE_NAME = 'list-sessions' MODULE_DESC = 'List sessions active in the database' MODULE_VER = '1.0' def START(db, *args): """Remove Darkstar account sessions""" import argparse AP = argparse.ArgumentParser('ffxi-tools ' + MODULE_NAME, description='Lists active sessions') args = AP.parse_args(args=args) sessions = db.get(''' select acc.login, c.charname from accounts_sessions sess left join accounts acc on sess.accid = acc.id left join chars c on sess.charid = c.charid '''.strip(), ('login', 'character')) if sessions: print 'login character' print '----- ---------' for session in sessions: print '%-16s %s' % (session['login'], session['character']) else: print 'No sessions found'
Ygshvr/marketplace-k8s-app-tools
marketplace/deployer_util/validate_app_resource.py
#!/usr/bin/env python3 # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function from argparse import ArgumentParser import json from yaml_util import load_resources_yaml from resources import find_application_resource import schema_values_common _PROG_HELP = """ Extract the Application resource from the input manifests and validate its correctness, such as Marketplace partner and solution ID annotations, application version and its declared value in the schema. """ def main(): parser = ArgumentParser(description=_PROG_HELP) schema_values_common.add_to_argument_parser(parser) parser.add_argument( '--manifests', required=True, help='The yaml file containing all resources') args = parser.parse_args() schema = schema_values_common.load_schema(args) resources = load_resources_yaml(args.manifests) app = find_application_resource(resources) mp_deploy_info = app.get('metadata', {}).get( 'annotations', {}).get('marketplace.cloud.google.com/deploy-info') if not mp_deploy_info: raise Exception('Application resource is missing ' '"marketplace.cloud.google.com/deploy-info" annotation') validate_deploy_info_annotation(mp_deploy_info, schema) version = app.get('spec', {}).get('descriptor', {}).get('version') if not version or not isinstance(version, str): raise Exception( 'Application resource must have a valid spec.descriptor.version value') if schema.is_v2(): published_version = schema.x_google_marketplace.published_version if version != published_version: raise Exception( 'Application resource\'s spec.descriptor.version "{}" does not match ' 'schema.yaml\'s publishedVersion "{}"'.format(version, published_version)) def validate_deploy_info_annotation(content, schema=None): try: parsed = json.loads(content) if 'partner_id' not in parsed: raise Exception('marketplace.cloud.google.com/deploy-info annotation ' 'on the Application resource must contain a partner_id') if 'solution_id' not in parsed: raise Exception('marketplace.cloud.google.com/deploy-info annotation ' 'on the Application resource must contain a solution_id') if (schema and schema.x_google_marketplace and schema.x_google_marketplace.partner_id): if (parsed['partner_id'] != schema.x_google_marketplace.partner_id or parsed['solution_id'] != schema.x_google_marketplace.solution_id): raise Exception('Partner or solution ID values in the schema and the ' 'Application resource are not consistent') except ValueError: raise Exception( 'marketplace.cloud.google.com/deploy-info annotation on the ' 'Application resource must be valid JSON') if __name__ == "__main__": main()
Ygshvr/marketplace-k8s-app-tools
marketplace/deployer_util/config_helper.py
#!/usr/bin/env python2 # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import io import os import re import sys import yaml NAME_RE = re.compile(r'[a-zA-z0-9_\.\-]+$') # Suggested from https://semver.org SEMVER_RE = re.compile(r'^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)' '(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)' '(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?' '(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$') XGOOGLE = 'x-google-marketplace' XTYPE_NAME = 'NAME' XTYPE_NAMESPACE = 'NAMESPACE' XTYPE_IMAGE = 'IMAGE' XTYPE_DEPLOYER_IMAGE = 'DEPLOYER_IMAGE' XTYPE_PASSWORD = '<PASSWORD>' XTYPE_REPORTING_SECRET = 'REPORTING_SECRET' XTYPE_SERVICE_ACCOUNT = 'SERVICE_ACCOUNT' XTYPE_STORAGE_CLASS = 'STORAGE_CLASS' XTYPE_STRING = 'STRING' XTYPE_APPLICATION_UID = 'APPLICATION_UID' XTYPE_ISTIO_ENABLED = 'ISTIO_ENABLED' XTYPE_INGRESS_AVAILABLE = 'INGRESS_AVAILABLE' XTYPE_TLS_CERTIFICATE = 'TLS_CERTIFICATE' XTYPE_MASKED_FIELD = 'MASKED_FIELD' WIDGET_TYPES = ['help'] _OAUTH_SCOPE_PREFIX = 'https://www.googleapis.com/auth/' class InvalidName(Exception): pass class InvalidValue(Exception): pass class InvalidSchema(Exception): pass def load_values(values_file, values_dir, schema): if values_file == '-': return yaml.safe_load(sys.stdin.read()) if values_file and os.path.isfile(values_file): with open(values_file, 'r') as f: return yaml.safe_load(f.read()) return _read_values_to_dict(values_dir, schema) def _read_values_to_dict(values_dir, schema): """Returns a dict constructed from files in values_dir.""" files = [ f for f in os.listdir(values_dir) if os.path.isfile(os.path.join(values_dir, f)) ] result = {} for filename in files: if not NAME_RE.match(filename): raise InvalidName('Invalid config parameter name: {}'.format(filename)) file_path = os.path.join(values_dir, filename) with open(file_path, "r") as f: data = f.read().decode('utf-8') result[filename] = data # Data read in as strings. Convert them to proper types defined in schema. result = { k: schema.properties[k].str_to_type(v) if k in schema.properties else v for k, v in result.iteritems() } return result class Schema: """Accesses a JSON schema.""" @staticmethod def load_yaml_file(filepath): with io.open(filepath, 'r') as f: d = yaml.load(f) return Schema(d) @staticmethod def load_yaml(yaml_str): return Schema(yaml.load(yaml_str)) def __init__(self, dictionary): self._x_google_marketplace = _maybe_get_and_apply( dictionary, 'x-google-marketplace', lambda v: SchemaXGoogleMarketplace(v)) self._required = dictionary.get('required', []) self._properties = { k: SchemaProperty(k, v, k in self._required) for k, v in dictionary.get('properties', {}).iteritems() } self._app_api_version = dictionary.get( 'applicationApiVersion', dictionary.get('application_api_version', None)) self._form = dictionary.get('form', []) def validate(self): """Fully validates the schema, raising InvalidSchema if fails.""" bad_required_names = [ x for x in self._required if x not in self._properties ] if bad_required_names: raise InvalidSchema( 'Undefined property names found in required: {}'.format( ', '.join(bad_required_names))) is_v2 = False if self._x_google_marketplace is not None: self._x_google_marketplace.validate() is_v2 = self._x_google_marketplace.is_v2() if not is_v2 and self._app_api_version is None: raise InvalidSchema('applicationApiVersion is required') if len(self.form) > 1: raise InvalidSchema('form must not contain more than 1 item.') for item in self.form: if 'widget' not in item: raise InvalidSchema('form items must have a widget.') if item['widget'] not in WIDGET_TYPES: raise InvalidSchema('Unrecognized form widget: {}'.format( item['widget'])) if 'description' not in item: raise InvalidSchema('form items must have a description.') if is_v2: for _, p in self._properties.iteritems(): if p.xtype == XTYPE_IMAGE: raise InvalidSchema( 'No properties should have x-google-marketplace.type=IMAGE in ' 'schema v2. Images must be declared in the top level ' 'x-google-marketplace.images') @property def x_google_marketplace(self): return self._x_google_marketplace @property def app_api_version(self): if self.is_v2(): return self.x_google_marketplace.app_api_version return self._app_api_version @property def properties(self): return self._properties @property def required(self): return self._required @property def form(self): return self._form def properties_matching(self, definition): return [ v for k, v in self._properties.iteritems() if v.matches_definition(definition) ] def is_v2(self): if self.x_google_marketplace: return self.x_google_marketplace.is_v2() return False _SCHEMA_VERSION_1 = 'v1' _SCHEMA_VERSION_2 = 'v2' _SCHEMA_VERSIONS = [_SCHEMA_VERSION_1, _SCHEMA_VERSION_2] class SchemaXGoogleMarketplace: """Accesses the top level x-google-markplace.""" def __init__(self, dictionary): self._app_api_version = None self._published_version = None self._published_version_meta = None self._partner_id = None self._solution_id = None self._images = None self._cluster_constraints = None self._deployer_service_account = None self._schema_version = dictionary.get('schemaVersion', _SCHEMA_VERSION_1) if self._schema_version not in _SCHEMA_VERSIONS: raise InvalidSchema('Invalid schema version {}'.format( self._schema_version)) self._partner_id = dictionary.get('partnerId', None) self._solution_id = dictionary.get('solutionId', None) if self._partner_id or self._solution_id: if not self._partner_id or not self._solution_id: raise InvalidSchema( 'x-google-marketplace.partnerId and x-google-marketplace.solutionId' ' must be specified or missing together') if 'clusterConstraints' in dictionary: self._cluster_constraints = SchemaClusterConstraints( dictionary['clusterConstraints']) if not self.is_v2(): return self._app_api_version = _must_get( dictionary, 'applicationApiVersion', 'x-google-marketplace.applicationApiVersion is required') self._published_version = _must_get( dictionary, 'publishedVersion', 'x-google-marketplace.publishedVersion is required') if not SEMVER_RE.match(self._published_version): raise InvalidSchema( 'Invalid schema publishedVersion "{}"; must be semver including patch version' .format(self._published_version)) self._published_version_meta = _must_get_and_apply( dictionary, 'publishedVersionMetadata', lambda v: SchemaVersionMeta(v), 'x-google-marketplace.publishedVersionMetadata is required') self._managed_updates = SchemaManagedUpdates( dictionary.get('managedUpdates', {})) images = _must_get(dictionary, 'images', 'x-google-marketplace.images is required') self._images = {k: SchemaImage(k, v) for k, v in images.iteritems()} if 'deployerServiceAccount' in dictionary: self._deployer_service_account = SchemaXServiceAccount( dictionary['deployerServiceAccount']) def validate(self): pass @property def cluster_constraints(self): return self._cluster_constraints @property def app_api_version(self): return self._app_api_version @property def published_version(self): return self._published_version @property def published_version_meta(self): return self._published_version_meta @property def partner_id(self): return self._partner_id @property def solution_id(self): return self._solution_id @property def images(self): return self._images @property def managed_updates(self): return self._managed_updates @property def deployer_service_account(self): return self._deployer_service_account def is_v2(self): return self._schema_version == _SCHEMA_VERSION_2 class SchemaManagedUpdates: """Accesses managedUpdates.""" def __init__(self, dictionary): self._kalm_supported = dictionary.get('kalmSupported', False) @property def kalm_supported(self): return self._kalm_supported class SchemaClusterConstraints: """Accesses top level clusterConstraints.""" def __init__(self, dictionary): self._k8s_version = dictionary.get('k8sVersion', None) self._resources = None self._istio = None self._gcp = None if 'resources' in dictionary: resources = dictionary['resources'] if not isinstance(resources, list): raise InvalidSchema('clusterConstraints.resources must be a list') self._resources = [SchemaResourceConstraints(r) for r in resources] self._istio = _maybe_get_and_apply(dictionary, 'istio', lambda v: SchemaIstio(v)) self._gcp = _maybe_get_and_apply(dictionary, 'gcp', lambda v: SchemaGcp(v)) @property def k8s_version(self): return self._k8s_version @property def resources(self): return self._resources @property def istio(self): return self._istio @property def gcp(self): return self._gcp class SchemaResourceConstraints: """Accesses a single resource's constraints.""" def __init__(self, dictionary): self._replicas = dictionary.get('replicas', None) self._affinity = _maybe_get_and_apply( dictionary, 'affinity', lambda v: SchemaResourceConstraintAffinity(v)) self._requests = _maybe_get_and_apply( dictionary, 'requests', lambda v: SchemaResourceConstraintRequests(v)) @property def replicas(self): return self._replicas @property def affinity(self): return self._affinity @property def requests(self): return self._requests class SchemaResourceConstraintAffinity: """Accesses a single resource's affinity constraints""" def __init__(self, dictionary): self._simple_node_affinity = _maybe_get_and_apply( dictionary, 'simpleNodeAffinity', lambda v: SchemaSimpleNodeAffinity(v)) @property def simple_node_affinity(self): return self._simple_node_affinity class SchemaSimpleNodeAffinity: """Accesses simple node affinity for resource constraints.""" def __init__(self, dictionary): self._minimum_node_count = dictionary.get('minimumNodeCount', None) self._type = _must_get(dictionary, 'type', 'simpleNodeAffinity requires a type') if (self._type == 'REQUIRE_MINIMUM_NODE_COUNT' and self._minimum_node_count is None): raise InvalidSchema( 'simpleNodeAffinity of type REQUIRE_MINIMUM_NODE_COUNT ' 'requires minimumNodeCount') @property def affinity_type(self): return self._type @property def minimum_node_count(self): return self._minimum_node_count class SchemaResourceConstraintRequests: """Accesses a single resource's requests.""" def __init__(self, dictionary): self.cpu = dictionary.get('cpu', None) self.memory = dictionary.get('memory', None) @property def cpu(self): return self._cpu @property def memory(self): return self._memory _ISTIO_TYPE_OPTIONAL = "OPTIONAL" _ISTIO_TYPE_REQUIRED = "REQUIRED" _ISTIO_TYPE_UNSUPPORTED = "UNSUPPORTED" _ISTIO_TYPES = [ _ISTIO_TYPE_OPTIONAL, _ISTIO_TYPE_REQUIRED, _ISTIO_TYPE_UNSUPPORTED ] class SchemaIstio: """Accesses top level istio.""" def __init__(self, dictionary): self._type = dictionary.get('type', None) _must_contain(self._type, _ISTIO_TYPES, "Invalid type of istio constraint") @property def type(self): return self._type class SchemaGcp: """Accesses top level GCP constraints.""" def __init__(self, dictionary): self._nodes = _maybe_get_and_apply(dictionary, 'nodes', lambda v: SchemaNodes(v)) @property def nodes(self): return self._nodes class SchemaNodes: """Accesses GKE cluster node constraints.""" def __init__(self, dictionary): self._required_oauth_scopes = dictionary.get('requiredOauthScopes', []) if not isinstance(self._required_oauth_scopes, list): raise InvalidSchema('nodes.requiredOauthScopes must be a list') for scope in self._required_oauth_scopes: if not scope.startswith(_OAUTH_SCOPE_PREFIX): raise InvalidSchema( 'OAuth scope references must be fully-qualified (start with {})' .format(_OAUTH_SCOPE_PREFIX)) @property def required_oauth_scopes(self): return self._required_oauth_scopes class SchemaImage: """Accesses an image definition.""" def __init__(self, name, dictionary): self._name = name self._properties = { k: SchemaImageProjectionProperty(k, v) for k, v in dictionary.get('properties', {}).iteritems() } @property def name(self): return self._name @property def properties(self): return self._properties IMAGE_PROJECTION_TYPE_FULL = 'FULL' IMAGE_PROJECTION_TYPE_REPO = 'REPO_WITHOUT_REGISTRY' IMAGE_PROJECTION_TYPE_REGISTRY_REPO = 'REPO_WITH_REGISTRY' IMAGE_PROJECTION_TYPE_REGISTRY = 'REGISTRY' IMAGE_PROJECTION_TYPE_TAG = 'TAG' _IMAGE_PROJECTION_TYPES = [ IMAGE_PROJECTION_TYPE_FULL, IMAGE_PROJECTION_TYPE_REPO, IMAGE_PROJECTION_TYPE_REGISTRY_REPO, IMAGE_PROJECTION_TYPE_REGISTRY, IMAGE_PROJECTION_TYPE_TAG, ] class SchemaImageProjectionProperty: """Accesses a property that an image name projects to.""" def __init__(self, name, dictionary): self._name = name self._type = _must_get( dictionary, 'type', 'Each property for an image in x-google-marketplace.images ' 'must have a valid type') if self._type not in _IMAGE_PROJECTION_TYPES: raise InvalidSchema('image property {} has invalid type {}'.format( name, self._type)) @property def name(self): return self._name @property def part_type(self): return self._type class SchemaVersionMeta: """Accesses publishedVersionMetadata.""" def __init__(self, dictionary): self._recommended = dictionary.get('recommended', False) self._release_types = dictionary.get('releaseTypes', []) self._release_note = _must_get( dictionary, 'releaseNote', 'publishedVersionMetadata.releaseNote is required') @property def recommended(self): return self._recommended @property def release_note(self): return self._release_note @property def release_types(self): return self._release_types class SchemaProperty: """Accesses a JSON schema property.""" def __init__(self, name, dictionary, required): self._name = name self._d = dictionary self._required = required self._default = dictionary.get('default', None) self._x = dictionary.get(XGOOGLE, None) self._application_uid = None self._image = None self._password = None self._reporting_secret = None self._service_account = None self._storage_class = None self._string = None self._tls_certificate = None if not NAME_RE.match(name): raise InvalidSchema('Invalid property name: {}'.format(name)) self._type = _must_get_and_apply( dictionary, 'type', lambda v: { 'int': int, 'integer': int, 'string': str, 'number': float, 'boolean': bool, }.get(v, None), 'Property {} has no type'.format(name)) if not self._type: raise InvalidSchema('Property {} has unsupported type: {}'.format( name, dictionary['type'])) if self._default: if not isinstance(self._default, self._type): raise InvalidSchema( 'Property {} has a default value of invalid type'.format(name)) if self._x: xt = _must_get(self._x, 'type', 'Property {} has {} without a type'.format(name, XGOOGLE)) if xt in (XTYPE_NAME, XTYPE_NAMESPACE, XTYPE_DEPLOYER_IMAGE, XTYPE_MASKED_FIELD): _property_must_have_type(self, str) elif xt in (XTYPE_ISTIO_ENABLED, XTYPE_INGRESS_AVAILABLE): _property_must_have_type(self, bool) elif xt == XTYPE_APPLICATION_UID: _property_must_have_type(self, str) d = self._x.get('applicationUid', {}) self._application_uid = SchemaXApplicationUid(d) elif xt == XTYPE_IMAGE: _property_must_have_type(self, str) d = self._x.get('image', {}) self._image = SchemaXImage(d, self._default) elif xt == XTYPE_PASSWORD: _property_must_have_type(self, str) d = self._x.get('generatedPassword', {}) spec = { 'length': d.get('length', 10), 'include_symbols': d.get('includeSymbols', False), 'base64': d.get('base64', True), } self._password = SchemaXPassword(**spec) elif xt == XTYPE_SERVICE_ACCOUNT: _property_must_have_type(self, str) d = self._x.get('serviceAccount', {}) self._service_account = SchemaXServiceAccount(d) elif xt == XTYPE_STORAGE_CLASS: _property_must_have_type(self, str) d = self._x.get('storageClass', {}) self._storage_class = SchemaXStorageClass(d) elif xt == XTYPE_STRING: _property_must_have_type(self, str) d = self._x.get('string', {}) self._string = SchemaXString(d) elif xt == XTYPE_REPORTING_SECRET: _property_must_have_type(self, str) d = self._x.get('reportingSecret', {}) self._reporting_secret = SchemaXReportingSecret(d) elif xt == XTYPE_TLS_CERTIFICATE: _property_must_have_type(self, str) d = self._x.get('tlsCertificate', {}) self._tls_certificate = SchemaXTlsCertificate(d) else: raise InvalidSchema('Property {} has an unknown type: {}'.format( name, xt)) @property def name(self): return self._name @property def required(self): return self._required @property def default(self): return self._default @property def type(self): """Python type of the property.""" return self._type @property def xtype(self): if self._x: return self._x['type'] return None @property def application_uid(self): return self._application_uid @property def image(self): return self._image @property def password(self): return self._password @property def reporting_secret(self): return self._reporting_secret @property def service_account(self): return self._service_account @property def storage_class(self): return self._storage_class @property def string(self): return self._string @property def tls_certificate(self): return self._tls_certificate def str_to_type(self, str_val): if self._type == bool: if str_val in {'true', 'True', 'yes', 'Yes'}: return True elif str_val in {'false', 'False', 'no', 'No'}: return False else: raise InvalidValue('Bad value for boolean property {}: {}'.format( self._name, str_val)) return self._type(str_val) def matches_definition(self, definition): """Returns true of the definition partially matches. The definition argument is a dictionary. All fields in the hierarchy defined there must be present and have the same values in the schema in order for the property to be a match. There is a special `name` field in the dictionary that captures the property name, which does not originally exist in the schema. """ def _matches(dictionary, subdict): for k, sv in subdict.iteritems(): v = dictionary.get(k, None) if isinstance(v, dict): if not _matches(v, sv): return False else: if v != sv: return False return True return _matches( dict(list(self._d.iteritems()) + [('name', self._name)]), definition) def __eq__(self, other): if not isinstance(other, SchemaProperty): return False return other._name == self._name and other._d == self._d class SchemaXApplicationUid: """Accesses APPLICATION_UID properties.""" def __init__(self, dictionary): generated_properties = dictionary.get('generatedProperties', {}) self._application_create = generated_properties.get( 'createApplicationBoolean', None) @property def application_create(self): return self._application_create class SchemaXImage: """Accesses IMAGE and DEPLOYER_IMAGE properties.""" def __init__(self, dictionary, default): self._split_by_colon = None self._split_to_registry_repo_tag = None if not default: raise InvalidSchema('default image value must be specified') if not default.startswith('gcr.io'): raise InvalidSchema( 'default image value must state registry: {}'.format(default)) if ':' not in default: raise InvalidSchema( 'default image value is missing a tag or digest: {}'.format(default)) generated_properties = dictionary.get('generatedProperties', {}) if 'splitByColon' in generated_properties: s = generated_properties['splitByColon'] self._split_by_colon = ( _must_get(s, 'before', '"before" attribute is required within splitByColon'), _must_get(s, 'after', '"after" attribute is required within splitByColon')) if 'splitToRegistryRepoTag' in generated_properties: s = generated_properties['splitToRegistryRepoTag'] parts = ['registry', 'repo', 'tag'] self._split_to_registry_repo_tag = tuple([ _must_get( s, name, '"{}" attribute is required within splitToRegistryRepoTag'.format( name)) for name in parts ]) @property def split_by_colon(self): """Return 2-tuple of before- and after-colon names, or None""" return self._split_by_colon @property def _split_to_registry_repo_tag(self): """Return 3-tuple, or None""" return self._split_to_registry_repo_tag SchemaXPassword = collections.namedtuple( 'SchemaXPassword', ['length', 'include_symbols', 'base64']) class SchemaXServiceAccount: """Accesses SERVICE_ACCOUNT property.""" def __init__(self, dictionary): self._roles = dictionary.get('roles', []) for role in self._roles: if role.get('rulesType') == 'PREDEFINED': if role.get('rules'): raise InvalidSchema('rules can only be used with rulesType CUSTOM') if not role.get('rulesFromRoleName'): raise InvalidSchema('Missing rulesFromRoleName for PREDEFINED role') elif role.get('rulesType') == 'CUSTOM': if role.get('rulesFromRoleName'): raise InvalidSchema( 'rulesFromRoleName can only be used with rulesType PREDEFINED') if not role.get('rules'): raise InvalidSchema('Missing rules for CUSTOM role') for rule in role.get('rules', []): if rule.get('nonResourceURLs'): raise InvalidSchema( 'Only attributes for resourceRules are supported in rules') if not rule.get('apiGroups') or not filter(lambda x: x, rule.get('apiGroups')): raise InvalidSchema("Missing or empty apiGroups in rules. " "Did you mean [\"v1\"] or [\"*\"]?") if not rule.get('resources') or not filter(lambda x: x, rule.get('resources')): raise InvalidSchema('Missing or empty resources in rules.') if not rule.get('verbs') or not filter(lambda x: x, rule.get('verbs')): raise InvalidSchema('Missing or empty verbs in rules.') else: raise InvalidSchema('rulesType must be one of PREDEFINED or CUSTOM') def custom_role_rules(self): """Returns a list of rules for custom Roles.""" return [ role.get('rules', []) for role in self._roles if role['type'] == 'Role' and role['rulesType'] == 'CUSTOM' ] def custom_cluster_role_rules(self): """Returns a list of rules for custom ClusterRoles.""" return [ role.get('rules', []) for role in self._roles if role['type'] == 'ClusterRole' and role['rulesType'] == 'CUSTOM' ] def predefined_roles(self): """Returns a list of predefined Roles.""" return [ role.get('rulesFromRoleName') for role in self._roles if role['type'] == 'Role' and role['rulesType'] == 'PREDEFINED' ] def predefined_cluster_roles(self): """Returns a list of predefined ClusterRoles.""" return [ role.get('rulesFromRoleName') for role in self._roles if role['type'] == 'ClusterRole' and role['rulesType'] == 'PREDEFINED' ] class SchemaXStorageClass: """Accesses STORAGE_CLASS property.""" def __init__(self, dictionary): self._type = dictionary['type'] @property def ssd(self): return self._type == 'SSD' class SchemaXString: """Accesses STRING property.""" def __init__(self, dictionary): generated_properties = dictionary.get('generatedProperties', {}) self._base64_encoded = generated_properties.get('base64Encoded', None) @property def base64_encoded(self): return self._base64_encoded class SchemaXReportingSecret: """Accesses REPORTING_SECRET property.""" def __init__(self, dictionary): pass class SchemaXTlsCertificate: """Accesses TLS_CERTIFICATE property.""" def __init__(self, dictionary): generated_properties = dictionary.get('generatedProperties', {}) self._base64_encoded_private_key = generated_properties.get( 'base64EncodedPrivateKey', None) self._base64_encoded_certificate = generated_properties.get( 'base64EncodedCertificate', None) @property def base64_encoded_private_key(self): return self._base64_encoded_private_key @property def base64_encoded_certificate(self): return self._base64_encoded_certificate def _must_get(dictionary, key, error_msg): """Gets the value of the key, or raises InvalidSchema.""" if key not in dictionary: raise InvalidSchema(error_msg) return dictionary[key] def _maybe_get_and_apply(dictionary, key, apply_fn): """Returns the result of apply_fn on the value of the key if not None.""" if key not in dictionary: return None return apply_fn(dictionary[key]) def _must_get_and_apply(dictionary, key, apply_fn, error_msg): """Similar to _maybe_get_and_apply but raises InvalidSchema if no such key.""" value = _must_get(dictionary, key, error_msg) return apply_fn(value) def _must_contain(value, valid_list, error_msg): """Validates that value in valid_list, or raises InvalidSchema.""" if value not in valid_list: raise InvalidSchema("{}. Must be one of {}".format(error_msg, ', '.join(valid_list))) def _property_must_have_type(prop, expected_type): if prop.type != expected_type: readable_type = { str: 'string', bool: 'boolean', int: 'integer', float: 'float', }.get(expected_type, expected_type.__name__) raise InvalidSchema( '{} x-google-marketplace type property must be of type {}'.format( prop.xtype, readable_type))
Ygshvr/marketplace-k8s-app-tools
marketplace/deployer_util/validate_app_resource_test.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import config_helper from validate_app_resource import validate_deploy_info_annotation class ValidateAppResourceTest(unittest.TestCase): def test_deploy_info_must_be_json(self): self.assertRaisesRegexp( Exception, r'.*must be valid JSON.*', lambda: validate_deploy_info_annotation('invalid json')) def test_deploy_info_must_contain_partner_id(self): self.assertRaisesRegexp( Exception, r'.*must contain a partner_id.*', lambda: validate_deploy_info_annotation('{"solution_id": "solution"}')) def test_deploy_info_must_contain_solution_id(self): self.assertRaisesRegexp( Exception, r'.*must contain a solution_id.*', lambda: validate_deploy_info_annotation('{"partner_id": "partner"}')) def test_deploy_info_must_match_schema(self): schema = config_helper.Schema.load_yaml(""" x-google-marketplace: schemaVersion: v2 partnerId: partner-a solutionId: solution-a applicationApiVersion: v1beta1 publishedVersion: 6.5.130-metadata publishedVersionMetadata: releaseNote: Bug fixes images: {} properties: {} """) self.assertRaisesRegexp( Exception, r'Partner or solution ID values.*schema.*not consistent', lambda: validate_deploy_info_annotation( '{"partner_id": "partner-a", "solution_id": "solution-b"}', schema)) self.assertRaisesRegexp( Exception, r'Partner or solution ID values.*schema.*not consistent', lambda: validate_deploy_info_annotation( '{"partner_id": "partner-b", "solution_id": "solution-a"}', schema)) validate_deploy_info_annotation( '{"partner_id": "partner-a", "solution_id": "solution-a"}', schema) def test_deploy_info_ok_if_schema_has_no_partner_solution_ids(self): schema = config_helper.Schema.load_yaml(""" x-google-marketplace: schemaVersion: v2 applicationApiVersion: v1beta1 publishedVersion: 6.5.130-metadata publishedVersionMetadata: releaseNote: Bug fixes images: {} properties: {} """) validate_deploy_info_annotation( '{"partner_id": "partner-a", "solution_id": "solution-a"}', schema)
jlandowner/kustomize-ingress
base/krmfunc/ingress_patch.py
#!/usr/bin/env python3 from functools import reduce import os import sys import yaml import logging def main(args=sys.argv[1:]): resource_list = yaml.load(sys.stdin, Loader=yaml.FullLoader) target_name = dict_get(resource_list, 'functionConfig.metadata.name') annotations = dict_get(resource_list, 'functionConfig.spec.annotations', {}) hosts = [] for host in dict_get(resource_list, 'functionConfig.spec.hosts', []): hosts.append({ 'name': dict_get(host, 'name'), 'target': dict_get(host, 'target') }) output = [] for resource in dict_get(resource_list, 'items', []): if resource['apiVersion'] in ['extensions/v1beta1', 'networking.k8s.io/v1', 'networking.k8s.io/v1beta1'] \ and resource['kind'] == 'Ingress' \ and dict_get(resource, 'metadata.name') == target_name: # patch annnotation if len(annotations) > 0: ann = dict_get(resource, 'metadata.annotations') if ann is not None: for key in annotations: ann[key] = annotations[key] else: resource['metadata']['annotations'] = annotations for host in hosts: host_name = dict_get(host, 'name') target = dict_get(host, 'target') # patch host for rule in dict_get(resource, 'spec.rules', []): if target is None or rule['host'] == target: rule['host'] = host_name #TODO patch tls output.append(resource) sys.stdout.write(yaml.dump_all(output)) def dict_get(dictionary, keys, default=None): return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary) if __name__ == '__main__': sys.stdin.reconfigure(encoding='utf-8') sys.stdout.reconfigure(encoding='utf-8') sys.stderr.reconfigure(encoding='utf-8') main()
jerrykan/roundup
roundup/cgi/wsgi_handler.py
# WSGI interface for Roundup Issue Tracker # # This module is free software, you may redistribute it # and/or modify under the same terms as Python. # import os import weakref from contextlib import contextmanager from roundup.anypy.html import html_escape import roundup.instance from roundup.cgi import TranslationService from roundup.anypy import http_ from roundup.anypy.strings import s2b from roundup.cgi.client import BinaryFieldStorage BaseHTTPRequestHandler = http_.server.BaseHTTPRequestHandler DEFAULT_ERROR_MESSAGE = http_.server.DEFAULT_ERROR_MESSAGE class Headers(object): """ Idea more or less stolen from the 'apache.py' in same directory. Except that wsgi stores http headers in environment. """ def __init__(self, environ): self.environ = environ def mangle_name(self, name): """ Content-Type is handled specially, it doesn't have a HTTP_ prefix in cgi. """ n = name.replace('-', '_').upper() if n == 'CONTENT_TYPE': return n return 'HTTP_' + n def get(self, name, default=None): return self.environ.get(self.mangle_name(name), default) getheader = get class Writer(object): '''Perform a start_response if need be when we start writing.''' def __init__(self, request): self.request = request #weakref.ref(request) def write(self, data): f = self.request.get_wfile() self.write = f return self.write(data) class RequestHandler(object): def __init__(self, environ, start_response): self.__start_response = start_response self.__wfile = None self.headers = Headers(environ) self.rfile, self.wfile = None, Writer(self) def start_response(self, headers, response_code): """Set HTTP response code""" message, explain = BaseHTTPRequestHandler.responses[response_code] self.__wfile = self.__start_response('%d %s' % (response_code, message), headers) def get_wfile(self): if self.__wfile is None: raise ValueError('start_response() not called') return self.__wfile class RequestDispatcher(object): def __init__(self, home, debug=False, timing=False, lang=None): assert os.path.isdir(home), '%r is not a directory' % (home,) self.home = home self.debug = debug self.timing = timing if lang: self.translator = TranslationService.get_translation(lang, tracker_home=home) else: self.translator = None self.preload() def __call__(self, environ, start_response): """Initialize with `apache.Request` object""" request = RequestHandler(environ, start_response) if environ['REQUEST_METHOD'] == 'OPTIONS': if environ["PATH_INFO"][:5] == "/rest": # rest does support options # This I hope will result in self.form=None environ['CONTENT_LENGTH'] = 0 else: code = 501 message, explain = BaseHTTPRequestHandler.responses[code] request.start_response([('Content-Type', 'text/html'), ('Connection', 'close')], code) request.wfile.write(s2b(DEFAULT_ERROR_MESSAGE % locals())) return [] # need to strip the leading '/' environ["PATH_INFO"] = environ["PATH_INFO"][1:] if self.timing: environ["CGI_SHOW_TIMING"] = self.timing if environ['REQUEST_METHOD'] in ("OPTIONS", "DELETE"): # these methods have no data. When we init tracker.Client # set form to None to get a properly initialized empty # form. form = None else: form = BinaryFieldStorage(fp=environ['wsgi.input'], environ=environ) with self.get_tracker() as tracker: client = tracker.Client(tracker, request, environ, form, self.translator) try: client.main() except roundup.cgi.client.NotFound: request.start_response([('Content-Type', 'text/html')], 404) request.wfile.write(s2b('Not found: %s' % html_escape(client.path))) # all body data has been written using wfile return [] def preload(self): """ Trigger pre-loading of imports and templates """ with self.get_tracker(): pass @contextmanager def get_tracker(self): # get a new instance for each request yield roundup.instance.open(self.home, not self.debug)
jerrykan/roundup
test/test_config.py
# # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/) # This module is free software, and you may redistribute it and/or modify # under the same terms as Python, so long as this copyright message and # disclaimer are retained in their original form. # # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. import unittest import logging import os, shutil, errno import pytest from roundup import configuration config = configuration.CoreConfig() config.DATABASE = "db" config.RDBMS_NAME = "rounduptest" config.RDBMS_HOST = "localhost" config.RDBMS_USER = "rounduptest" config.RDBMS_PASSWORD = "<PASSWORD>" config.RDBMS_TEMPLATE = "template0" # these TRACKER_WEB and MAIL_DOMAIN values are used in mailgw tests config.MAIL_DOMAIN = "your.tracker.email.domain.example" config.TRACKER_WEB = "http://tracker.example/cgi-bin/roundup.cgi/bugs/" # uncomment the following to have excessive debug output from test cases # FIXME: tracker logging level should be increased by -v arguments # to 'run_tests.py' script #config.LOGGING_FILENAME = "/tmp/logfile" #config.LOGGING_LEVEL = "DEBUG" config.init_logging() config.options['FOO'] = "value" # for TrackerConfig test class from roundup import instance from . import db_test_base class ConfigTest(unittest.TestCase): def test_badConfigKeyword(self): """Run configure tests looking for invalid option name """ self.assertRaises(configuration.InvalidOptionError, config._get_option, "BadOptionName") def test_validConfigKeyword(self): """Run configure tests looking for invalid option name """ self.assertEqual(config._get_option("FOO"), "value") def testTrackerWeb(self): config = configuration.CoreConfig() self.assertEqual(None, config._get_option('TRACKER_WEB').set("http://foo.example/bar/")) self.assertEqual(None, config._get_option('TRACKER_WEB').set("https://foo.example/bar/")) self.assertRaises(configuration.OptionValueError, config._get_option('TRACKER_WEB').set, "https://foo.example/bar") self.assertRaises(configuration.OptionValueError, config._get_option('TRACKER_WEB').set, "htt://foo.example/bar/") self.assertRaises(configuration.OptionValueError, config._get_option('TRACKER_WEB').set, "htt://foo.example/bar") self.assertRaises(configuration.OptionValueError, config._get_option('TRACKER_WEB').set, "") def testLoginAttemptsMin(self): config = configuration.CoreConfig() self.assertEqual(None, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set("0")) self.assertEqual(None, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set("200")) self.assertRaises(configuration.OptionValueError, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set, "fred") self.assertRaises(configuration.OptionValueError, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set, "-1") self.assertRaises(configuration.OptionValueError, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set, "") def testTimeZone(self): config = configuration.CoreConfig() self.assertEqual(None, config._get_option('TIMEZONE').set("0")) # not a valid timezone self.assertRaises(configuration.OptionValueError, config._get_option('TIMEZONE').set, "Zot") # 25 is not a valid UTC offset: -12 - +14 is range # possibly +/- 1 for DST. But roundup.date doesn't # constrain to this range. #self.assertRaises(configuration.OptionValueError, # config._get_option('TIMEZONE').set, "25") try: import pytz self.assertEqual(None, config._get_option('TIMEZONE').set("UTC")) self.assertEqual(None, config._get_option('TIMEZONE').set("America/New_York")) self.assertEqual(None, config._get_option('TIMEZONE').set("EST")) self.assertRaises(configuration.OptionValueError, config._get_option('TIMEZONE').set, "Zool/Zot") except ImportError: # UTC is a known offset of 0 coded into roundup.date # so it works even without pytz. self.assertEqual(None, config._get_option('TIMEZONE').set("UTC")) # same with EST known timeone offset of 5 self.assertEqual(None, config._get_option('TIMEZONE').set("EST")) self.assertRaises(configuration.OptionValueError, config._get_option('TIMEZONE').set, "America/New_York") def testWebSecretKey(self): config = configuration.CoreConfig() self.assertEqual(None, config._get_option('WEB_SECRET_KEY').set("skskskd")) self.assertRaises(configuration.OptionValueError, config._get_option('WEB_SECRET_KEY').set, "") def testStaticFiles(self): config = configuration.CoreConfig() self.assertEqual(None, config._get_option('STATIC_FILES').set("foo /tmp/bar")) self.assertEqual(config.STATIC_FILES, ["./foo", "/tmp/bar"]) self.assertEqual(config['STATIC_FILES'], ["./foo", "/tmp/bar"]) def testIsolationLevel(self): config = configuration.CoreConfig() self.assertEqual(None, config._get_option('RDBMS_ISOLATION_LEVEL').set("read uncommitted")) self.assertEqual(None, config._get_option('RDBMS_ISOLATION_LEVEL').set("read committed")) self.assertEqual(None, config._get_option('RDBMS_ISOLATION_LEVEL').set("repeatable read")) self.assertRaises(configuration.OptionValueError, config._get_option('RDBMS_ISOLATION_LEVEL').set, "not a level") def testConfigSave(self): config = configuration.CoreConfig() # make scratch directory to create files in self.startdir = os.getcwd() self.dirname = os.getcwd() + '_test_config' os.mkdir(self.dirname) try: os.chdir(self.dirname) self.assertFalse(os.access("config.ini", os.F_OK)) self.assertFalse(os.access("config.bak", os.F_OK)) config.save() config.save() # creates .bak file self.assertTrue(os.access("config.ini", os.F_OK)) self.assertTrue(os.access("config.bak", os.F_OK)) self.assertFalse(os.access("foo.bar", os.F_OK)) self.assertFalse(os.access("foo.bak", os.F_OK)) config.save("foo.bar") config.save("foo.bar") # creates .bak file self.assertTrue(os.access("foo.bar", os.F_OK)) self.assertTrue(os.access("foo.bak", os.F_OK)) finally: # cleanup scratch directory and files try: os.chdir(self.startdir) shutil.rmtree(self.dirname) except OSError as error: if error.errno not in (errno.ENOENT, errno.ESRCH): raise def testFloatAndInt_with_update_option(self): config = configuration.CoreConfig() # Update existing IntegerNumberGeqZeroOption to IntegerNumberOption config.update_option('WEB_LOGIN_ATTEMPTS_MIN', configuration.IntegerNumberOption, "0", description="new desc") # -1 is allowed now that it is an int. self.assertEqual(None, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set("-1")) # but can't float this self.assertRaises(configuration.OptionValueError, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set, "2.4") # but fred is still an issue self.assertRaises(configuration.OptionValueError, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set, "fred") # Update existing IntegerNumberOption to FloatNumberOption config.update_option('WEB_LOGIN_ATTEMPTS_MIN', configuration.FloatNumberOption, "0.0") self.assertEqual(config['WEB_LOGIN_ATTEMPTS_MIN'], -1) # can float this self.assertEqual(None, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set("3.1415926")) # but fred is still an issue self.assertRaises(configuration.OptionValueError, config._get_option('WEB_LOGIN_ATTEMPTS_MIN').set, "fred") self.assertAlmostEqual(config['WEB_LOGIN_ATTEMPTS_MIN'], 3.1415926, places=6) class TrackerConfig(unittest.TestCase): """ Arguably this should be tested in test_instance since it is triggered by instance.open. But it raises an error in the configuration module with a missing required param in config.ini.""" backend = 'anydbm' def setUp(self): self.dirname = '_test_instance' # set up and open a tracker self.instance = db_test_base.setupTracker(self.dirname, self.backend) # open the database self.db = self.instance.open('admin') self.db.commit() self.db.close() def tearDown(self): if self.db: self.db.close() try: shutil.rmtree(self.dirname) except OSError as error: if error.errno not in (errno.ENOENT, errno.ESRCH): raise def testNoDBInConfig(self): # comment out the backend key in config.ini import fileinput for line in fileinput.input(os.path.join(self.dirname, "config.ini"), inplace=True): if line.startswith("backend = "): continue print(line) # this should fail as backend isn't defined. self.assertRaises(configuration.OptionUnsetError, instance.open, self.dirname)
jerrykan/roundup
test/rest_common.py
import pytest import unittest import os import shutil import errno import cgi from time import sleep from datetime import datetime, timedelta try: from datetime import timezone myutc = timezone.utc except ImportError: # python 2 from datetime import tzinfo ZERO = timedelta(0) class UTC(tzinfo): """UTC""" def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO myutc = UTC() from roundup.cgi.exceptions import * from roundup.hyperdb import HyperdbValueError from roundup.exceptions import * from roundup import password, hyperdb from roundup.rest import RestfulInstance, calculate_etag from roundup.backends import list_backends from roundup.cgi import client from roundup.anypy.strings import b2s, s2b, us2u import random from roundup.backends.sessions_dbm import OneTimeKeys from roundup.anypy.dbm_ import anydbm, whichdb from .db_test_base import setupTracker from .mocknull import MockNull from io import BytesIO import json from copy import copy try: import jwt skip_jwt = lambda func, *args, **kwargs: func except ImportError: from .pytest_patcher import mark_class jwt=None skip_jwt = mark_class(pytest.mark.skip( reason='Skipping JWT tests: jwt library not available')) NEEDS_INSTANCE = 1 class TestCase(): backend = None url_pfx = 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/' def setUp(self): from packaging import version self.dirname = '_test_rest' # set up and open a tracker # Set optimize=True as code under test (Client.main()::determine_user) # will close and re-open the database on user changes. This wipes # out additions to the schema needed for testing. self.instance = setupTracker(self.dirname, self.backend, optimize=True) # open the database self.db = self.instance.open('admin') # Create the Otk db. # This allows a test later on to open the existing db and # set a class attribute to test the open retry loop # just as though this process was using a pre-existing db # rather then the new one we create. otk = OneTimeKeys(self.db) otk.set('key', key="value") # Get user id (user4 maybe). Used later to get data from db. self.joeid = self.db.user.create( username='joe', password=<PASSWORD>('<PASSWORD>'), address='<EMAIL>', realname='<NAME>', roles='User' ) self.db.user.set('1', address="<EMAIL>") self.db.user.set('2', address="<EMAIL>") self.db.commit() self.db.close() self.db = self.instance.open('joe') # Allow joe to retire p = self.db.security.addPermission(name='Retire', klass='issue') self.db.security.addPermissionToRole('User', p) # add set of roles for testing jwt's. self.db.security.addRole(name="User:email", description="allow email by jwt") # allow the jwt to access everybody's email addresses. # this makes it easier to differentiate between User and # User:email roles by accessing the /rest/data/user # endpoint jwt_perms = self.db.security.addPermission(name='View', klass='user', properties=('id', 'realname', 'address', 'username'), description="Allow jwt access to email", props_only=False) self.db.security.addPermissionToRole("User:email", jwt_perms) self.db.security.addPermissionToRole("User:email", "Rest Access") # add set of roles for testing jwt's. # this is like the user:email role, but it missing access to the rest endpoint. self.db.security.addRole(name="User:emailnorest", description="allow email by jwt") jwt_perms = self.db.security.addPermission(name='View', klass='user', properties=('id', 'realname', 'address', 'username'), description="Allow jwt access to email but forget to allow rest", props_only=False) self.db.security.addPermissionToRole("User:emailnorest", jwt_perms) if jwt: # must be 32 chars in length minimum (I think this is at least # 256 bits of data) secret = "TestingTheJwtSecretTestingTheJwtSecret" self.db.config['WEB_JWT_SECRET'] = secret # generate all timestamps in UTC. base_datetime = datetime(1970,1,1, tzinfo=myutc) # A UTC timestamp for now. dt = datetime.now(myutc) now_ts = int((dt - base_datetime).total_seconds()) # one good for a minute dt = dt + timedelta(seconds=60) plus1min_ts = int((dt - base_datetime).total_seconds()) # one that expired a minute ago dt = dt - timedelta(seconds=120) expired_ts = int((dt - base_datetime).total_seconds()) # claims match what cgi/client.py::determine_user # is looking for claim= { 'sub': self.db.getuid(), 'iss': self.db.config.TRACKER_WEB, 'aud': self.db.config.TRACKER_WEB, 'roles': [ 'User' ], 'iat': now_ts, 'exp': plus1min_ts, } # in version 2.0.0 and newer jwt.encode returns string # not bytestring. So we have to skip b2s conversion if version.parse(jwt.__version__) >= version.parse('2.0.0'): tostr = lambda x: x else: tostr = b2s self.jwt = {} self.claim = {} # generate invalid claim with expired timestamp self.claim['expired'] = copy(claim) self.claim['expired']['exp'] = expired_ts self.jwt['expired'] = tostr(jwt.encode(self.claim['expired'], secret, algorithm='HS256')) # generate valid claim with user role self.claim['user'] = copy(claim) self.claim['user']['exp'] = plus1min_ts self.jwt['user'] = tostr(jwt.encode(self.claim['user'], secret, algorithm='HS256')) # generate invalid claim bad issuer self.claim['badiss'] = copy(claim) self.claim['badiss']['iss'] = "http://someissuer/bugs" self.jwt['badiss'] = tostr(jwt.encode(self.claim['badiss'], secret, algorithm='HS256')) # generate invalid claim bad aud(ience) self.claim['badaud'] = copy(claim) self.claim['badaud']['aud'] = "http://someaudience/bugs" self.jwt['badaud'] = tostr(jwt.encode(self.claim['badaud'], secret, algorithm='HS256')) # generate invalid claim bad sub(ject) self.claim['badsub'] = copy(claim) self.claim['badsub']['sub'] = str("99") self.jwt['badsub'] = tostr(jwt.encode(self.claim['badsub'], secret, algorithm='HS256')) # generate invalid claim bad roles self.claim['badroles'] = copy(claim) self.claim['badroles']['roles'] = [ "badrole1", "badrole2" ] self.jwt['badroles'] = tostr(jwt.encode(self.claim['badroles'], secret, algorithm='HS256')) # generate valid claim with limited user:email role self.claim['user:email'] = copy(claim) self.claim['user:email']['roles'] = [ "user:email" ] self.jwt['user:email'] = tostr(jwt.encode(self.claim['user:email'], secret, algorithm='HS256')) # generate valid claim with limited user:emailnorest role self.claim['user:emailnorest'] = copy(claim) self.claim['user:emailnorest']['roles'] = [ "user:emailnorest" ] self.jwt['user:emailnorest'] = tostr(jwt.encode(self.claim['user:emailnorest'], secret, algorithm='HS256')) self.db.tx_Source = 'web' self.db.issue.addprop(tx_Source=hyperdb.String()) self.db.issue.addprop(anint=hyperdb.Integer()) self.db.issue.addprop(afloat=hyperdb.Number()) self.db.issue.addprop(abool=hyperdb.Boolean()) self.db.issue.addprop(requireme=hyperdb.String(required=True)) self.db.user.addprop(issue=hyperdb.Link('issue')) self.db.msg.addprop(tx_Source=hyperdb.String()) self.db.post_init() thisdir = os.path.dirname(__file__) vars = {} with open(os.path.join(thisdir, "tx_Source_detector.py")) as f: code = compile(f.read(), "tx_Source_detector.py", "exec") exec(code, vars) vars['init'](self.db) env = { 'PATH_INFO': 'http://localhost/rounduptest/rest/', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest' } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.server = RestfulInstance(self.dummy_client, self.db) self.db.Otk = self.db.getOTKManager() self.db.config['WEB_SECRET_KEY'] = "<KEY>" def tearDown(self): self.db.close() try: shutil.rmtree(self.dirname) except OSError as error: if error.errno not in (errno.ENOENT, errno.ESRCH): raise def get_header (self, header, not_found=None): try: return self.headers[header.lower()] except (AttributeError, KeyError, TypeError): return not_found def create_stati(self): try: self.db.status.create(name='open', order='9') except ValueError: pass try: self.db.status.create(name='closed', order='91') except ValueError: pass try: self.db.priority.create(name='normal') except ValueError: pass try: self.db.priority.create(name='critical') except ValueError: pass def create_sampledata(self): """ Create sample data common to some test cases """ self.create_stati() self.db.issue.create( title='foo1', status=self.db.status.lookup('open'), priority=self.db.priority.lookup('normal'), nosy = [ "1", "2" ] ) issue_open_norm = self.db.issue.create( title='foo2', status=self.db.status.lookup('open'), priority=self.db.priority.lookup('normal'), assignedto = "3" ) issue_open_crit = self.db.issue.create( title='foo5', status=self.db.status.lookup('open'), priority=self.db.priority.lookup('critical') ) def testGet(self): """ Retrieve all three users obtain data for 'joe' """ # Retrieve all three users. results = self.server.get_collection('user', self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['data']['collection']), 3) self.assertEqual(results['data']['@total_size'], 3) print(self.dummy_client.additional_headers["X-Count-Total"]) self.assertEqual( self.dummy_client.additional_headers["X-Count-Total"], "3" ) # Obtain data for 'joe'. results = self.server.get_element('user', self.joeid, self.empty_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['username'], 'joe') self.assertEqual(results['attributes']['realname'], '<NAME>') # Obtain data for 'joe' via username lookup. results = self.server.get_element('user', 'joe', self.empty_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['username'], 'joe') self.assertEqual(results['attributes']['realname'], '<NAME>') # Obtain data for 'joe' via username lookup (long form). key = 'username=joe' results = self.server.get_element('user', key, self.empty_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['username'], 'joe') self.assertEqual(results['attributes']['realname'], '<NAME>') # Obtain data for 'joe'. results = self.server.get_attribute( 'user', self.joeid, 'username', self.empty_form ) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['data'], 'joe') def testGetTransitive(self): """ Retrieve all issues with an 'o' in status sort by status.name (not order) """ base_path = self.db.config['TRACKER_WEB'] + 'rest/data/' #self.maxDiff=None self.create_sampledata() self.db.issue.set('2', status=self.db.status.lookup('closed')) self.db.issue.set('3', status=self.db.status.lookup('chatting')) expected={'data': {'@total_size': 2, 'collection': [ { 'id': '2', 'link': base_path + 'issue/2', 'assignedto.issue': None, 'status': { 'id': '10', 'link': base_path + 'status/10' } }, { 'id': '1', 'link': base_path + 'issue/1', 'assignedto.issue': None, 'status': { 'id': '9', 'link': base_path + 'status/9' } }, ]} } form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status.name', 'o'), cgi.MiniFieldStorage('@fields', 'status,assignedto.issue'), cgi.MiniFieldStorage('@sort', 'status.name'), ] results = self.server.get_collection('issue', form) self.assertDictEqual(expected, results) def testGetExactMatch(self): """ Retrieve all issues with an exact title """ base_path = self.db.config['TRACKER_WEB'] + 'rest/data/' #self.maxDiff=None self.create_sampledata() self.db.issue.set('2', title='This is an exact match') self.db.issue.set('3', title='This is an exact match') self.db.issue.set('1', title='This is AN exact match') expected={'data': {'@total_size': 2, 'collection': [ { 'id': '2', 'link': base_path + 'issue/2', }, { 'id': '3', 'link': base_path + 'issue/3', }, ]} } form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('title:', 'This is an exact match'), cgi.MiniFieldStorage('@sort', 'status.name'), ] results = self.server.get_collection('issue', form) self.assertDictEqual(expected, results) def testOutputFormat(self): """ test of @fields and @verbose implementation """ self.maxDiff = 4000 self.create_sampledata() base_path = self.db.config['TRACKER_WEB'] + 'rest/data/issue/' # Check formating for issues status=open; @fields and verbose tests form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'open'), cgi.MiniFieldStorage('@fields', 'nosy,status,creator'), cgi.MiniFieldStorage('@verbose', '2') ] expected={'data': {'@total_size': 3, 'collection': [ { 'creator': {'id': '3', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3', 'username': 'joe'}, 'status': {'id': '9', 'name': 'open', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9'}, 'id': '1', 'nosy': [ {'username': 'admin', 'id': '1', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/1'}, {'username': 'anonymous', 'id': '2', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/2'} ], 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1', 'title': 'foo1' }, { 'creator': {'id': '3', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3', 'username': 'joe'}, 'status': { 'id': '9', 'name': 'open', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9' }, 'id': '2', 'nosy': [ {'username': 'joe', 'id': '3', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3'} ], 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/2', 'title': 'foo2'}, {'creator': {'id': '3', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3', 'username': 'joe'}, 'status': { 'id': '9', 'name': 'open', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9'}, 'id': '3', 'nosy': [], 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3', 'title': 'foo5'} ]}} results = self.server.get_collection('issue', form) self.assertDictEqual(expected, results) # Check formating for issues status=open; @fields and verbose tests form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'open') # default cgi.MiniFieldStorage('@verbose', '1') ] expected={'data': {'@total_size': 3, 'collection': [ {'id': '1', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1',}, { 'id': '2', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/2'}, {'id': '3', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3'} ]}} results = self.server.get_collection('issue', form) self.assertDictEqual(expected, results) # Generate failure case, unknown field. form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'open'), cgi.MiniFieldStorage('@fields', 'title,foo') ] expected={'error': { 'msg': UsageError("Failed to find property 'foo' " "for class issue.",), 'status': 400}} results = self.server.get_collection('issue', form) # I tried assertDictEqual but seems it can't handle # the exception value of 'msg'. So I am using repr to check. self.assertEqual(repr(sorted(expected['error'])), repr(sorted(results['error'])) ) # Check formating for issues status=open; @fields and verbose tests form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'open'), cgi.MiniFieldStorage('@fields', 'nosy,status,assignedto'), cgi.MiniFieldStorage('@verbose', '0') ] expected={'data': { '@total_size': 3, 'collection': [ {'assignedto': None, 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1', 'status': '9', 'nosy': ['1', '2'], 'id': '1'}, {'assignedto': '3', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/2', 'status': '9', 'nosy': ['3'], 'id': '2'}, {'assignedto': None, 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3', 'status': '9', 'nosy': [], 'id': '3'}]}} results = self.server.get_collection('issue', form) print(results) self.assertDictEqual(expected, results) # check users form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@fields', 'username,queries,password'), cgi.MiniFieldStorage('@verbose', '0') ] # note this is done as user joe, so we only get queries # and password for joe. expected = {'data': {'collection': [ {'id': '1', 'username': 'admin', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/1'}, {'id': '2', 'username': 'anonymous', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/2'}, {'password': '[<PASSWORD>]', 'id': '3', 'queries': [], 'username': 'joe', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3'}], '@total_size': 3}} results = self.server.get_collection('user', form) self.assertDictEqual(expected, results) ## Start testing get_element form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@fields', 'queries,password,creator'), cgi.MiniFieldStorage('@verbose', '2') ] expected = {'data': { 'id': '3', 'type': 'user', '@etag': '', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/3', 'attributes': { 'creator': {'id': '1', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/1', 'username': 'admin'}, 'password': <PASSWORD>]', 'queries': [], 'username': 'joe' } }} results = self.server.get_element('user', self.joeid, form) results['data']['@etag'] = '' # etag depends on date, set to empty self.assertDictEqual(expected,results) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@fields', 'status:priority'), cgi.MiniFieldStorage('@verbose', '1') ] expected = {'data': { 'type': 'issue', 'id': '3', 'attributes': { 'status': { 'id': '9', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status/9'}, 'priority': { 'id': '1', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/priority/1'}}, '@etag': '', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3'}} results = self.server.get_element('issue', "3", form) results['data']['@etag'] = '' # etag depends on date, set to empty self.assertDictEqual(expected,results) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@fields', 'status,priority'), cgi.MiniFieldStorage('@verbose', '0') ] expected = {'data': { 'type': 'issue', 'id': '3', 'attributes': { 'status': '9', 'priority': '1'}, '@etag': '', 'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/3'}} results = self.server.get_element('issue', "3", form) results['data']['@etag'] = '' # etag depends on date, set to empty self.assertDictEqual(expected,results) def testSorting(self): self.maxDiff = 4000 self.create_sampledata() self.db.issue.set('1', status='7') self.db.issue.set('2', status='2') self.db.issue.set('3', status='2') self.db.commit() base_path = self.db.config['TRACKER_WEB'] + 'rest/data/issue/' # change some data for sorting on later form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@fields', 'status'), cgi.MiniFieldStorage('@sort', 'status,-id'), cgi.MiniFieldStorage('@verbose', '0') ] # status is sorted by orderprop (property 'order') # which provides the same ordering as the status ID expected={'data': { '@total_size': 3, 'collection': [ {'link': base_path + '3', 'status': '2', 'id': '3'}, {'link': base_path + '2', 'status': '2', 'id': '2'}, {'link': base_path + '1', 'status': '7', 'id': '1'}]}} results = self.server.get_collection('issue', form) self.assertDictEqual(expected, results) def testTransitiveField(self): """ Test a transitive property in @fields """ base_path = self.db.config['TRACKER_WEB'] + 'rest/data/' # create sample data self.create_stati() self.db.issue.create( title='foo4', status=self.db.status.lookup('closed'), priority=self.db.priority.lookup('critical') ) # Retrieve all issue @fields=status.name form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@fields', 'status.name') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) exp = [ {'link': base_path + 'issue/1', 'id': '1', 'status.name': 'closed'}] self.assertEqual(results['data']['collection'], exp) def testFilter(self): """ Retrieve all three users obtain data for 'joe' """ # create sample data self.create_stati() self.db.issue.create( title='foo4', status=self.db.status.lookup('closed'), priority=self.db.priority.lookup('critical') ) self.db.issue.create( title='foo1', status=self.db.status.lookup('open'), priority=self.db.priority.lookup('normal') ) issue_open_norm = self.db.issue.create( title='foo2 normal', status=self.db.status.lookup('open'), priority=self.db.priority.lookup('normal') ) issue_closed_norm = self.db.issue.create( title='foo3 closed normal', status=self.db.status.lookup('closed'), priority=self.db.priority.lookup('normal') ) issue_closed_crit = self.db.issue.create( title='foo4 closed', status=self.db.status.lookup('closed'), priority=self.db.priority.lookup('critical') ) issue_open_crit = self.db.issue.create( title='foo5', status=self.db.status.lookup('open'), priority=self.db.priority.lookup('critical') ) base_path = self.db.config['TRACKER_WEB'] + 'rest/data/issue/' # Retrieve all issue status=open form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'open') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertIn(get_obj(base_path, issue_open_norm), results['data']['collection']) self.assertIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn( get_obj(base_path, issue_closed_norm), results['data']['collection'] ) # Retrieve all issue status=closed and priority=critical form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'closed'), cgi.MiniFieldStorage('priority', 'critical') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertIn(get_obj(base_path, issue_closed_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn( get_obj(base_path, issue_closed_norm), results['data']['collection'] ) # Retrieve all issue status=closed and priority=normal,critical form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'closed'), cgi.MiniFieldStorage('priority', 'normal,critical') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertIn(get_obj(base_path, issue_closed_crit), results['data']['collection']) self.assertIn(get_obj(base_path, issue_closed_norm), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_norm), results['data']['collection']) # Retrieve all issue status=closed and priority=normal,critical # using duplicate priority key's. form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('status', 'closed'), cgi.MiniFieldStorage('priority', 'normal'), cgi.MiniFieldStorage('priority', 'critical') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertIn(get_obj(base_path, issue_closed_crit), results['data']['collection']) self.assertIn(get_obj(base_path, issue_closed_norm), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_norm), results['data']['collection']) # Retrieve all issues with title containing # closed, normal and 3 using duplicate title filterkeys form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('title', 'closed'), cgi.MiniFieldStorage('title', 'normal'), cgi.MiniFieldStorage('title', '3') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertNotIn(get_obj(base_path, issue_closed_crit), results['data']['collection']) self.assertIn(get_obj(base_path, issue_closed_norm), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_norm), results['data']['collection']) self.assertEqual(len(results['data']['collection']), 1) # Retrieve all issues (no hits) with title containing # closed, normal and foo3 in this order using title filter form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('title', 'closed normal foo3') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertNotIn(get_obj(base_path, issue_closed_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_closed_norm), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_norm), results['data']['collection']) self.assertEqual(len(results['data']['collection']), 0) # Retrieve all issues with title containing # foo3, closed and normal in this order using title filter form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('title', 'foo3 closed normal') ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertNotIn(get_obj(base_path, issue_closed_crit), results['data']['collection']) self.assertIn(get_obj(base_path, issue_closed_norm), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_norm), results['data']['collection']) self.assertEqual(len(results['data']['collection']), 1) # Retrieve all issues with word closed in title form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('title', 'closed'), ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertIn(get_obj(base_path, issue_closed_crit), results['data']['collection']) self.assertIn(get_obj(base_path, issue_closed_norm), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_crit), results['data']['collection']) self.assertNotIn(get_obj(base_path, issue_open_norm), results['data']['collection']) self.assertEqual(len(results['data']['collection']), 2) def testPagination(self): """ Test pagination. page_size is required and is an integer starting at 1. page_index is optional and is an integer starting at 1. Verify that pagination links are present if paging, @total_size and X-Count-Total header match number of items. """ # create sample data for i in range(0, random.randint(8,15)): self.db.issue.create(title='foo' + str(i)) # Retrieving all the issues results = self.server.get_collection('issue', self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) total_length = len(results['data']['collection']) # Verify no pagination links if paging not used self.assertFalse('@links' in results['data']) self.assertEqual(results['data']['@total_size'], total_length) self.assertEqual( self.dummy_client.additional_headers["X-Count-Total"], str(total_length) ) # Pagination will be 45% of the total result # So 2 full pages and 1 partial page. page_size = total_length * 45 // 100 page_one_expected = page_size page_two_expected = page_size page_three_expected = total_length - (2*page_one_expected) base_url="http://tracker.example/cgi-bin/roundup.cgi/" \ "bugs/rest/data/issue" # Retrieve page 1 form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@page_size', page_size), cgi.MiniFieldStorage('@page_index', 1) ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['data']['collection']), page_one_expected) self.assertTrue('@links' in results['data']) self.assertTrue('self' in results['data']['@links']) self.assertTrue('next' in results['data']['@links']) self.assertFalse('prev' in results['data']['@links']) self.assertEqual(results['data']['@links']['self'][0]['uri'], "%s?@page_index=1&@page_size=%s"%(base_url,page_size)) self.assertEqual(results['data']['@links']['next'][0]['uri'], "%s?@page_index=2&@page_size=%s"%(base_url,page_size)) page_one_results = results # save this for later # Retrieve page 2 form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@page_size', page_size), cgi.MiniFieldStorage('@page_index', 2) ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['data']['collection']), page_two_expected) self.assertTrue('@links' in results['data']) self.assertTrue('self' in results['data']['@links']) self.assertTrue('next' in results['data']['@links']) self.assertTrue('prev' in results['data']['@links']) self.assertEqual(results['data']['@links']['self'][0]['uri'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue?@page_index=2&@page_size=%s"%page_size) self.assertEqual(results['data']['@links']['next'][0]['uri'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue?@page_index=3&@page_size=%s"%page_size) self.assertEqual(results['data']['@links']['prev'][0]['uri'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue?@page_index=1&@page_size=%s"%page_size) self.assertEqual(results['data']['@links']['self'][0]['rel'], 'self') self.assertEqual(results['data']['@links']['next'][0]['rel'], 'next') self.assertEqual(results['data']['@links']['prev'][0]['rel'], 'prev') # Retrieve page 3 form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@page_size', page_size), cgi.MiniFieldStorage('@page_index', 3) ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['data']['collection']), page_three_expected) self.assertTrue('@links' in results['data']) self.assertTrue('self' in results['data']['@links']) self.assertFalse('next' in results['data']['@links']) self.assertTrue('prev' in results['data']['@links']) self.assertEqual(results['data']['@links']['self'][0]['uri'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue?@page_index=3&@page_size=%s"%page_size) self.assertEqual(results['data']['@links']['prev'][0]['uri'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue?@page_index=2&@page_size=%s"%page_size) # Verify that page_index is optional # Should start at page 1 form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@page_size', page_size), ] results = self.server.get_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['data']['collection']), page_size) self.assertTrue('@links' in results['data']) self.assertTrue('self' in results['data']['@links']) self.assertTrue('next' in results['data']['@links']) self.assertFalse('prev' in results['data']['@links']) self.assertEqual(page_one_results, results) # FIXME add tests for out of range once we decide what response # is needed to: # page_size < 0 # page_index < 0 def testRestRateLimit(self): self.db.config['WEB_API_CALLS_PER_INTERVAL'] = 20 self.db.config['WEB_API_INTERVAL_IN_SEC'] = 60 # Otk code never passes through the # retry loop. Not sure why but I can force it # through the loop by setting the internal _db_type # setting once the db is created by the previous command. try: self.db.Otk._db_type = whichdb("%s/%s"%(self.db.Otk.dir, self.db.Otk.name)) except AttributeError: # if dir attribute doesn't exist the primary db is not # sqlite or anydbm. So don't need to exercise code. pass print("Now realtime start:", datetime.utcnow()) # don't set an accept header; json should be the default # use up all our allowed api calls for i in range(20): # i is 0 ... 19 self.client_error_message = [] results = self.server.dispatch('GET', "/rest/data/user/%s/realname"%self.joeid, self.empty_form) # is successful self.assertEqual(self.server.client.response_code, 200) # does not have Retry-After header as we have # suceeded with this query self.assertFalse("Retry-After" in self.server.client.additional_headers) # remaining count is correct self.assertEqual( self.server.client.additional_headers["X-RateLimit-Remaining"], str(self.db.config['WEB_API_CALLS_PER_INTERVAL'] -1 - i) ) # trip limit self.server.client.additional_headers.clear() results = self.server.dispatch('GET', "/rest/data/user/%s/realname"%self.joeid, self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 429) self.assertEqual( self.server.client.additional_headers["X-RateLimit-Limit"], str(self.db.config['WEB_API_CALLS_PER_INTERVAL'])) self.assertEqual( self.server.client.additional_headers["X-RateLimit-Limit-Period"], str(self.db.config['WEB_API_INTERVAL_IN_SEC'])) self.assertEqual( self.server.client.additional_headers["X-RateLimit-Remaining"], '0') # value will be almost 60. Allow 1-2 seconds for all 20 rounds. self.assertAlmostEqual( float(self.server.client.additional_headers["X-RateLimit-Reset"]), 59, delta=1) self.assertEqual( str(self.server.client.additional_headers["Retry-After"]), "3") # check as string print("Reset:", self.server.client.additional_headers["X-RateLimit-Reset"]) print("Now realtime pre-sleep:", datetime.utcnow()) sleep(3.1) # sleep as requested so we can do another login print("Now realtime post-sleep:", datetime.utcnow()) # this should succeed self.server.client.additional_headers.clear() results = self.server.dispatch('GET', "/rest/data/user/%s/realname"%self.joeid, self.empty_form) print(results) print("Reset:", self.server.client.additional_headers["X-RateLimit-Reset-date"]) print("Now realtime:", datetime.utcnow()) print("Now ts header:", self.server.client.additional_headers["Now"]) print("Now date header:", self.server.client.additional_headers["Now-date"]) self.assertEqual(self.server.client.response_code, 200) self.assertEqual( self.server.client.additional_headers["X-RateLimit-Limit"], str(self.db.config['WEB_API_CALLS_PER_INTERVAL'])) self.assertEqual( self.server.client.additional_headers["X-RateLimit-Limit-Period"], str(self.db.config['WEB_API_INTERVAL_IN_SEC'])) self.assertEqual( self.server.client.additional_headers["X-RateLimit-Remaining"], '0') self.assertFalse("Retry-After" in self.server.client.additional_headers) # we still need to wait a minute for everything to clear self.assertAlmostEqual( float(self.server.client.additional_headers["X-RateLimit-Reset"]), 59, delta=1) # and make sure we need to wait another three seconds # as we consumed the last api call results = self.server.dispatch('GET', "/rest/data/user/%s/realname"%self.joeid, self.empty_form) self.assertEqual(self.server.client.response_code, 429) self.assertEqual( str(self.server.client.additional_headers["Retry-After"]), "3") # check as string json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['msg'], "Api rate limits exceeded. Please wait: 3 seconds.") # reset rest params self.db.config['WEB_API_CALLS_PER_INTERVAL'] = 0 self.db.config['WEB_API_INTERVAL_IN_SEC'] = 3600 def testEtagGeneration(self): ''' Make sure etag generation is stable This mocks date.Date() when creating the target to be etagged. Differing dates make this test impossible. ''' from roundup import date originalDate = date.Date dummy=date.Date('2000-06-26.00:34:02.0') # is a closure the best way to return a static Date object?? def dummyDate(adate=None): def dummyClosure(adate=None, translator=None): return dummy return dummyClosure date.Date = dummyDate() try: newuser = self.db.user.create( username='john', password=password.Password('<PASSWORD>', scheme='plaintext'), address='<EMAIL>', realname='JohnRandom', roles='User,Admin' ) # verify etag matches what we calculated in the past node = self.db.user.getnode(newuser) etag = calculate_etag(node, self.db.config['WEB_SECRET_KEY']) items = node.items(protected=True) # include every item print(repr(sorted(items))) print(etag) self.assertEqual(etag, '"07c3a7f214d394cf46220e294a5a53c8"') # modify key and verify we have a different etag etag = calculate_etag(node, self.db.config['WEB_SECRET_KEY'] + "a") items = node.items(protected=True) # include every item print(repr(sorted(items))) print(etag) self.assertNotEqual(etag, '"07c3a7f214d394cf46220e294a5a53c8"') # change data and verify we have a different etag node.username="Paul" etag = calculate_etag(node, self.db.config['WEB_SECRET_KEY']) items = node.items(protected=True) # include every item print(repr(sorted(items))) print(etag) self.assertEqual(etag, '"d655801d3a6d51e32891531b06ccecfa"') finally: date.Date = originalDate def testEtagProcessing(self): ''' Etags can come from two places: If-Match http header @etags value posted in the form Both will be checked if availble. If either one fails, the etag check will fail. Run over header only, etag in form only, both, each one broke and no etag. Use the put command to trigger the etag checking code. ''' for mode in ('header', 'etag', 'both', 'brokenheader', 'brokenetag', 'none'): try: # clean up any old header del(self.headers) except AttributeError: pass form = cgi.FieldStorage() etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('data', '<NAME>'), ] if mode == 'header': print("Mode = %s"%mode) self.headers = {'if-match': etag} elif mode == 'etag': print("Mode = %s"%mode) form.list.append(cgi.MiniFieldStorage('@etag', etag)) elif mode == 'both': print("Mode = %s"%mode) self.headers = {'etag': etag} form.list.append(cgi.MiniFieldStorage('@etag', etag)) elif mode == 'brokenheader': print("Mode = %s"%mode) self.headers = {'if-match': 'bad'} form.list.append(cgi.MiniFieldStorage('@etag', etag)) elif mode == 'brokenetag': print("Mode = %s"%mode) self.headers = {'if-match': etag} form.list.append(cgi.MiniFieldStorage('@etag', 'bad')) elif mode == 'none': print( "Mode = %s"%mode) else: self.fail("unknown mode found") results = self.server.put_attribute( 'user', self.joeid, 'realname', form ) if mode not in ('brokenheader', 'brokenetag', 'none'): self.assertEqual(self.dummy_client.response_code, 200) else: self.assertEqual(self.dummy_client.response_code, 412) def testBinaryFieldStorage(self): ''' attempt to exercise all paths in the BinaryFieldStorage class ''' expected={ "data": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1", "id": "1" } } body=b'{ "title": "<NAME> problems", \ "nosy": [ "1", "3" ], \ "assignedto": "2", \ "abool": true, \ "afloat": 2.3, \ "anint": 567890 \ }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json; version=1", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict,expected) def testDispatchPost(self): """ run POST through rest dispatch(). This also tests sending json payload through code as dispatch is the code that changes json payload into something we can process. """ # TEST #0 # POST: issue make joe assignee and admin and demo as # nosy # simulate: /rest/data/issue body=b'{ "title": "<NAME> problems", \ "nosy": [ "1", "3" ], \ "assignedto": "2", \ "abool": true, \ "afloat": 2.3, \ "anint": 567890 \ }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json; version=1", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 201) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['data']['link'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1") self.assertEqual(json_dict['data']['id'], "1") results = self.server.dispatch('GET', "/rest/data/issue/1", self.empty_form) print(results) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['data']['link'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue/1") self.assertEqual(json_dict['data']['attributes']['abool'], True) self.assertEqual(json_dict['data']['attributes']['afloat'], 2.3) self.assertEqual(json_dict['data']['attributes']['anint'], 567890) self.assertEqual(len(json_dict['data']['attributes']['nosy']), 3) self.assertEqual(json_dict['data']['attributes']\ ['assignedto']['link'], "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user/2") def testDispatchDelete(self): """ run Delete through rest dispatch(). """ # TEST #0 # Delete class raises unauthorized error # simulate: /rest/data/issue env = { "REQUEST_METHOD": "DELETE" } headers={"accept": "application/json; version=1", } self.headers=headers self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 403) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['msg'], "Deletion of a whole class disabled") def testDispatchBadContent(self): """ runthrough rest dispatch() with bad content_type patterns. """ # simulate: /rest/data/issue body=b'{ "title": "<NAME> has problems", \ "nosy": [ "1", "3" ], \ "assignedto": "2", \ "abool": true, \ "afloat": 2.3, \ "anint": 567890 \ }' env = { "CONTENT_TYPE": "application/jzot", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json; version=1", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 415) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['msg'], "Unable to process input of type application/jzot") # Test GET as well. I am not sure if this should pass or not. # Arguably GET doesn't use any form/json input but.... results = self.server.dispatch('GET', "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 415) def testDispatchBadAccept(self): # simulate: /rest/data/issue expect failure unknown accept settings body=b'{ "title": "<NAME> has problems", \ "nosy": [ "1", "3" ], \ "assignedto": "2", \ "abool": true, \ "afloat": 2.3, \ "anint": 567890 \ }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/zot; version=1; q=0.5", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 406) self.assertIn(b"Requested content type 'application/zot; version=1; q=0.5' is not available.\nAcceptable types: */*, application/json", results) # simulate: /rest/data/issue works, multiple acceptable output, one # is valid env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/zot; version=1; q=0.75, " "application/json; version=1; q=0.5", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 201) json_dict = json.loads(b2s(results)) # ERROR this should be 1. What's happening is that the code # for handling 406 error code runs through everything and creates # the item. Then it throws a 406 after the work is done when it # realizes it can't respond as requested. So the 406 post above # creates issue 1 and this one creates issue 2. self.assertEqual(json_dict['data']['id'], "2") # test 3 accept is empty. This triggers */* so passes headers={"accept": "", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 201) json_dict = json.loads(b2s(results)) # This is one more than above. Will need to be fixed # When error above is fixed. self.assertEqual(json_dict['data']['id'], "3") # test 4 accept is random junk. headers={"accept": "Xyzzy I am not a mime, type;", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 406) json_dict = json.loads(b2s(results)) self.assertIn('Unable to parse Accept Header. Invalid media type: Xyzzy I am not a mime. Acceptable types: */* application/json', json_dict['error']['msg']) # test 5 accept mimetype is ok, param is not headers={"accept": "*/*; foo", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch(env["REQUEST_METHOD"], "/rest/data/issue", form) print(results) self.assertEqual(self.server.client.response_code, 406) json_dict = json.loads(b2s(results)) self.assertIn('Unable to parse Accept Header. Invalid param: foo. Acceptable types: */* application/json', json_dict['error']['msg']) def testStatsGen(self): # check stats being returned by put and get ops # using dispatch which parses the @stats query param # find correct py2/py3 list comparison ignoring order try: list_test = self.assertCountEqual # py3 except AttributeError: list_test = self.assertItemsEqual # py2.7+ # get stats form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@stats', 'True'), ] results = self.server.dispatch('GET', "/rest/data/user/1/realname", form) self.assertEqual(self.dummy_client.response_code, 200) json_dict = json.loads(b2s(results)) # check that @stats are defined self.assertTrue( '@stats' in json_dict['data'] ) # check that the keys are present # not validating values as that changes valid_fields= [ us2u('elapsed'), us2u('cache_hits'), us2u('cache_misses'), us2u('get_items'), us2u('filtering') ] list_test(valid_fields,json_dict['data']['@stats'].keys()) # Make sure false value works to suppress @stats form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@stats', 'False'), ] results = self.server.dispatch('GET', "/rest/data/user/1/realname", form) self.assertEqual(self.dummy_client.response_code, 200) json_dict = json.loads(b2s(results)) print(results) # check that @stats are not defined self.assertTrue( '@stats' not in json_dict['data'] ) # Make sure non-true value works to suppress @stats # false will always work form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@stats', 'random'), ] results = self.server.dispatch('GET', "/rest/data/user/1/realname", form) self.assertEqual(self.dummy_client.response_code, 200) json_dict = json.loads(b2s(results)) print(results) # check that @stats are not defined self.assertTrue( '@stats' not in json_dict['data'] ) # if @stats is not defined there should be no stats results = self.server.dispatch('GET', "/rest/data/user/1/realname", self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) json_dict = json.loads(b2s(results)) # check that @stats are not defined self.assertTrue( '@stats' not in json_dict['data'] ) # change admin's realname via a normal web form # This generates a FieldStorage that looks like: # FieldStorage(None, None, []) # use etag from header # # Also use GET on the uri via the dispatch to retrieve # the results from the db. etag = calculate_etag(self.db.user.getnode('1'), self.db.config['WEB_SECRET_KEY']) headers={"if-match": etag, "accept": "application/vnd.json.test-v1+json", } form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('data', '<NAME>'), cgi.MiniFieldStorage('@apiver', '1'), cgi.MiniFieldStorage('@stats', 'true'), ] self.headers = headers self.server.client.request.headers.get = self.get_header self.db.setCurrentUser('admin') # must be admin to change user results = self.server.dispatch('PUT', "/rest/data/user/1/realname", form) self.assertEqual(self.dummy_client.response_code, 200) json_dict = json.loads(b2s(results)) list_test(valid_fields,json_dict['data']['@stats'].keys()) def testDispatch(self): """ run changes through rest dispatch(). This also tests sending json payload through code as dispatch is the code that changes json payload into something we can process. """ # TEST #1 # PUT: joe's 'realname' using json data. # simulate: /rest/data/user/<id>/realname # use etag in header etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) body=b'{ "data": "<NAME>" }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "PUT" } headers={"accept": "application/json; version=1", "content-type": env['CONTENT_TYPE'], "content-length": env['CONTENT_LENGTH'], "if-match": etag } self.headers=headers # we need to generate a FieldStorage the looks like # FieldStorage(None, None, 'string') rather than # FieldStorage(None, None, []) body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('PUT', "/rest/data/user/%s/realname"%self.joeid, form) self.assertEqual(self.server.client.response_code, 200) results = self.server.get_element('user', self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['realname'], '<NAME>') # substitute the version with an unacceptable version # and verify it returns 400 code. self.headers["accept"] = "application/json; version=1.1" body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('PUT', "/rest/data/user/%s/realname"%self.joeid, form) self.assertEqual(self.server.client.response_code, 400) del(self.headers) # TEST #2 # Set joe's 'realname' using json data. # simulate: /rest/data/user/<id>/realname # use etag in payload etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) etagb = etag.strip ('"') body=s2b('{ "@etag": "\\"%s\\"", "data": "<NAME>" }'%etagb) env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "PUT", } self.headers=None # have FieldStorage get len from env. body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=None, environ=env) self.server.client.request.headers.get=self.get_header headers={"accept": "application/json", "content-type": env['CONTENT_TYPE'], "if-match": etag } self.headers=headers # set for dispatch results = self.server.dispatch('PUT', "/rest/data/user/%s/realname"%self.joeid, form) self.assertEqual(self.server.client.response_code, 200) results = self.server.get_element('user', self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['realname'], '<NAME> 2') del(self.headers) # TEST #3 # change Joe's realname via a normal web form # This generates a FieldStorage that looks like: # FieldStorage(None, None, []) # use etag from header # # Also use GET on the uri via the dispatch to retrieve # the results from the db. etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) headers={"if-match": etag, "accept": "application/vnd.json.test-v1+json", } form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('data', '<NAME>'), cgi.MiniFieldStorage('@apiver', '1'), ] self.headers = headers self.server.client.request.headers.get = self.get_header results = self.server.dispatch('PUT', "/rest/data/user/%s/realname"%self.joeid, form) self.assertEqual(self.dummy_client.response_code, 200) results = self.server.dispatch('GET', "/rest/data/user/%s/realname"%self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['data']['data'], '<NAME>') self.assertEqual(json_dict['data']['link'], "http://tracker.example/cgi-bin/" "roundup.cgi/bugs/rest/data/user/3/realname") self.assertIn(json_dict['data']['type'], ("<class 'str'>", "<type 'str'>")) self.assertEqual(json_dict['data']["id"], "3") del(self.headers) # TEST #4 # PATCH: joe's email address with json # save address so we can use it later stored_results = self.server.get_element('user', self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) etagb = etag.strip ('"') body=s2b('{ "address": "<EMAIL>", "@etag": "\\"%s\\""}'%etagb) env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "PATCH" } headers={"accept": "application/json", "content-type": env['CONTENT_TYPE'], "content-length": len(body) } self.headers=headers body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('PATCH', "/rest/data/user/%s"%self.joeid, form) self.assertEqual(self.server.client.response_code, 200) results = self.server.get_element('user', self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['address'], '<EMAIL>') # and set it back reusing env and headers from last test etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) etagb = etag.strip ('"') body=s2b('{ "address": "%s", "@etag": "\\"%s\\""}'%( stored_results['data']['attributes']['address'], etagb)) # reuse env and headers from prior test. body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('PATCH', "/rest/data/user/%s"%self.joeid, form) self.assertEqual(self.server.client.response_code, 200) results = self.server.get_element('user', self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['address'], '<EMAIL>') del(self.headers) # TEST #5 # POST: create new issue # no etag needed etag = "not needed" body=b'{ "title": "foo bar", "priority": "critical" }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json", "content-type": env['CONTENT_TYPE'], "content-length": len(body) } self.headers=headers body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue", form) self.assertEqual(self.server.client.response_code, 201) json_dict = json.loads(b2s(results)) issue_id=json_dict['data']['id'] results = self.server.get_element('issue', str(issue_id), # must be a string not unicode self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['title'], 'foo bar') # TEST #6 # POST: an invalid class # no etag needed etag = "not needed" body=b'{ "title": "foo bar", "priority": "critical" }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json", "content-type": env['CONTENT_TYPE'], "content-length": len(body) } self.headers=headers body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/nonissue", form) self.assertEqual(self.server.client.response_code, 404) json_dict = json.loads(b2s(results)) status=json_dict['error']['status'] msg=json_dict['error']['msg'] self.assertEqual(status, 404) self.assertEqual(msg, 'Class nonissue not found') # TEST #7 # POST: status without key field of name # also test that version spec in accept header is accepted # no etag needed etag = "not needed" body=b'{ "order": 5 }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json; version=1", "content-type": env['CONTENT_TYPE'], "content-length": len(body) } self.headers=headers body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header self.db.setCurrentUser('admin') # must be admin to create status results = self.server.dispatch('POST', "/rest/data/status", form) self.assertEqual(self.server.client.response_code, 400) json_dict = json.loads(b2s(results)) status=json_dict['error']['status'] msg=json_dict['error']['msg'] self.assertEqual(status, 400) self.assertEqual(msg, "Must provide the 'name' property.") # TEST #8 # DELETE: delete issue 1 also test return type by extension # test bogus extension as well. etag = calculate_etag(self.db.issue.getnode("1"), self.db.config['WEB_SECRET_KEY']) etagb = etag.strip ('"') env = {"CONTENT_TYPE": "application/json", "CONTENT_LEN": 0, "REQUEST_METHOD": "DELETE" } # use text/plain header and request json output by appending # .json to the url. headers={"accept": "text/plain", "content-type": env['CONTENT_TYPE'], "if-match": '"%s"'%etagb, "content-length": 0, } self.headers=headers body_file=BytesIO(b'') # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header self.db.setCurrentUser('admin') # must be admin to delete issue results = self.server.dispatch('DELETE', "/rest/data/issue/1.json", form) self.assertEqual(self.server.client.response_code, 200) print(results) json_dict = json.loads(b2s(results)) status=json_dict['data']['status'] self.assertEqual(status, 'ok') results = self.server.dispatch('GET', "/rest/data/issuetitle:=asdf.jon", form) self.assertEqual(self.server.client.response_code, 406) print(results) try: # only verify local copy not system installed copy from roundup.dicttoxml import dicttoxml includexml = ', application/xml' except ImportError: includexml = '' response="Requested content type 'jon' is not available.\n" \ "Acceptable types: */*, application/json%s\n"%includexml self.assertEqual(b2s(results), response) # TEST #9 # GET: test that version can be set with accept: # ... ; version=z # or # application/vnd.x.y-vz+json # or # @apiver # simulate: /rest/data/issue form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@apiver', 'L'), ] headers={"accept": "application/json; notversion=z" } self.headers=headers self.server.client.request.headers.get=self.get_header results = self.server.dispatch('GET', "/rest/data/issue/1", form) print("9a: " + b2s(results)) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['status'], 400) self.assertEqual(json_dict['error']['msg'], "Unrecognized version: L. See /rest without " "specifying version for supported versions.") headers={"accept": "application/json; version=z" } self.headers=headers self.server.client.request.headers.get=self.get_header results = self.server.dispatch('GET', "/rest/data/issue/1", form) print("9b: " + b2s(results)) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['status'], 400) self.assertEqual(json_dict['error']['msg'], "Unrecognized version: z. See /rest without " "specifying version for supported versions.") headers={"accept": "application/vnd.roundup.test-vz+json" } self.headers=headers self.server.client.request.headers.get=self.get_header results = self.server.dispatch('GET', "/rest/data/issue/1", self.empty_form) print("9c:" + b2s(results)) self.assertEqual(self.server.client.response_code, 400) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['status'], 400) self.assertEqual(json_dict['error']['msg'], "Unrecognized version: z. See /rest without " "specifying version for supported versions.") # verify that version priority is correct; should be version=... headers={"accept": "application/vnd.roundup.test-vz+json; version=a" } self.headers=headers self.server.client.request.headers.get=self.get_header results = self.server.dispatch('GET', "/rest/data/issue/1", self.empty_form) print("9d: " + b2s(results)) self.assertEqual(self.server.client.response_code, 400) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['status'], 400) self.assertEqual(json_dict['error']['msg'], "Unrecognized version: a. See /rest without " "specifying version for supported versions.") # TEST #10 # check /rest and /rest/summary and /rest/notthere expected_rest = { "data": { "supported_versions": [ 1 ], "default_version": 1, "links": [ { "rel": "summary", "uri": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/summary" }, { "rel": "self", "uri": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest" }, { "rel": "data", "uri": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data" } ] } } self.headers={} results = self.server.dispatch('GET', "/rest", self.empty_form) print("10a: " + b2s(results)) self.assertEqual(self.server.client.response_code, 200) results_dict = json.loads(b2s(results)) self.assertEqual(results_dict, expected_rest) results = self.server.dispatch('GET', "/rest/", self.empty_form) print("10b: " + b2s(results)) self.assertEqual(self.server.client.response_code, 200) results_dict = json.loads(b2s(results)) self.assertEqual(results_dict, expected_rest) results = self.server.dispatch('GET', "/rest/summary", self.empty_form) print("10c: " + b2s(results)) self.assertEqual(self.server.client.response_code, 200) results = self.server.dispatch('GET', "/rest/summary/", self.empty_form) print("10d: " + b2s(results)) self.assertEqual(self.server.client.response_code, 200) expected_data = { "data": { "issue": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/issue" }, "priority": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/priority" }, "user": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/user" }, "query": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/query" }, "status": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/status" }, "keyword": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/keyword" }, "msg": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/msg" }, "file": { "link": "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/file" } } } results = self.server.dispatch('GET', "/rest/data", self.empty_form) print("10e: " + b2s(results)) self.assertEqual(self.server.client.response_code, 200) results_dict = json.loads(b2s(results)) self.assertEqual(results_dict, expected_data) results = self.server.dispatch('GET', "/rest/data/", self.empty_form) print("10f: " + b2s(results)) self.assertEqual(self.server.client.response_code, 200) results_dict = json.loads(b2s(results)) self.assertEqual(results_dict, expected_data) results = self.server.dispatch('GET', "/rest/notthere", self.empty_form) self.assertEqual(self.server.client.response_code, 404) results = self.server.dispatch('GET', "/rest/notthere/", self.empty_form) self.assertEqual(self.server.client.response_code, 404) del(self.headers) def testAcceptHeaderParsing(self): # TEST #1 # json highest priority self.server.client.request.headers.get=self.get_header headers={"accept": "application/json; version=1," "application/xml; q=0.5; version=2," "text/plain; q=0.75; version=2" } self.headers=headers results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 200) self.assertEqual(self.server.client.additional_headers['Content-Type'], "application/json") # TEST #2 # text highest priority headers={"accept": "application/json; q=0.5; version=1," "application/xml; q=0.25; version=2," "text/plain; q=1.0; version=3" } self.headers=headers results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 200) self.assertEqual(self.server.client.additional_headers['Content-Type'], "application/json") # TEST #3 # no acceptable type headers={"accept": "text/plain; q=1.0; version=2" } self.headers=headers results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 406) self.assertEqual(self.server.client.additional_headers['Content-Type'], "application/json") # TEST #4 # no accept header, should use default json headers={} self.headers=headers results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 200) self.assertEqual(self.server.client.additional_headers['Content-Type'], "application/json") # TEST #5 # wildcard accept header, should use default json headers={ "accept": "*/*"} self.headers=headers results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 200) self.assertEqual(self.server.client.additional_headers['Content-Type'], "application/json") # TEST #6 # invalid q factor if not ignored/demoted # application/json is selected with invalid version # and errors. # this ends up choosing */* which triggers json. self.server.client.request.headers.get=self.get_header headers={"accept": "application/json; q=1.5; version=99," "*/*; q=0.9; version=1," "text/plain; q=3.75; version=2" } self.headers=headers results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 200) self.assertEqual(self.server.client.additional_headers['Content-Type'], "application/json") ''' # only works if dicttoxml.py is installed. # not installed for testing # TEST #7 # xml wins headers={"accept": "application/json; q=0.5; version=2," "application/xml; q=0.75; version=1," "text/plain; q=1.0; version=2" } self.headers=headers results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 200) self.assertEqual(self.server.client.additional_headers['Content-Type'], "application/xml") ''' # TEST #8 # invalid api version # application/json is selected with invalid version self.server.client.request.headers.get=self.get_header headers={"accept": "application/json; version=99" } self.headers=headers with self.assertRaises(UsageError) as ctx: results = self.server.dispatch('GET', "/rest/data/status/1", self.empty_form) print(results) self.assertEqual(self.server.client.response_code, 200) self.assertEqual(ctx.exception.args[0], "Unrecognized version: 99. See /rest without " "specifying version for supported versions.") def testMethodOverride(self): # TEST #1 # Use GET, PUT, PATCH to tunnel DELETE expect error body=b'{ "order": 5 }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } body_file=BytesIO(body) # FieldStorage needs a file self.server.client.request.headers.get=self.get_header for method in ( "GET", "PUT", "PATCH" ): headers={"accept": "application/json; version=1", "content-type": env['CONTENT_TYPE'], "content-length": len(body), "x-http-method-override": "DElETE", } self.headers=headers form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.db.setCurrentUser('admin') # must be admin to create status results = self.server.dispatch(method, "/rest/data/status", form) self.assertEqual(self.server.client.response_code, 400) json_dict = json.loads(b2s(results)) status=json_dict['error']['status'] msg=json_dict['error']['msg'] self.assertEqual(status, 400) self.assertEqual(msg, "X-HTTP-Method-Override: DElETE must be " "used with POST method not %s."%method) # TEST #2 # DELETE: delete issue 1 via post tunnel self.assertFalse(self.db.status.is_retired("1")) etag = calculate_etag(self.db.status.getnode("1"), self.db.config['WEB_SECRET_KEY']) etagb = etag.strip ('"') headers={"accept": "application/json; q=1.0, application/xml; q=0.75", "if-match": '"%s"'%etagb, "content-length": 0, "x-http-method-override": "DElETE" } self.headers=headers body_file=BytesIO(b'') # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header self.db.setCurrentUser('admin') # must be admin to delete issue results = self.server.dispatch('POST', "/rest/data/status/1", form) print(results) self.assertEqual(self.server.client.response_code, 200) json_dict = json.loads(b2s(results)) status=json_dict['data']['status'] self.assertEqual(status, 'ok') self.assertTrue(self.db.status.is_retired("1")) def testPostPOE(self): ''' test post once exactly: get POE url, create issue using POE url. Use dispatch entry point. ''' import time # setup environment etag = "not needed" empty_body=b'' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(empty_body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json", "content-type": env['CONTENT_TYPE'], "content-length": len(empty_body) } self.headers=headers # use empty_body to test code path for missing/empty json body_file=BytesIO(empty_body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) ## Obtain the POE url. self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue/@poe", form) self.assertEqual(self.server.client.response_code, 200) json_dict = json.loads(b2s(results)) url=json_dict['data']['link'] # strip tracker web prefix leaving leading /. url = url[len(self.db.config['TRACKER_WEB'])-1:] ## create an issue using poe url. body=b'{ "title": "foo bar", "priority": "critical" }' env = { "CONTENT_TYPE": "application/json", "CONTENT_LENGTH": len(body), "REQUEST_METHOD": "POST" } headers={"accept": "application/json", "content-type": env['CONTENT_TYPE'], "content-length": len(body) } self.headers=headers body_file=BytesIO(body) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', url, form) self.assertEqual(self.server.client.response_code, 201) json_dict = json.loads(b2s(results)) issue_id=json_dict['data']['id'] results = self.server.get_element('issue', str(issue_id), # must be a string not unicode self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['title'], 'foo bar') ## Reuse POE url. It will fail. self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', url, form) # get the last component stripping the trailing / poe=url[url.rindex('/')+1:] self.assertEqual(self.server.client.response_code, 400) results = json.loads(b2s(results)) self.assertEqual(results['error']['status'], 400) self.assertEqual(results['error']['msg'], "POE token \'%s\' not valid."%poe) ## Try using GET on POE url. Should fail with method not ## allowed (405) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('GET', "/rest/data/issue/@poe", form) self.assertEqual(self.server.client.response_code, 405) ## Try creating generic POE url. body_poe=b'{"generic": "null", "lifetime": "100" }' body_file=BytesIO(body_poe) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue/@poe", form) json_dict = json.loads(b2s(results)) url=json_dict['data']['link'] # strip tracker web prefix leaving leading /. url = url[len(self.db.config['TRACKER_WEB'])-1:] url = url.replace('/issue/', '/keyword/') body_keyword=b'{"name": "keyword"}' body_file=BytesIO(body_keyword) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) results = self.server.dispatch('POST', url, form) self.assertEqual(self.server.client.response_code, 201) json_dict = json.loads(b2s(results)) url=json_dict['data']['link'] id=json_dict['data']['id'] self.assertEqual(id, "1") self.assertEqual(url, "http://tracker.example/cgi-bin/roundup.cgi/bugs/rest/data/keyword/1") ## Create issue POE url and try to use for keyword. ## This should fail. body_poe=b'{"lifetime": "100" }' body_file=BytesIO(body_poe) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue/@poe", form) json_dict = json.loads(b2s(results)) url=json_dict['data']['link'] # strip tracker web prefix leaving leading /. url = url[len(self.db.config['TRACKER_WEB'])-1:] url = url.replace('/issue/', '/keyword/') body_keyword=b'{"name": "keyword"}' body_file=BytesIO(body_keyword) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) results = self.server.dispatch('POST', url, form) poe=url[url.rindex('/')+1:] self.assertEqual(self.server.client.response_code, 400) json_dict = json.loads(b2s(results)) stat=json_dict['error']['status'] msg=json_dict['error']['msg'] self.assertEqual(stat, 400) self.assertEqual(msg, "POE token '%s' not valid for keyword, was generated for class issue"%poe) ## Create POE with 10 minute lifetime and verify ## expires is within 10 minutes. body_poe=b'{"lifetime": "30" }' body_file=BytesIO(body_poe) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue/@poe", form) json_dict = json.loads(b2s(results)) expires=int(json_dict['data']['expires']) # allow up to 3 seconds between time stamp creation # done under dispatch and this point. expected=int(time.time() + 30) print("expected=%d, expires=%d"%(expected,expires)) self.assertTrue((expected - expires) < 3 and (expected - expires) >= 0) ## Use a token created above as joe by a different user. self.db.setCurrentUser('admin') url=json_dict['data']['link'] # strip tracker web prefix leaving leading /. url = url[len(self.db.config['TRACKER_WEB'])-1:] body_file=BytesIO(body_keyword) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) results = self.server.dispatch('POST', url, form) print(results) self.assertEqual(self.server.client.response_code, 400) json_dict = json.loads(b2s(results)) # get the last component stripping the trailing / poe=url[url.rindex('/')+1:] self.assertEqual(json_dict['error']['msg'], "POE token '%s' not valid."%poe) ## Create POE with bogus lifetime body_poe=b'{"lifetime": "10.2" }' body_file=BytesIO(body_poe) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue/@poe", form) self.assertEqual(self.server.client.response_code, 400) print(results) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['msg'], "Value \'lifetime\' must be an integer specify " "lifetime in seconds. Got 10.2.") ## Create POE with lifetime > 1 hour body_poe=b'{"lifetime": "3700" }' body_file=BytesIO(body_poe) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue/@poe", form) self.assertEqual(self.server.client.response_code, 400) print(results) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['msg'], "Value 'lifetime' must be between 1 second and 1 " "hour (3600 seconds). Got 3700.") ## Create POE with lifetime < 1 second body_poe=b'{"lifetime": "-1" }' body_file=BytesIO(body_poe) # FieldStorage needs a file form = client.BinaryFieldStorage(body_file, headers=headers, environ=env) self.server.client.request.headers.get=self.get_header results = self.server.dispatch('POST', "/rest/data/issue/@poe", form) self.assertEqual(self.server.client.response_code, 400) print(results) json_dict = json.loads(b2s(results)) self.assertEqual(json_dict['error']['msg'], "Value 'lifetime' must be between 1 second and 1 " "hour (3600 seconds). Got -1.") del(self.headers) def testPutElement(self): """ Change joe's 'realname' Check if we can't change admin's detail """ # fail to change Joe's realname via attribute uri # no etag form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('data', '<NAME>') ] results = self.server.put_attribute( 'user', self.joeid, 'realname', form ) self.assertEqual(self.dummy_client.response_code, 412) results = self.server.get_attribute( 'user', self.joeid, 'realname', self.empty_form ) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['data'], '<NAME>') # change Joe's realname via attribute uri - etag in header form = cgi.FieldStorage() etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('data', '<NAME>'), ] self.headers = {'if-match': etag } # use etag in header results = self.server.put_attribute( 'user', self.joeid, 'realname', form ) self.assertEqual(self.dummy_client.response_code, 200) results = self.server.get_attribute( 'user', self.joeid, 'realname', self.empty_form ) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['data'], '<NAME>') del(self.headers) # Reset joe's 'realname'. etag in body # Also try to set protected items. The protected items should # be ignored on put_element to make it easy to get the item # with all fields, change one field and put the result without # having to filter out protected items. form = cgi.FieldStorage() etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('creator', '3'), cgi.MiniFieldStorage('realname', '<NAME>'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.put_element('user', self.joeid, form) self.assertEqual(self.dummy_client.response_code, 200) results = self.server.get_element('user', self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['realname'], '<NAME>') # We are joe, so check we can't change admin's details results = self.server.put_element('user', '1', form) self.assertEqual(self.dummy_client.response_code, 403) self.assertEqual(results['error']['status'], 403) # Try to reset joe's 'realname' and add a broken prop. # This should result in no change to the name and # a 400 UsageError stating prop does not exist. form = cgi.FieldStorage() etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('JustKidding', '3'), cgi.MiniFieldStorage('realname', '<NAME>'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.put_element('user', self.joeid, form) expected= {'error': {'status': 400, 'msg': UsageError('Property JustKidding not ' 'found in class user')}} self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 400) results = self.server.get_element('user', self.joeid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['realname'], '<NAME>') def testPutAttribute(self): # put protected property # make sure we don't have permission issues self.db.setCurrentUser('admin') form = cgi.FieldStorage() etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('data', '3'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.put_attribute( 'user', self.joeid, 'creator', form ) expected= {'error': {'status': 405, 'msg': AttributeError('\'"creator", "actor", "creation" and ' '"activity" are reserved\'')}} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 405) # put invalid property # make sure we don't have permission issues self.db.setCurrentUser('admin') form = cgi.FieldStorage() etag = calculate_etag(self.db.user.getnode(self.joeid), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('data', '3'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.put_attribute( 'user', self.joeid, 'youMustBeKiddingMe', form ) expected= {'error': {'status': 400, 'msg': UsageError("'youMustBeKiddingMe' " "is not a property of user")}} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 400) def testPost(self): """ Post a new issue with title: foo Verify the information of the created issue """ form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('title', 'foo') ] results = self.server.post_collection('issue', form) self.assertEqual(self.dummy_client.response_code, 201) issueid = results['data']['id'] results = self.server.get_element('issue', issueid, self.empty_form) self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['data']['attributes']['title'], 'foo') self.assertEqual(self.db.issue.get(issueid, "tx_Source"), 'web') def testPostFile(self): """ Post a new file with content: hello\r\nthere Verify the information of the created file """ form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('content', 'hello\r\nthere') ] results = self.server.post_collection('file', form) self.assertEqual(self.dummy_client.response_code, 201) fileid = results['data']['id'] results = self.server.get_element('file', fileid, self.empty_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['content'], {'link': 'http://tracker.example/cgi-bin/roundup.cgi/bugs/file1/'}) # File content is only shown with verbose=3 form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@verbose', '3'), cgi.MiniFieldStorage('@protected', 'true') ] results = self.server.get_element('file', fileid, form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['content'], 'hello\r\nthere') self.assertIn('creator', results['attributes']) # added by @protected self.assertEqual(results['attributes']['creator']['username'], "joe") def testAuthDeniedPut(self): """ Test unauthorized PUT request """ # Wrong permissions (caught by roundup security module). form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('realname', 'someone') ] results = self.server.put_element('user', '1', form) self.assertEqual(self.dummy_client.response_code, 403) self.assertEqual(results['error']['status'], 403) def testAuthDeniedPost(self): """ Test unauthorized POST request """ form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('username', 'blah') ] results = self.server.post_collection('user', form) self.assertEqual(self.dummy_client.response_code, 403) self.assertEqual(results['error']['status'], 403) def testAuthAllowedPut(self): """ Test authorized PUT request """ self.db.setCurrentUser('admin') form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('realname', 'someone') ] try: self.server.put_element('user', '2', form) except Unauthorised as err: self.fail('raised %s' % err) finally: self.db.setCurrentUser('joe') def testAuthAllowedPost(self): """ Test authorized POST request """ self.db.setCurrentUser('admin') form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('username', 'blah') ] try: self.server.post_collection('user', form) except Unauthorised as err: self.fail('raised %s' % err) finally: self.db.setCurrentUser('joe') def testDeleteAttributeUri(self): """ Test Delete an attribute """ self.maxDiff = 4000 # create a new issue with userid 1 in the nosy list issue_id = self.db.issue.create(title='foo', nosy=['1']) # No etag, so this should return 412 - Precondition Failed # With no changes results = self.server.delete_attribute( 'issue', issue_id, 'nosy', self.empty_form ) self.assertEqual(self.dummy_client.response_code, 412) results = self.server.get_element('issue', issue_id, self.empty_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['attributes']['nosy']), 1) self.assertListEqual(results['attributes']['nosy'], [{'id': '1', 'link': self.url_pfx + 'user/1'}]) form = cgi.FieldStorage() etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list.append(cgi.MiniFieldStorage('@etag', etag)) # remove the title and nosy results = self.server.delete_attribute( 'issue', issue_id, 'title', form ) self.assertEqual(self.dummy_client.response_code, 200) del(form.list[-1]) etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list.append(cgi.MiniFieldStorage('@etag', etag)) results = self.server.delete_attribute( 'issue', issue_id, 'nosy', form ) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['attributes']['nosy']), 0) self.assertListEqual(results['attributes']['nosy'], []) self.assertEqual(results['attributes']['title'], None) # delete protected property etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list.append(cgi.MiniFieldStorage('@etag', etag)) results = self.server.delete_attribute( 'issue', issue_id, 'creator', form ) expected= {'error': { 'status': 405, 'msg': AttributeError("Attribute 'creator' can not be updated for class issue.") }} self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 405) # delete required property etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list.append(cgi.MiniFieldStorage('@etag', etag)) results = self.server.delete_attribute( 'issue', issue_id, 'requireme', form ) expected= {'error': {'status': 400, 'msg': UsageError("Attribute 'requireme' is " "required by class issue and can not be deleted.")}} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(str(results['error']['msg']), str(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 400) # delete bogus property etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list.append(cgi.MiniFieldStorage('@etag', etag)) results = self.server.delete_attribute( 'issue', issue_id, 'nosuchprop', form ) expected= {'error': {'status': 400, 'msg': UsageError("Attribute 'nosuchprop' not valid " "for class issue.")}} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(str(results['error']['msg']), str(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 400) def testPatchAdd(self): """ Test Patch op 'Add' """ # create a new issue with userid 1 in the nosy list issue_id = self.db.issue.create(title='foo', nosy=['1']) # fail to add userid 2 to the nosy list # no etag form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'add'), cgi.MiniFieldStorage('nosy', '2') ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 412) etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'add'), cgi.MiniFieldStorage('nosy', '2'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertListEqual(results['attributes']['nosy'], ['1', '2']) etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'add'), cgi.MiniFieldStorage('data', '3'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_attribute('issue', issue_id, 'nosy', form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertListEqual(results['attributes']['nosy'], ['1', '2', '3']) # patch with no new_val/data etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'add'), cgi.MiniFieldStorage('data', ''), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_attribute('issue', issue_id, 'nosy', form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertListEqual(results['attributes']['nosy'], ['1', '2', '3']) # patch invalid property etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'add'), cgi.MiniFieldStorage('data', '3'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_attribute('issue', issue_id, 'notGoingToWork', form) self.assertEqual(self.dummy_client.response_code, 400) print(results) expected={'error': {'status': 400, 'msg': UsageError( HyperdbValueError( "'notGoingToWork' is not a property of issue",),)}} self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(str(results['error']['msg']), str(expected['error']['msg'])) def testPatchReplace(self): """ Test Patch op 'Replace' """ # create a new issue with userid 1 in the nosy list and status = 1 issue_id = self.db.issue.create(title='foo', nosy=['1'], status='1') # fail to replace userid 2 to the nosy list and status = 3 # no etag. form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'replace'), cgi.MiniFieldStorage('nosy', '2'), cgi.MiniFieldStorage('status', '3') ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 412) results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['status'], '1') self.assertListEqual(results['attributes']['nosy'], ['1']) # replace userid 2 to the nosy list and status = 3 etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'replace'), cgi.MiniFieldStorage('nosy', '2'), cgi.MiniFieldStorage('status', '3'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['status'], '3') self.assertListEqual(results['attributes']['nosy'], ['2']) # replace status = 2 using status attribute etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'replace'), cgi.MiniFieldStorage('data', '2'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_attribute('issue', issue_id, 'status', form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['status'], '2') # try to set a protected prop. It should fail. etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'replace'), cgi.MiniFieldStorage('creator', '2'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) expected= {'error': {'status': 400, 'msg': KeyError('"creator", "actor", "creation" and "activity" are reserved',)}} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(str(results['error']['msg']), str(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 400) # try to set a protected prop using patch_attribute. It should # fail with a 405 bad/unsupported method. etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'replace'), cgi.MiniFieldStorage('data', '2'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_attribute('issue', issue_id, 'creator', form) expected= {'error': {'status': 405, 'msg': AttributeError("Attribute 'creator' can not be updated for class issue.",)}} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(str(results['error']['msg']), str(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 405) def testPatchRemoveAll(self): """ Test Patch Action 'Remove' """ # create a new issue with userid 1 and 2 in the nosy list issue_id = self.db.issue.create(title='foo', nosy=['1', '2']) # fail to remove the nosy list and the title # no etag form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'remove'), cgi.MiniFieldStorage('nosy', ''), cgi.MiniFieldStorage('title', '') ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 412) results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['title'], 'foo') self.assertEqual(len(results['attributes']['nosy']), 2) self.assertEqual(results['attributes']['nosy'], ['1', '2']) # remove the nosy list and the title form = cgi.FieldStorage() etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('@op', 'remove'), cgi.MiniFieldStorage('nosy', ''), cgi.MiniFieldStorage('title', ''), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(results['attributes']['title'], None) self.assertEqual(len(results['attributes']['nosy']), 0) self.assertEqual(results['attributes']['nosy'], []) # try to remove a protected prop. It should fail. etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'remove'), cgi.MiniFieldStorage('creator', '2'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) expected= {'error': {'status': 400, 'msg': KeyError('"creator", "actor", "creation" and "activity" are reserved',)}} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(str(results['error']['msg']), str(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 400) # try to remove a required prop. it should fail etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('@op', 'remove'), cgi.MiniFieldStorage('requireme', ''), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) expected= {'error': {'status': 400, 'msg': UsageError("Attribute 'requireme' is required by class issue and can not be removed.") }} print(results) self.assertEqual(results['error']['status'], expected['error']['status']) self.assertEqual(type(results['error']['msg']), type(expected['error']['msg'])) self.assertEqual(str(results['error']['msg']), str(expected['error']['msg'])) self.assertEqual(self.dummy_client.response_code, 400) def testPatchAction(self): """ Test Patch Action 'Action' """ # create a new issue with userid 1 and 2 in the nosy list issue_id = self.db.issue.create(title='foo') # fail to execute action retire # no etag form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'action'), cgi.MiniFieldStorage('@action_name', 'retire') ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 412) self.assertFalse(self.db.issue.is_retired(issue_id)) # execute action retire form = cgi.FieldStorage() etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('@op', 'action'), cgi.MiniFieldStorage('@action_name', 'retire'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result self.assertTrue(self.db.issue.is_retired(issue_id)) # execute action restore form = cgi.FieldStorage() etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('@op', 'action'), cgi.MiniFieldStorage('@action_name', 'restore'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result self.assertTrue(not self.db.issue.is_retired(issue_id)) def testPatchBadAction(self): """ Test Patch Action 'Unknown' """ # create a new issue with userid 1 and 2 in the nosy list issue_id = self.db.issue.create(title='foo') # execute action retire form = cgi.FieldStorage() etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('@op', 'action'), cgi.MiniFieldStorage('@action_name', 'unknown'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 400) # verify the result, note order of allowed elements changes # for python2/3 so just check prefix. self.assertIn('action "unknown" is not supported, allowed: ', results['error']['msg'].args[0]) def testPatchRemove(self): """ Test Patch Action 'Remove' only some element from a list """ # create a new issue with userid 1, 2, 3 in the nosy list issue_id = self.db.issue.create(title='foo', nosy=['1', '2', '3']) # fail to remove the nosy list and the title # no etag form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'remove'), cgi.MiniFieldStorage('nosy', '1, 2'), ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 412) results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['attributes']['nosy']), 3) self.assertEqual(results['attributes']['nosy'], ['1', '2', '3']) # remove 1 and 2 from the nosy list form = cgi.FieldStorage() etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form.list = [ cgi.MiniFieldStorage('@op', 'remove'), cgi.MiniFieldStorage('nosy', '1, 2'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_element('issue', issue_id, form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['attributes']['nosy']), 1) self.assertEqual(results['attributes']['nosy'], ['3']) # delete last element: 3 etag = calculate_etag(self.db.issue.getnode(issue_id), self.db.config['WEB_SECRET_KEY']) form = cgi.FieldStorage() form.list = [ cgi.MiniFieldStorage('@op', 'remove'), cgi.MiniFieldStorage('data', '3'), cgi.MiniFieldStorage('@etag', etag) ] results = self.server.patch_attribute('issue', issue_id, 'nosy', form) self.assertEqual(self.dummy_client.response_code, 200) # verify the result results = self.server.get_element('issue', issue_id, self.terse_form) results = results['data'] self.assertEqual(self.dummy_client.response_code, 200) self.assertEqual(len(results['attributes']['nosy']), 0) self.assertListEqual(results['attributes']['nosy'], []) @skip_jwt def test_expired_jwt(self): # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) secret = self.db.config.WEB_JWT_SECRET # verify library and tokens are correct self.assertRaises(jwt.exceptions.InvalidTokenError, jwt.decode, self.jwt['expired'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) result = jwt.decode(self.jwt['user'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user'],result) result = jwt.decode(self.jwt['user:email'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user:email'],result) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh # set up for expired token first env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['expired'] self.dummy_client.main() # this will be the admin still as auth failed self.assertEqual('1', self.db.getuid()) self.assertEqual(out[0], b'Invalid Login - Signature has expired') del(out[0]) @skip_jwt def test_user_jwt(self): # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) secret = self.db.config.WEB_JWT_SECRET # verify library and tokens are correct self.assertRaises(jwt.exceptions.InvalidTokenError, jwt.decode, self.jwt['expired'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) result = jwt.decode(self.jwt['user'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user'],result) result = jwt.decode(self.jwt['user:email'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user:email'],result) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh # set up for standard user role token env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['user'] self.dummy_client.main() print(out[0]) json_dict = json.loads(b2s(out[0])) print(json_dict) # user will be joe id 3 as auth works self.assertTrue('3', self.db.getuid()) # there should be three items in the collection admin, anon, and joe self.assertEqual(3, len(json_dict['data']['collection'])) # since this token has no access to email addresses, only joe # should have email addresses. Order is by id by default. self.assertFalse('address' in json_dict['data']['collection'][0]) self.assertFalse('address' in json_dict['data']['collection'][1]) self.assertTrue('address' in json_dict['data']['collection'][2]) del(out[0]) self.db.setCurrentUser('admin') @skip_jwt def test_user_email_jwt(self): '''tests "Rest Access" permission present case''' # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) secret = self.db.config.WEB_JWT_SECRET # verify library and tokens are correct self.assertRaises(jwt.exceptions.InvalidTokenError, jwt.decode, self.jwt['expired'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) result = jwt.decode(self.jwt['user'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user'],result) result = jwt.decode(self.jwt['user:email'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user:email'],result) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh # set up for limited user:email role token env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['user:email'] self.dummy_client.main() json_dict = json.loads(b2s(out[0])) print(json_dict) # user will be joe id 3 as auth works self.assertTrue('3', self.db.getuid()) # there should be three items in the collection admin, anon, and joe self.assertEqual(3, len(json_dict['data']['collection'])) # However this token has access to email addresses, so all three # should have email addresses. Order is by id by default. self.assertTrue('address' in json_dict['data']['collection'][0]) self.assertTrue('address' in json_dict['data']['collection'][1]) self.assertTrue('address' in json_dict['data']['collection'][2]) @skip_jwt def test_user_emailnorest_jwt(self): '''tests "Rest Access" permission missing case''' # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) secret = self.db.config.WEB_JWT_SECRET # verify library and tokens are correct self.assertRaises(jwt.exceptions.InvalidTokenError, jwt.decode, self.jwt['expired'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) result = jwt.decode(self.jwt['user'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user'],result) result = jwt.decode(self.jwt['user:email'], secret, algorithms=['HS256'], audience=self.db.config.TRACKER_WEB, issuer=self.db.config.TRACKER_WEB) self.assertEqual(self.claim['user:email'],result) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh # set up for limited user:email role token env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['user:emailnorest'] self.dummy_client.main() json_dict = json.loads(b2s(out[0])) # user will be joe id 3 as auth works self.assertTrue('1', self.db.getuid()) { "error": { "status": 403, "msg": "Forbidden." } } self.assertTrue('error' in json_dict) self.assertTrue(json_dict['error']['status'], 403) self.assertTrue(json_dict['error']['msg'], "Forbidden.") @skip_jwt def test_disabled_jwt(self): # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh # disable jwt validation by making secret too short # use the default value for this in configure.py. self.db.config['WEB_JWT_SECRET'] = "disabled" env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['user'] self.dummy_client.main() # user will be 1 as there is no auth self.assertTrue('1', self.db.getuid()) self.assertEqual(out[0], b'Invalid Login - Support for jwt disabled by admin.') @skip_jwt def test_bad_issue_jwt(self): # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['badiss'] self.dummy_client.main() # user will be 1 as there is no auth self.assertTrue('1', self.db.getuid()) self.assertEqual(out[0], b'Invalid Login - Invalid issuer') @skip_jwt def test_bad_audience_jwt(self): # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['badaud'] self.dummy_client.main() # user will be 1 as there is no auth self.assertTrue('1', self.db.getuid()) self.assertEqual(out[0], b'Invalid Login - Invalid audience') @skip_jwt def test_bad_roles_jwt(self): # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['badroles'] self.dummy_client.main() # user will be 1 as there is no auth self.assertTrue('1', self.db.getuid()) self.assertEqual(out[0], b'Invalid Login - Token roles are invalid.') @skip_jwt def test_bad_subject_jwt(self): # self.dummy_client.main() closes database, so # we need a new test with setup called for each test out = [] def wh(s): out.append(s) # set environment for all jwt tests env = { 'PATH_INFO': 'rest/data/user', 'HTTP_HOST': 'localhost', 'TRACKER_NAME': 'rounduptest', "REQUEST_METHOD": "GET" } self.dummy_client = client.Client(self.instance, MockNull(), env, [], None) self.dummy_client.db = self.db self.dummy_client.request.headers.get = self.get_header self.empty_form = cgi.FieldStorage() self.terse_form = cgi.FieldStorage() self.terse_form.list = [ cgi.MiniFieldStorage('@verbose', '0'), ] self.dummy_client.form = cgi.FieldStorage() self.dummy_client.form.list = [ cgi.MiniFieldStorage('@fields', 'username,address'), ] # accumulate json output for further analysis self.dummy_client.write = wh env['HTTP_AUTHORIZATION'] = 'bearer %s'%self.jwt['badsub'] self.dummy_client.main() # user will be 1 as there is no auth self.assertTrue('1', self.db.getuid()) self.assertEqual(out[0], b'Invalid Login - Token subject is invalid.') def get_obj(path, id): return { 'id': id, 'link': path + id } if __name__ == '__main__': runner = unittest.TextTestRunner() unittest.main(testRunner=runner)
jerrykan/roundup
test/test_templating.py
from __future__ import print_function import unittest from cgi import FieldStorage, MiniFieldStorage from roundup.cgi.templating import * from .test_actions import MockNull, true import pytest from .pytest_patcher import mark_class if ReStructuredText: skip_rst = lambda func, *args, **kwargs: func else: skip_rst = mark_class(pytest.mark.skip( reason='ReStructuredText not available')) if StructuredText: skip_stext = lambda func, *args, **kwargs: func else: skip_stext = mark_class(pytest.mark.skip( reason='StructuredText not available')) import roundup.cgi.templating if roundup.cgi.templating._import_mistune(): skip_mistune = lambda func, *args, **kwargs: func else: skip_mistune = mark_class(pytest.mark.skip( reason='mistune not available')) if roundup.cgi.templating._import_markdown2(): skip_markdown2 = lambda func, *args, **kwargs: func else: skip_markdown2 = mark_class(pytest.mark.skip( reason='markdown2 not available')) if roundup.cgi.templating._import_markdown(): skip_markdown = lambda func, *args, **kwargs: func else: skip_markdown = mark_class(pytest.mark.skip( reason='markdown not available')) from roundup.anypy.strings import u2s, s2u class MockDatabase(MockNull): def getclass(self, name): # limit class names if name not in [ 'issue', 'user' ]: raise KeyError('There is no class called "%s"' % name) # Class returned must have hasnode(id) method that returns true # otherwise designators like 'issue1' can't be hyperlinked. self.classes[name].hasnode = lambda id: True if int(id) < 10 else False return self.classes[name] # setup for csrf testing of otks database api storage = {} def set(self, key, **props): MockDatabase.storage[key] = {} MockDatabase.storage[key].update(props) def get(self, key, field, default=None): if key not in MockDatabase.storage: return default return MockDatabase.storage[key][field] def exists(self,key): return key in MockDatabase.storage def getOTKManager(self): return MockDatabase() class TemplatingTestCase(unittest.TestCase): def setUp(self): self.form = FieldStorage() self.client = MockNull() self.client.db = db = MockDatabase() db.security.hasPermission = lambda *args, **kw: True self.client.form = self.form # add client props for testing anti_csrf_nonce self.client.session_api = MockNull(_sid="1234567890") self.client.db.getuid = lambda : 10 self.client.db.config = {'WEB_CSRF_TOKEN_LIFETIME': 10, 'MARKDOWN_BREAK_ON_NEWLINE': False } class HTMLDatabaseTestCase(TemplatingTestCase): def test_HTMLDatabase___getitem__(self): db = HTMLDatabase(self.client) self.assertTrue(isinstance(db['issue'], HTMLClass)) # following assertions are invalid # since roundup/cgi/templating.py r1.173. # HTMLItem is function, not class, # but HTMLUserClass and HTMLUser are passed on. # these classes are no more. they have ceased to be. #self.assertTrue(isinstance(db['user'], HTMLUserClass)) #self.assertTrue(isinstance(db['issue1'], HTMLItem)) #self.assertTrue(isinstance(db['user1'], HTMLUser)) def test_HTMLDatabase___getattr__(self): db = HTMLDatabase(self.client) self.assertTrue(isinstance(db.issue, HTMLClass)) # see comment in test_HTMLDatabase___getitem__ #self.assertTrue(isinstance(db.user, HTMLUserClass)) #self.assertTrue(isinstance(db.issue1, HTMLItem)) #self.assertTrue(isinstance(db.user1, HTMLUser)) def test_HTMLDatabase_classes(self): db = HTMLDatabase(self.client) db._db.classes = {'issue':MockNull(), 'user': MockNull()} db.classes() class FunctionsTestCase(TemplatingTestCase): def test_lookupIds(self): db = HTMLDatabase(self.client) def lookup(key): if key == 'ok': return '1' if key == 'fail': raise KeyError('fail') return key db._db.classes = {'issue': MockNull(lookup=lookup)} prop = MockNull(classname='issue') self.assertEqual(lookupIds(db._db, prop, ['1','2']), ['1','2']) self.assertEqual(lookupIds(db._db, prop, ['ok','2']), ['1','2']) self.assertEqual(lookupIds(db._db, prop, ['ok', 'fail'], 1), ['1', 'fail']) self.assertEqual(lookupIds(db._db, prop, ['ok', 'fail']), ['1']) def test_lookupKeys(self): db = HTMLDatabase(self.client) def get(entry, key): return {'1': 'green', '2': 'eggs'}.get(entry, entry) shrubbery = MockNull(get=get) db._db.classes = {'shrubbery': shrubbery} self.assertEqual(lookupKeys(shrubbery, 'spam', ['1','2']), ['green', 'eggs']) self.assertEqual(lookupKeys(shrubbery, 'spam', ['ok','2']), ['ok', 'eggs']) class HTMLClassTestCase(TemplatingTestCase) : def test_link(self): """Make sure lookup of a Link property works even in the presence of multiple values in the form.""" def lookup(key) : self.assertEqual(key, key.strip()) return "Status%s"%key self.form.list.append(MiniFieldStorage("status", "1")) self.form.list.append(MiniFieldStorage("status", "2")) status = hyperdb.Link("status") self.client.db.classes = dict \ ( issue = MockNull(getprops = lambda : dict(status = status)) , status = MockNull(get = lambda id, name : id, lookup = lookup) ) cls = HTMLClass(self.client, "issue") cls["status"] def test_multilink(self): """`lookup` of an item will fail if leading or trailing whitespace has not been stripped. """ def lookup(key) : self.assertEqual(key, key.strip()) return "User%s"%key self.form.list.append(MiniFieldStorage("nosy", "1, 2")) nosy = hyperdb.Multilink("user") self.client.db.classes = dict \ ( issue = MockNull(getprops = lambda : dict(nosy = nosy)) , user = MockNull(get = lambda id, name : id, lookup = lookup) ) cls = HTMLClass(self.client, "issue") cls["nosy"] def test_anti_csrf_nonce(self): '''call the csrf creation function and do basic length test Store the data in a mock db with the same api as the otk db. Make sure nonce is 64 chars long. Lookup the nonce in db and retrieve data. Verify that the nonce lifetime is correct (within 1 second of 1 week - lifetime), the uid is correct (1), the dummy sid is correct. Consider three cases: * create nonce via module function setting lifetime * create nonce via TemplatingUtils method setting lifetime * create nonce via module function with default lifetime ''' # the value below is number of seconds in a week. week_seconds = 604800 otks=self.client.db.getOTKManager() for test in [ 'module', 'template', 'default_time' ]: print("Testing:", test) if test == 'module': # test the module function nonce1 = anti_csrf_nonce(self.client, lifetime=1) # lifetime * 60 is the offset greater_than = week_seconds - 1 * 60 elif test == 'template': # call the function through the TemplatingUtils class cls = TemplatingUtils(self.client) nonce1 = cls.anti_csrf_nonce(lifetime=5) greater_than = week_seconds - 5 * 60 elif test == 'default_time': # use the module function but with no lifetime nonce1 = anti_csrf_nonce(self.client) # see above for web nonce lifetime. greater_than = week_seconds - 10 * 60 self.assertEqual(len(nonce1), 64) uid = otks.get(nonce1, 'uid', default=None) sid = otks.get(nonce1, 'sid', default=None) timestamp = otks.get(nonce1, '__timestamp', default=None) self.assertEqual(uid, 10) self.assertEqual(sid, self.client.session_api._sid) now = time.time() print("now, timestamp, greater, difference", now, timestamp, greater_than, now - timestamp) # lower bound of the difference is above. Upper bound # of difference is run time between time.time() in # the call to anti_csrf_nonce and the time.time() call # that assigns ts above. I declare that difference # to be less than 1 second for this to pass. self.assertEqual(True, greater_than <= now - timestamp < (greater_than + 1) ) def test_string_url_quote(self): ''' test that urlquote quotes the string ''' p = StringHTMLProperty(self.client, 'test', '1', None, 'test', 'test string< foo@bar') self.assertEqual(p.url_quote(), 'test%20string%3C%20foo%40bar') def test_string_email(self): ''' test that email obscures the email ''' p = StringHTMLProperty(self.client, 'test', '1', None, 'test', '<EMAIL>') self.assertEqual(p.email(), 'rouilj at foo example ...') def test_string_wrapped(self): test_string = ('A long string that needs to be wrapped to' ' 80 characters and no more. Put in a link issue1.' ' Put in <html> to be escaped. Put in a' ' https://example.com/link as well. Let us see if' ' it will wrap properly.' ) test_result = ('A long string that needs to be wrapped to 80' ' characters and no more. Put in a\n' 'link <a href="issue1">issue1</a>. Put in' ' &lt;html&gt; to be escaped. Put in a <a' ' href="https://example.com/link"' ' rel="nofollow noopener">' 'https://example.com/link</a> as\n' 'well. Let us see if it will wrap properly.') p = StringHTMLProperty(self.client, 'test', '1', None, 'test', test_string) self.assertEqual(p.wrapped(), test_result) def test_string_plain_or_hyperlinked(self): ''' test that email obscures the email ''' p = StringHTMLProperty(self.client, 'test', '1', None, 'test', 'A string <b> with <EMAIL> embedded &lt; html</b>') self.assertEqual(p.plain(), 'A string <b> with <EMAIL> embedded &lt; html</b>') self.assertEqual(p.plain(escape=1), 'A string &lt;b&gt; with <EMAIL> embedded &amp;lt; html&lt;/b&gt;') self.assertEqual(p.plain(hyperlink=1), 'A string &lt;b&gt; with <a href="mailto:<EMAIL>"><EMAIL></a> embedded &amp;lt; html&lt;/b&gt;') self.assertEqual(p.plain(escape=1, hyperlink=1), 'A string &lt;b&gt; with <a href="mailto:<EMAIL>"><EMAIL></a> embedded &amp;lt; html&lt;/b&gt;') self.assertEqual(p.hyperlinked(), 'A string &lt;b&gt; with <a href="mailto:<EMAIL>"><EMAIL></a> embedded &amp;lt; html&lt;/b&gt;') # check designators for designator in [ "issue1", "issue 1" ]: p = StringHTMLProperty(self.client, 'test', '1', None, 'test', designator) self.assertEqual(p.hyperlinked(), '<a href="issue1">%s</a>'%designator) # issue 100 > 10 which is a magic number for the mocked hasnode # If id number is greater than 10 hasnode reports it does not have # the node. for designator in ['issue100', 'issue 100']: p = StringHTMLProperty(self.client, 'test', '1', None, 'test', designator) self.assertEqual(p.hyperlinked(), designator) # zoom class does not exist for designator in ['zoom1', 'zoom100', 'zoom 1']: p = StringHTMLProperty(self.client, 'test', '1', None, 'test', designator) self.assertEqual(p.hyperlinked(), designator) @skip_rst def test_string_rst(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A string with <EMAIL> *embedded* \u00df')) # test case to make sure include directive is disabled q = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'\n\n.. include:: XyZrMt.html\n\n<badtag>\n\n')) q_result=u'''<div class="document"> <div class="system-message"> <p class="system-message-title">System Message: WARNING/2 (<tt class="docutils">&lt;string&gt;</tt>, line 3)</p> <p>&quot;include&quot; directive disabled.</p> <pre class="literal-block"> .. include:: XyZrMt.html </pre> </div> <p>&lt;badtag&gt;</p> </div> ''' # test case to make sure raw directive is disabled r = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'\n\n.. raw:: html\n\n <badtag>\n\n')) r_result='''<div class="document"> <div class="system-message"> <p class="system-message-title">System Message: WARNING/2 (<tt class="docutils">&lt;string&gt;</tt>, line 3)</p> <p>&quot;raw&quot; directive disabled.</p> <pre class="literal-block"> .. raw:: html &lt;badtag&gt; </pre> </div> </div> ''' # test case to make sure javascript and data url's aren't turned # into links s = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'<badtag>\njavascript:badcode data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==')) s_result = '<div class="document">\n<p>&lt;badtag&gt;\njavascript:badcode data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==</p>\n</div>\n' # test url recognition t = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'link is https://example.com/link for testing.')) t_result = '<div class="document">\n<p>link is <a class="reference external" href="https://example.com/link">https://example.com/link</a> for testing.</p>\n</div>\n' # test text that doesn't need to be processed u = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'Just a plain old string here. Nothig to process.')) u_result = '<div class="document">\n<p>Just a plain old string here. Nothig to process.</p>\n</div>\n' self.assertEqual(p.rst(), u2s(u'<div class="document">\n<p>A string with <a class="reference external" href="mailto:cmeerw&#64;example.com">cmeerw&#64;example.com</a> <em>embedded</em> \u00df</p>\n</div>\n')) self.assertEqual(q.rst(), u2s(q_result)) self.assertEqual(r.rst(), u2s(r_result)) self.assertEqual(s.rst(), u2s(s_result)) self.assertEqual(t.rst(), u2s(t_result)) self.assertEqual(u.rst(), u2s(u_result)) @skip_stext def test_string_stext(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A string with <EMAIL> *embedded* \u00df')) self.assertEqual(p.stext(), u2s(u'<p>A string with <a href="mailto:<EMAIL>"><EMAIL></a> <em>embedded</em> \u00df</p>\n')) def test_string_field(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', 'A string <b> with <EMAIL> embedded &lt; html</b>') self.assertEqual(p.field(), '<input name="test1@test" size="30" type="text" value="A string &lt;b&gt; with <EMAIL> embedded &amp;lt; html&lt;/b&gt;">') def test_string_multiline(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', 'A string <b> with <EMAIL> embedded &lt; html</b>') self.assertEqual(p.multiline(), '<textarea name="test1@test" id="test1@test" rows="5" cols="40">A string &lt;b&gt; with <EMAIL> embedded &amp;lt; html&lt;/b&gt;</textarea>') self.assertEqual(p.multiline(rows=300, cols=100, **{'class':'css_class'}), '<textarea class="css_class" name="test1@test" id="test1@test" rows="300" cols="100">A string &lt;b&gt; with <EMAIL> embedded &amp;lt; html&lt;/b&gt;</textarea>') def test_url_match(self): '''Test the URL regular expression in StringHTMLProperty. ''' def t(s, nothing=False, **groups): m = StringHTMLProperty.hyper_re.search(s) if nothing: if m: self.assertEqual(m, None, '%r matched (%r)'%(s, m.groupdict())) return else: self.assertNotEqual(m, None, '%r did not match'%s) d = m.groupdict() for g in groups: self.assertEqual(d[g], groups[g], '%s %r != %r in %r'%(g, d[g], groups[g], s)) #t('123.321.123.321', 'url') t('http://localhost/', url='http://localhost/') t('http://roundup.net/', url='http://roundup.net/') t('http://richard@localhost/', url='http://richard@localhost/') t('http://richard:sekrit@localhost/', url='http://richard:sekrit@localhost/') t('<HTTP://roundup.net/>', url='HTTP://roundup.net/') t('www.a.ex', url='www.a.ex') t('foo.a.ex', nothing=True) t('StDevValidTimeSeries.GetObservation', nothing=True) t('http://a.ex', url='http://a.ex') t('http://a.ex/?foo&bar=baz\\.@!$%()qwerty', url='http://a.ex/?foo&bar=baz\\.@!$%()qwerty') t('www.foo.net', url='www.foo.net') t('<EMAIL>', email='<EMAIL>') t('<EMAIL>', email='<EMAIL>') t('i1', **{'class':'i', 'id':'1'}) t('item123', **{'class':'item', 'id':'123'}) t('www.user:<EMAIL>', email='<EMAIL>') t('user:<EMAIL>', url='user:<EMAIL>') t('123.35', nothing=True) t('-.3535', nothing=True) def test_url_replace(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', '') def t(s): return p.hyper_re.sub(p._hyper_repl, s) ae = self.assertEqual ae(t('item123123123123'), 'item123123123123') ae(t('http://roundup.net/'), '<a href="http://roundup.net/" rel="nofollow noopener">http://roundup.net/</a>') ae(t('&lt;HTTP://roundup.net/&gt;'), '&lt;<a href="HTTP://roundup.net/" rel="nofollow noopener">HTTP://roundup.net/</a>&gt;') ae(t('&lt;http://roundup.net/&gt;.'), '&lt;<a href="http://roundup.net/" rel="nofollow noopener">http://roundup.net/</a>&gt;.') ae(t('&lt;www.roundup.net&gt;'), '&lt;<a href="http://www.roundup.net" rel="nofollow noopener">www.roundup.net</a>&gt;') ae(t('(www.roundup.net)'), '(<a href="http://www.roundup.net" rel="nofollow noopener">www.roundup.net</a>)') ae(t('foo http://msdn.microsoft.com/en-us/library/ms741540(VS.85).aspx bar'), 'foo <a href="http://msdn.microsoft.com/en-us/library/ms741540(VS.85).aspx" rel="nofollow noopener">' 'http://msdn.microsoft.com/en-us/library/ms741540(VS.85).aspx</a> bar') ae(t('(e.g. http://en.wikipedia.org/wiki/Python_(programming_language))'), '(e.g. <a href="http://en.wikipedia.org/wiki/Python_(programming_language)" rel="nofollow noopener">' 'http://en.wikipedia.org/wiki/Python_(programming_language)</a>)') ae(t('(e.g. http://en.wikipedia.org/wiki/Python_(programming_language)).'), '(e.g. <a href="http://en.wikipedia.org/wiki/Python_(programming_language)" rel="nofollow noopener">' 'http://en.wikipedia.org/wiki/Python_(programming_language)</a>).') ae(t('(e.g. http://en.wikipedia.org/wiki/Python_(programming_language))&gt;.'), '(e.g. <a href="http://en.wikipedia.org/wiki/Python_(programming_language)" rel="nofollow noopener">' 'http://en.wikipedia.org/wiki/Python_(programming_language)</a>)&gt;.') ae(t('(e.g. http://en.wikipedia.org/wiki/Python_(programming_language&gt;)).'), '(e.g. <a href="http://en.wikipedia.org/wiki/Python_(programming_language" rel="nofollow noopener">' 'http://en.wikipedia.org/wiki/Python_(programming_language</a>&gt;)).') for c in '.,;:!': # trailing punctuation is not included ae(t('http://roundup.net/%c ' % c), '<a href="http://roundup.net/" rel="nofollow noopener">http://roundup.net/</a>%c ' % c) # but it's included if it's part of the URL ae(t('http://roundup.net/%c/' % c), '<a href="http://roundup.net/%c/" rel="nofollow noopener">http://roundup.net/%c/</a>' % (c, c)) def test_input_html4(self): # boolean attributes are just the attribute name # indicate with attr=None or attr="attr" # e.g. disabled input=input_html4(required=None, size=30) self.assertEqual(input, '<input required size="30" type="text">') input=input_html4(required="required", size=30) self.assertEqual(input, '<input required="required" size="30" type="text">') attrs={"required": None, "class": "required", "size": 30} input=input_html4(**attrs) self.assertEqual(input, '<input class="required" required size="30" type="text">') attrs={"disabled": "disabled", "class": "required", "size": 30} input=input_html4(**attrs) self.assertEqual(input, '<input class="required" disabled="disabled" size="30" type="text">') def test_input_xhtml(self): # boolean attributes are attribute name="attribute name" # indicate with attr=None or attr="attr" # e.g. disabled="disabled" input=input_xhtml(required=None, size=30) self.assertEqual(input, '<input required="required" size="30" type="text"/>') input=input_xhtml(required="required", size=30) self.assertEqual(input, '<input required="required" size="30" type="text"/>') attrs={"required": None, "class": "required", "size": 30} input=input_xhtml(**attrs) self.assertEqual(input, '<input class="required" required="required" size="30" type="text"/>') attrs={"disabled": "disabled", "class": "required", "size": 30} input=input_xhtml(**attrs) self.assertEqual(input, '<input class="required" disabled="disabled" size="30" type="text"/>') # common markdown test cases class MarkdownTests: def mangleMarkdown2(self, s): ''' markdown2's rel=nofollow support on 'a' tags isn't programmable. So we are using it's builtin nofollow support. Mangle the string so that it matches the test case. turn: <a rel="nofollow" href="foo"> into <a href="foo" rel="nofollow noopener"> Also if it is a mailto url, we don't expect rel="nofollow", so delete it. turn: <a rel="nofollow" href="mailto:foo"> into <a href="mailto:foo"> Also when a title is present it is put in a different place from markdown, so fix it to normalize. turn: <a rel="nofollow" href="http://example.com/" title="a title"> into <a href="http://example.com/" rel="nofollow noopener" title="a title"> ''' if type(self) == Markdown2TestCase and s.find('a rel="nofollow"') != -1: if s.find('href="mailto:') == -1: # not a mailto url if 'rel="nofollow"' in s: if 'title="' in s: s = s.replace(' rel="nofollow" ', ' ').replace(' title=', ' rel="nofollow noopener" title=') else: s = s.replace(' rel="nofollow" ', ' ').replace('">', '" rel="nofollow noopener">') return s else: # a mailto url return s.replace(' rel="nofollow" ', ' ') return s def test_string_markdown(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A string with <br> *embedded* \u00df')) self.assertEqual(p.markdown().strip(), u2s(u'<p>A string with &lt;br&gt; <em>embedded</em> \u00df</p>')) def test_string_markdown_link(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A link <http://localhost>')) self.assertEqual(p.markdown().strip(), u2s(u'<p>A link <a href="http://localhost">http://localhost</a></p>')) def test_string_markdown_link_item(self): """ The link formats for the different markdown engines changes. Order of attributes, value for rel (noopener, nofollow etc) is different. So most tests check for a substring that indicates success rather than the entire returned string. """ p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'An issue1 link')) self.assertIn( u2s(u'href="issue1"'), p.markdown().strip()) # just verify that plain linking is working self.assertIn( u2s(u'href="issue1"'), p.plain(hyperlink=1)) p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'An [issue1](issue1) link')) self.assertIn( u2s(u'href="issue1"'), p.markdown().strip()) # just verify that plain linking is working self.assertIn( u2s(u'href="issue1"'), p.plain(hyperlink=1)) p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'An [issue1](https://example.com/issue1) link')) self.assertIn( u2s(u'href="https://example.com/issue1"'), p.markdown().strip()) p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'An [issue1] (https://example.com/issue1) link')) self.assertIn( u2s(u'href="issue1"'), p.markdown().strip()) if type(self) == MistuneTestCase: # mistune makes the https url into a real link self.assertIn( u2s(u'href="https://example.com/issue1"'), p.markdown().strip()) else: # the other two engines leave the parenthesized url as is. self.assertIn( u2s(u' (https://example.com/issue1) link'), p.markdown().strip()) def test_string_markdown_link(self): # markdown2 and markdown escape the email address try: from html import unescape as html_unescape except ImportError: from HTMLParser import HTMLParser html_unescape = HTMLParser().unescape p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A link <<EMAIL>>')) m = html_unescape(p.markdown().strip()) m = self.mangleMarkdown2(m) self.assertEqual(m, u2s(u'<p>A link <a href="mailto:<EMAIL>"><EMAIL></a></p>')) def test_string_markdown_javascript_link(self): # make sure we don't get a "javascript:" link p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'<javascript:alert(1)>')) self.assertTrue(p.markdown().find('href="javascript:') == -1) p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'[link](javascript:alert(1))')) self.assertTrue(p.markdown().find('href="javascript:') == -1) def test_string_markdown_data_link(self): # make sure we don't get a "data:" link p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'<data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==>')) print(p.markdown()) self.assertTrue(p.markdown().find('href="data:') == -1) p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'[data link](data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==)')) print(p.markdown()) self.assertTrue(p.markdown().find('href="data:') == -1) def test_string_markdown_forced_line_break(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'This is a set of text \n:that should have a break \n:at newlines. Each \n:colon should be the start of an html line')) # sigh different backends render this differently: # of text <br /> # of text<br> # etc. # Rather than using a different result for each # renderer, look for '<br' and require three of them. m = p.markdown() print(m) self.assertEqual(3, m.count('<br')) def test_string_markdown_code_block(self): ''' also verify that embedded html is escaped ''' p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'embedded code block <pre>\n\n```\nline 1\nline 2\n```\n\nnew </pre> paragraph')) self.assertEqual(p.markdown().strip().replace('\n\n', '\n'), u2s(u'<p>embedded code block &lt;pre&gt;</p>\n<pre><code>line 1\nline 2\n</code></pre>\n<p>new &lt;/pre&gt; paragraph</p>')) def test_string_markdown_code_block_attribute(self): ''' also verify that embedded html is escaped ''' p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'embedded code block <pre>\n\n``` python\nline 1\nline 2\n```\n\nnew </pre> paragraph')) m = p.markdown().strip() print(m) if type(self) == MistuneTestCase: self.assertEqual(m.replace('\n\n','\n'), '<p>embedded code block &lt;pre&gt;</p>\n<pre><code class="lang-python">line 1\nline 2\n</code></pre>\n<p>new &lt;/pre&gt; paragraph</p>') elif type(self) == MarkdownTestCase: self.assertEqual(m.replace('\n\n','\n'), '<p>embedded code block &lt;pre&gt;</p>\n<pre><code class="language-python">line 1\nline 2\n</code></pre>\n<p>new &lt;/pre&gt; paragraph</p>') else: self.assertEqual(m.replace('\n\n', '\n'), '<p>embedded code block &lt;pre&gt;</p>\n<div class="codehilite"><pre><span></span><code><span class="n">line</span> <span class="mi">1</span>\n<span class="n">line</span> <span class="mi">2</span>\n</code></pre></div>\n<p>new &lt;/pre&gt; paragraph</p>') def test_markdown_return_text_on_exception(self): ''' string is invalid markdown. missing end of fenced code block ''' p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'embedded code block <pre>\n\n``` python\nline 1\nline 2\n\n\nnew </pre> paragraph')) m = p.markdown().strip() print(m) self.assertEqual(m.replace('\n\n','\n'), '<p>embedded code block &lt;pre&gt;</p>\n<p>``` python\nline 1\nline 2</p>\n<p>new &lt;/pre&gt; paragraph</p>') def test_markdown_break_on_newline(self): self.client.db.config['MARKDOWN_BREAK_ON_NEWLINE'] = True p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A string with\nline break\ntwice.')) m = p.markdown() self.assertEqual(2, m.count('<br')) self.client.db.config['MARKDOWN_BREAK_ON_NEWLINE'] = False m = p.markdown() self.assertEqual(0, m.count('<br')) def test_markdown_hyperlinked_url(self): # classic markdown does not emit a \n at end of rendered string # so rstrip \n. p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'http://example.com/')) m = p.markdown(hyperlink=1) m = self.mangleMarkdown2(m) print(m) self.assertEqual(m.rstrip('\n'), '<p><a href="http://example.com/" rel="nofollow noopener">http://example.com/</a></p>') p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'<http://example.com/>')) m = p.markdown(hyperlink=1) m = self.mangleMarkdown2(m) self.assertEqual(m.rstrip('\n'), '<p><a href="http://example.com/" rel="nofollow noopener">http://example.com/</a></p>') p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'[label](http://example.com/ "a title")')) m = p.markdown(hyperlink=1) m = self.mangleMarkdown2(m) self.assertEqual(m.rstrip('\n'), '<p><a href="http://example.com/" rel="nofollow noopener" title="a title">label</a></p>') p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'[label](http://example.com/).')) m = p.markdown(hyperlink=1) m = self.mangleMarkdown2(m) self.assertEqual(m.rstrip('\n'), '<p><a href="http://example.com/" rel="nofollow noopener">label</a>.</p>') p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'![](http://example.com/)')) m = p.markdown(hyperlink=1) m = self.mangleMarkdown2(m) self.assertIn(m, [ '<p><img src="http://example.com/" alt=""/></p>\n', '<p><img src="http://example.com/" alt="" /></p>\n', '<p><img src="http://example.com/" alt=""></p>\n', '<p><img alt="" src="http://example.com/" /></p>', # markdown ]) p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'An URL http://example.com/ with text')) m = p.markdown(hyperlink=1) m = self.mangleMarkdown2(m) self.assertEqual(m.rstrip('\n'), '<p>An URL <a href="http://example.com/" rel="nofollow noopener">http://example.com/</a> with text</p>') p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'An URL https://example.com/path with text')) m = p.markdown(hyperlink=1) m = self.mangleMarkdown2(m) self.assertEqual(m.rstrip('\n'), '<p>An URL <a href="https://example.com/path" rel="nofollow noopener">https://example.com/path</a> with text</p>') @skip_mistune class MistuneTestCase(TemplatingTestCase, MarkdownTests) : def setUp(self): TemplatingTestCase.setUp(self) from roundup.cgi import templating self.__markdown = templating.markdown templating.markdown = templating._import_mistune() def tearDown(self): from roundup.cgi import templating templating.markdown = self.__markdown @skip_markdown2 class Markdown2TestCase(TemplatingTestCase, MarkdownTests) : def setUp(self): TemplatingTestCase.setUp(self) from roundup.cgi import templating self.__markdown = templating.markdown templating.markdown = templating._import_markdown2() def tearDown(self): from roundup.cgi import templating templating.markdown = self.__markdown @skip_markdown class MarkdownTestCase(TemplatingTestCase, MarkdownTests) : def setUp(self): TemplatingTestCase.setUp(self) from roundup.cgi import templating self.__markdown = templating.markdown templating.markdown = templating._import_markdown() def tearDown(self): from roundup.cgi import templating templating.markdown = self.__markdown class NoMarkdownTestCase(TemplatingTestCase) : def setUp(self): TemplatingTestCase.setUp(self) from roundup.cgi import templating self.__markdown = templating.markdown templating.markdown = None def tearDown(self): from roundup.cgi import templating templating.markdown = self.__markdown def test_string_markdown(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A string http://localhost with <EMAIL> <br> *embedded* \u00df')) self.assertEqual(p.markdown(), u2s(u'A string <a href="http://localhost" rel="nofollow noopener">http://localhost</a> with <a href="mailto:<EMAIL>"><EMAIL></a> &lt;br&gt; *embedded* \u00df')) class NoRstTestCase(TemplatingTestCase) : def setUp(self): TemplatingTestCase.setUp(self) from roundup.cgi import templating self.__ReStructuredText = templating.ReStructuredText templating.ReStructuredText = None def tearDown(self): from roundup.cgi import templating templating.ReStructuredText = self.__ReStructuredText def test_string_rst(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A string with <EMAIL> *embedded* \u00df')) self.assertEqual(p.rst(), u2s(u'A string with <a href="mailto:<EMAIL>"><EMAIL></a> *embedded* \u00df')) class NoStextTestCase(TemplatingTestCase) : def setUp(self): TemplatingTestCase.setUp(self) from roundup.cgi import templating self.__StructuredText = templating.StructuredText templating.StructuredText = None def tearDown(self): from roundup.cgi import templating templating.StructuredText = self.__StructuredText def test_string_stext(self): p = StringHTMLProperty(self.client, 'test', '1', None, 'test', u2s(u'A string with <EMAIL> *embedded* \u00df')) self.assertEqual(p.stext(), u2s(u'A string with <a href="mailto:<EMAIL>"><EMAIL></a> *embedded* \u00df')) r''' class HTMLPermissions: def is_edit_ok(self): def is_view_ok(self): def is_only_view_ok(self): def view_check(self): def edit_check(self): def input_html4(**attrs): def input_xhtml(**attrs): class HTMLInputMixin: def __init__(self): class HTMLClass(HTMLInputMixin, HTMLPermissions): def __init__(self, client, classname, anonymous=0): def __repr__(self): def __getitem__(self, item): def __getattr__(self, attr): def designator(self): def getItem(self, itemid, num_re=re.compile(r'-?\d+')): def properties(self, sort=1, cansearch=True): def list(self, sort_on=None): def csv(self): def propnames(self): def filter(self, request=None, filterspec={}, sort=(None,None), def classhelp(self, properties=None, label='(list)', width='500', def submit(self, label="Submit New Entry"): def history(self): def renderWith(self, name, **kwargs): class HTMLItem(HTMLInputMixin, HTMLPermissions): def __init__(self, client, classname, nodeid, anonymous=0): def __repr__(self): def __getitem__(self, item): def __getattr__(self, attr): def designator(self): def is_retired(self): def submit(self, label="Submit Changes"): def journal(self, direction='descending'): def history(self, direction='descending', dre=re.compile('\d+')): def renderQueryForm(self): class HTMLUserPermission: def is_edit_ok(self): def is_view_ok(self): def _user_perm_check(self, type): class HTMLUserClass(HTMLUserPermission, HTMLClass): class HTMLUser(HTMLUserPermission, HTMLItem): def __init__(self, client, classname, nodeid, anonymous=0): def hasPermission(self, permission, classname=_marker): class HTMLProperty(HTMLInputMixin, HTMLPermissions): def __init__(self, client, classname, nodeid, prop, name, value, def __repr__(self): def __str__(self): def __lt__(self, other): def __le__(self, other): def __eq__(self, other): def __ne__(self, other): def __gt__(self, other): def __ge__(self, other): def is_edit_ok(self): def is_view_ok(self): class StringHTMLProperty(HTMLProperty): def _hyper_repl(self, match): def hyperlinked(self): def plain(self, escape=0, hyperlink=0): def stext(self, escape=0): def field(self, size = 30): def multiline(self, escape=0, rows=5, cols=40): def email(self, escape=1): class PasswordHTMLProperty(HTMLProperty): def plain(self): def field(self, size = 30): def confirm(self, size = 30): class NumberHTMLProperty(HTMLProperty): def plain(self): def field(self, size = 30): def __int__(self): def __float__(self): class IntegerHTMLProperty(HTMLProperty): def plain(self): def field(self, size = 30): def __int__(self): class BooleanHTMLProperty(HTMLProperty): def plain(self): def field(self): class DateHTMLProperty(HTMLProperty): def plain(self): def now(self): def field(self, size = 30): def reldate(self, pretty=1): def pretty(self, format=_marker): def local(self, offset): class IntervalHTMLProperty(HTMLProperty): def plain(self): def pretty(self): def field(self, size = 30): class LinkHTMLProperty(HTMLProperty): def __init__(self, *args, **kw): def __getattr__(self, attr): def plain(self, escape=0): def field(self, showid=0, size=None): def menu(self, size=None, height=None, showid=0, additional=[], class MultilinkHTMLProperty(HTMLProperty): def __init__(self, *args, **kwargs): def __len__(self): def __getattr__(self, attr): def __getitem__(self, num): def __contains__(self, value): def reverse(self): def sorted(self, property, reverse=False): def plain(self, escape=0): def field(self, size=30, showid=0): def menu(self, size=None, height=None, showid=0, additional=[], def make_key_function(db, classname, sort_on=None): def keyfunc(a): def find_sort_key(linkcl): def handleListCGIValue(value): class ShowDict: def __init__(self, columns): def __getitem__(self, name): class HTMLRequest(HTMLInputMixin): def __init__(self, client): def _post_init(self): def updateFromURL(self, url): def update(self, kwargs): def description(self): def __str__(self): def indexargs_form(self, columns=1, sort=1, group=1, filter=1, def indexargs_url(self, url, args): def base_javascript(self): def batch(self): class Batch(ZTUtils.Batch): def __init__(self, client, sequence, size, start, end=0, orphan=0, def __getitem__(self, index): def propchanged(self, property): def previous(self): def next(self): #class TemplatingUtils: # def __init__(self, client): # def Batch(self, sequence, size, start, end=0, orphan=0, overlap=0): class NoTemplate(Exception): class Unauthorised(Exception): def __init__(self, action, klass): def __str__(self): class Loader: def __init__(self, dir): def precompileTemplates(self): def load(self, name, extension=None): def __getitem__(self, name): class RoundupPageTemplate(PageTemplate.PageTemplate): def getContext(self, client, classname, request): def render(self, client, classname, request, **options): def __repr__(self): ''' # vim: set et sts=4 sw=4 :
jerrykan/roundup
website/issues/detectors/rsswriter.py
#!/usr/bin/python # # RSS writer Roundup reactor # <NAME> <<EMAIL>> # import os import logging logger = logging.getLogger('detector') import sys # How many <item>s to have in the feed, at most. MAX_ITEMS = 30 # # Module metadata # __author__ = "<NAME> <<EMAIL>>" __copyright__ = "Copyright 2003 <NAME>" __version__ = "1.2" __changes__ = """ 1.1 29 Aug 2003 Produces valid pubDates. Produces pubDates and authors for change notes. Consolidates a message and change note into one item. Uses TRACKER_NAME in filename to produce one feed per tracker. Keeps to MAX_ITEMS limit more efficiently. 1.2 5 Sep 2003 Fixes bug with programmatically submitted issues having messages without summaries (?!). x.x 26 Feb 2017 <NAME> try to deal with truncation of rss file cause by error in parsing 8'bit characcters in input message. Further attempts to fix issue by modifying message bail on 0 length rss file. Delete it and retry. """ __license__ = 'MIT' # # Copyright 2003 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # The strftime format to use for <pubDate>s. RSS20_DATE_FORMAT = '%a, %d %b %Y %H:%M:%S %z' def newRss(title, link, description): """Returns an XML Document containing an RSS 2.0 feed with no items.""" import xml.dom.minidom rss = xml.dom.minidom.Document() root = rss.appendChild(rss.createElement("rss")) root.setAttribute("version", "2.0") root.setAttribute("xmlns:atom","http://www.w3.org/2005/Atom") channel = root.appendChild(rss.createElement("channel")) addEl = lambda tag,value: channel.appendChild(rss.createElement(tag)).appendChild(rss.createTextNode(value)) def addElA(tag,attr): node=rss.createElement(tag) for attr, val in attr.items(): node.setAttribute(attr, val) channel.appendChild(node) addEl("title", title) addElA('atom:link', attr={"rel": "self", "type": "application/rss+xml", "href": link + "@@file/rss.xml"}) addEl("link", link) addEl("description", description) return rss # has no items def writeRss(db, cl, nodeid, olddata): """ Reacts to a created or changed issue. Puts new messages and the change note in items in the RSS feed, as determined by the rsswriter.py FILENAME setting. If no RSS feed exists where FILENAME specifies, a new feed is created with rsswriter.newRss. """ # The filename of a tracker's RSS feed. Tracker config variables # are placed with the standard '%' operator syntax. FILENAME = "%s/rss.xml"%db.config['TEMPLATES'] # i.e., roundup.cgi/projects/_file/rss.xml # FILENAME = "/home/markpasc/public_html/%(TRACKER_NAME)s.xml" filename = FILENAME % db.config.__dict__ # return if issue is private # enable when private property is added ##if ( db.issue.get(nodeid, 'private') ): ## if __debug__: ## logger.debug("rss: Private issue. not generating rss") ## return if __debug__: logger.debug("rss: generating rss for issue %s", nodeid) # open the RSS import xml.dom.minidom from xml.parsers.expat import ExpatError try: rss = xml.dom.minidom.parse(filename) except IOError as e: if 2 != e.errno: raise # File not found rss = newRss( "%s tracker" % (db.config.TRACKER_NAME,), db.config.TRACKER_WEB, "Recent changes to the %s Roundup issue tracker" % (db.config.TRACKER_NAME,) ) except ExpatError as e: if os.path.getsize(filename) == 0: # delete the file, it's broke os.remove(filename) # create new rss file rss = newRss( "%s tracker" % (db.config.TRACKER_NAME,), db.config.TRACKER_WEB, "Recent changes to the %s Roundup issue tracker" % (db.config.TRACKER_NAME,) ) else: raise channel = rss.documentElement.getElementsByTagName('channel')[0] addEl = lambda parent,tag,value: parent.appendChild(rss.createElement(tag)).appendChild(rss.createTextNode(value)) issuelink = '%sissue%s' % (db.config.TRACKER_WEB, nodeid) if olddata: chg = cl.generateChangeNote(nodeid, olddata) else: chg = cl.generateCreateNote(nodeid) def addItem(desc, date, userid): """ Adds an RSS item to the RSS document. The title, link, and comments link are those of the current issue. desc: the description text to use date: an appropriately formatted string for pubDate userid: a Roundup user ID to use as author """ item = rss.createElement('item') addEl(item, 'title', db.issue.get(nodeid, 'title')) addEl(item, 'link', issuelink) addEl(item, 'guid', issuelink + '#' + date.replace(' ','+')) addEl(item, 'comments', issuelink) addEl(item, 'description', desc.replace('&','&amp;').replace('<','&lt;').replace('\n', '<br>\n')) addEl(item, 'pubDate', date) addEl(item, 'author', '%s' % ( db.user.get(userid, 'username') ) ) channel.appendChild(item) # add detectors directory to path if it's not there. # FIXME - see if this pollutes the sys.path for other # trackers. detector_path="%s/detectors"%(db.config.TRACKER_HOME) if ( sys.path.count(detector_path) == 0 ): sys.path.insert(0,detector_path) from nosyreaction import determineNewMessages for msgid in determineNewMessages(cl, nodeid, olddata): logger.debug("Processing new message msg%s for issue%s", msgid, nodeid) desc = db.msg.get(msgid, 'content') if desc and chg: desc += chg elif chg: desc = chg chg = None addItem(desc or '', db.msg.get(msgid, 'date').pretty(RSS20_DATE_FORMAT), db.msg.get(msgid, 'author')) if chg: from time import strftime addItem(chg.replace('\n----------\n', ''), strftime(RSS20_DATE_FORMAT), db.getuid()) for c in channel.getElementsByTagName('item')[0:-MAX_ITEMS]: # leaves at most MAX_ITEMS at the end channel.removeChild(c) # write the RSS out = open(filename, 'w') try: out.write(rss.toxml()) except Exception as e: # record the falure This should not happen. logger.error(e) out.close() # create 0 length file maybe?? But we handle above. raise # let the user know something went wrong. out.close() def init(db): db.issue.react('create', writeRss) db.issue.react('set', writeRss) #SHA: c4f916a13d533ff0c49386fc4f1f9f254adeb744
xoolive/edu_constraints
notebooks/solutions/lazy_nqueens.py
import facile def lazy_n_queens(n: int, *args, **kwargs) -> facile.Solution: queens = [facile.variable(range(n)) for i in range(n)] diag1 = [queens[i] + i for i in range(n)] diag2 = [queens[i] - i for i in range(n)] # facile.constraint(facile.alldifferent(queens)) for i, q1 in enumerate(queens): for q2 in queens[i + 1 :]: facile.constraint(q1 != q2) # facile.constraint(facile.alldifferent(diag1)) for i, q1 in enumerate(diag1): for q2 in diag1[i + 1 :]: facile.constraint(q1 != q2) # facile.constraint(facile.alldifferent(diag2)) for i, q1 in enumerate(diag2): for q2 in diag2[i + 1 :]: facile.constraint(q1 != q2) return facile.solve(queens, *args, **kwargs)
xoolive/edu_constraints
problems/picross/picross/__init__.py
from .loader import picross # noqa: F401
xoolive/edu_constraints
problems/airlines/airlines/tiny.py
Nv = 2 Na = 2 Ni = 2 Va = [0, 1, 2] Ov = [0, 1, 2] Dv = [0, 2, 1] Td = [0, 8, 12] Ta = [0, 9, 13] Dt = [[0, 0, 0], [0, 2, 25], [0, 25, 2]] Dtinf = 25 Np = [0, 80, 80] Nec = [0, 2, 2] Pr = [0, 100, 100] Ne = 5 Ty = [1, 1, 0, 0, 0] Vh = [1, 1, 1, 1, 2] Nvmax = 2 Dmax = 7 Dda = 2
xoolive/edu_constraints
problems/tatami/tatami_solve.py
<gh_stars>1-10 from __future__ import annotations import click import facile import matplotlib.pyplot as plt def tatami_solve(xmax: int, ymax: int) -> list[facile.Solution]: """Solves the tatami problem. The variables in the solve_all must be passed in order: - x coordinates; - y coordinates; - xs the size of the tatami on the x axis (1: vertical, 2: horizontal); - other variables """ if (xmax * ymax) & 1 == 1: raise ValueError(f"The room area must be an even number: {xmax * ymax}") n = xmax * ymax // 2 # noqa: F841 # start with a "simple" solve(), then comment the line when things work return [facile.solve([], backtrack=True)] # the evaluation process expects that you return *all* solutions return facile.solve_all([], backtrack=True) @click.command() @click.argument("xmax", type=int, default=4) @click.argument("ymax", type=int, default=3) def main(xmax: int, ymax: int): sol = tatami_solve(xmax, ymax) for solution in sol: print(solution) if solution.solution is None: continue n = len(solution.solution) // 3 x = solution.solution[:n] y = solution.solution[n : 2 * n] xs = solution.solution[2 * n :] fig, ax = plt.subplots() for (xi, yi, xsi) in zip(x, y, xs): ysi = 3 - xsi ax.fill([xi, xi, xi + xsi, xi + xsi], [yi, yi + ysi, yi + ysi, yi]) ax.set_xlim((0, xmax)) ax.set_ylim((0, ymax)) ax.set_aspect(1) ax.set_xticks(range(xmax + 1)) ax.set_yticks(range(ymax + 1)) plt.show() if __name__ == "__main__": main()
xoolive/edu_constraints
notebooks/solutions/send_more_money.py
import facile import functools # The list comprehension mechanism is always helpful! [s, e, n, d, m, o, r, y] = [facile.variable(range(10)) for i in range(8)] # A shortcut letters = [s, e, n, d, m, o, r, y] # Constraints facile.constraint(s > 0) facile.constraint(m > 0) facile.constraint(facile.alldifferent(letters)) send = functools.reduce(lambda x, y: 10 * x + y, [s, e, n, d]) more = functools.reduce(lambda x, y: 10 * x + y, [m, o, r, e]) money = functools.reduce(lambda x, y: 10 * x + y, [m, o, n, e, y]) facile.constraint(send + more == money) if facile.solve(letters): [vs, ve, vn, vd, vm, vo, vr, vy] = [x.value() for x in letters] print("Solution found :") print print(" %d%d%d%d" % (vs, ve, vn, vd)) print("+ %d%d%d%d" % (vm, vo, vr, ve)) print("------") print(" %d%d%d%d%d" % (vm, vo, vn, ve, vy)) else: print("No solution found")
xoolive/edu_constraints
notebooks/solutions/send_more_money_wrong.py
<reponame>xoolive/edu_constraints<filename>notebooks/solutions/send_more_money_wrong.py import facile # The list comprehension mechanism is always helpful! [s, e, n, d, m, o, r, y] = [facile.variable(range(10)) for i in range(8)] # A shortcut letters = [s, e, n, d, m, o, r, y] # Retenues [c0, c1, c2] = [facile.variable([0, 1]) for i in range(3)] # Constraints # facile.constraint(s > 0) # facile.constraint(m > 0) facile.constraint(facile.alldifferent(letters)) facile.constraint(d + e == y + 10 * c0) facile.constraint(c0 + n + r == e + 10 * c1) facile.constraint(c1 + e + o == n + 10 * c2) facile.constraint(c2 + s + m == o + 10 * m) if facile.solve(letters): [vs, ve, vn, vd, vm, vo, vr, vy] = [x.value() for x in letters] print("Solution found :") print print(" %d%d%d%d" % (vs, ve, vn, vd)) print("+ %d%d%d%d" % (vm, vo, vr, ve)) print("------") print(" %d%d%d%d%d" % (vm, vo, vn, ve, vy)) else: print("No solution found")
xoolive/edu_constraints
problems/airlines/airlines/__init__.py
<gh_stars>1-10 from . import tiny as tiny_instance from . import small as small_instance from . import normal as normal_instance __all__ = ["tiny", "small", "normal"] instances = { "tiny": tiny_instance, "small": small_instance, "normal": normal_instance, } def get_instance(name: str): module = instances[name] return dict( (key, getattr(module, key)) for key in dir(module) if not key.startswith("_") ) tiny = get_instance("tiny") small = get_instance("small") normal = get_instance("normal")
xoolive/edu_constraints
problems/picross/picross_solve.py
from __future__ import annotations import signal import sys import click import facile from picross import picross def picross_solve( lines: list[list[int]], columns: list[list[int]], ) -> tuple[facile.Solution, facile.Array]: n, m = len(lines), len(columns) grid = facile.Array.binary((n, m)) sol = facile.solve(grid) return sol, grid @click.command(help="Picross solver program") @click.argument("name", default="moon") def main(name: str) -> None: lines, columns = picross[name] def signal_handler(signal, frame): print("You pressed Ctrl+C!") sys.exit(1) signal.signal(signal.SIGINT, signal_handler) sol, grid = picross_solve(lines, columns) print(sol) for line in grid.value(): for item in line: if item == 1: print("█", end="") else: print("·", end="") print() if __name__ == "__main__": main()
xoolive/edu_constraints
problems/picross/picross/loader.py
<filename>problems/picross/picross/loader.py<gh_stars>1-10 from __future__ import annotations from collections import UserDict from pathlib import Path __all__ = ["picross"] class PicrossLoader(UserDict): def __getitem__(self, name: str) -> tuple[list[list[int]], list[list[int]]]: problem = UserDict.__getitem__(self, name) lines = [ [int(s) for s in s_.split(",")] for s_ in problem["lines"].split(" ") ] columns = [ [int(s) for s in s_.split(",")] for s_ in problem["columns"].split(" ") ] return lines, columns def __missing__(self, name: str): filename = Path(__file__).parent / f"{name}.non" print(filename) if not filename.exists(): raise AttributeError(f"{name} does not exist.") with filename.open("r") as fh: lines = [] columns = [] rows_flag = False columns_flag = False for line in fh.readlines(): line = line.strip() if line == "rows": rows_flag = True columns_flag = False continue if line == "columns": rows_flag = False columns_flag = True continue if line == "": continue if rows_flag: lines.append(line) if columns_flag: columns.append(line) return {"lines": " ".join(lines), "columns": " ".join(columns)} picross = PicrossLoader( { "moon": {"lines": "2 2 1,2 5 3", "columns": "2 2 1,2 5 3"}, "star": {"lines": "2,2 2,2 0 1,1 1,1,1", "columns": "2,2 2 1 2 2,2"}, "cat": { "lines": "1,1 2,2 5 1,1,1 7 5,2 3,1 3,1 4,2 7", "columns": "1 6 2,6 8 2,6 6,2 1,1 1 1,2 4", }, "horse": { "lines": "1 4 4,1 8 2,2 3,3 1,5 1,2,2,1 3,3 8", "columns": "2,3 2,2 5,3 8,1 1,2,1 1,1,1 1,3,1 7 3,2 2,2", }, "house": { "lines": ( "1 2,5 2,2,1,2 11 5,1,5 15 1,1 1,5,1 1,1,1,1,5,1 " "1,5,5,1 1,1,1,1,5,1 1,5,5,1 1,5,1 1,5,1 1,5,1" ), "columns": ( "10 5 5,5 3,1,1,1 4,5 5,1,1,1 1,1,1,5 6 1,1,1,7 " "5,7 4,7 3,7 2,7 2 10" ), }, "duck": { "lines": "3 5 4,3 7 5 3 5 1,8 3,3,3 7,3,2 5,4,2 8,2 10 2,3 6", "columns": ( "3 4 5 4 5 6 3,2,1 2,2,5 4,2,6 8,2,3 8,2,1,1 2,6,2,1 " "4,6 2,4 1" ), }, } )
yossiz16/microcOSM
images/tegola/start.py
#!/usr/bin/env python3 import time from datetime import datetime import signal import os import glob import sys from jsonlogger.logger import JSONLogger from osmeterium.run_command import run_command, run_command_async EXPIRE_TILES_DIR = os.environ.get('EXPIRE_TILES_DIR', '/mnt/expiretiles') CONFIG_PATH = '/opt/tegola_config/config.toml' EXPIRE_TILES_LIST_FILE = 'expire_tiles.txt' MAX_ZOOM = os.environ['TILER_CACHE_MAX_ZOOM'] MIN_ZOOM = os.environ['TILER_CACHE_MIN_ZOOM'] INTERVAL = os.environ['TILER_CACHE_UPDATE_INTERVAL'] os.environ["PATH"] = os.environ.get("PATH") + ":/opt" def purgeExpireTiles(): with open(EXPIRE_TILES_LIST_FILE, 'w') as writer: for filepath in glob.iglob(f'{EXPIRE_TILES_DIR}/**/*.tiles', recursive=True): with open(filepath, 'r') as reader: tiles = reader.readlines() for tile in tiles: writer.write(tile) os.remove(filepath) if os.path.getsize(EXPIRE_TILES_LIST_FILE) != 0: # if file is not empty log.info("Remove expire tiles from cache...") tegola_cache_command = 'tegola cache purge tile-list {0} --min-zoom={1} --max-zoom={2} --config={3}'.format( EXPIRE_TILES_LIST_FILE, MIN_ZOOM, MAX_ZOOM, CONFIG_PATH) run_command(tegola_cache_command, log.info, log.error, terminate_on_tegola_exit, lambda: None) def terminate_on_tegola_exit(exit_code=0): log.error('tegola terminated with error code {}'.format(exit_code)) os.kill(os.getpid(), signal.SIGINT) def main(): log.info("Starting tiles server!") tegola_serve_command = 'tegola serve --config={0}'.format(CONFIG_PATH) _ = run_command_async( tegola_serve_command, log.info, log.error, terminate_on_tegola_exit, terminate_on_tegola_exit) while True: now = datetime.now() log.info("Updating cache {0}".format( now.strftime("%d/%m/%Y %H:%M:%S"))) purgeExpireTiles() time.sleep(int(INTERVAL)) if __name__ == '__main__': log = JSONLogger('main-debug', additional_fields={'service': 'tegola'}) main()
yossiz16/microcOSM
images/mod-tile/start.py
<reponame>yossiz16/microcOSM import psycopg2 import re import subprocess import sys import time from os import path, linesep, environ, mkdir from jsonlogger.logger import JSONLogger from osmeterium.run_command import run_command_async, run_command SEQUENCE_PATH_DENOMINATORS = [1000000, 1000, 1] CARTO_FILE = '/src/openstreetmap-carto/project.mml' EXPIRED_DIRECTORY = environ.get('EXPIRED_DIRECTORY', '/mnt/expired') RENDER_EXPIRED_TILES_INTERVAL = float(environ.get('RENDER_EXPIRED_TILES_INTERVAL', 60)) TILE_EXPIRE_MIN_ZOOM = int(environ.get('TILE_EXPIRE_MIN_ZOOM', 14)) db_config = { 'osm_db_name':environ['OSM_POSTGRES_DB'], 'osm_host':environ['OSM_POSTGRES_HOST'], 'osm_password':environ['OSM_POSTGRES_PASSWORD'], 'osm_user':environ['OSM_POSTGRES_USER'], 'et_db_name':environ['EARTH_TILES_POSTGRES_DB'], 'et_host':environ['EARTH_TILES_POSTGRES_HOST'], 'et_password':environ['EARTH_TILES_POSTGRES_PASSWORD'], 'et_user':environ['EARTH_TILES_POSTGRES_USER'] } def extract_positivie_integer_value(text, key): """ Extract an integer value for a given key in a text Args: text (str): text to extract value from key (str): key to extract value for Raises: ValueError: value is not a positive integer Returns: int: extraced value """ found = re.search(fr'{key}=\d+', text) if not found: return None value = found.group(0).split('=')[1] try: integer_value = int(value) if integer_value < 0: raise ValueError() except ValueError: raise ValueError( f'"{key}=" must be followed by a positive integer in text') return integer_value def get_path_part_from_sequence_number(sequence_number, denominator): """ Get a path part of a sequence number styled path (e.g. 000/002/345) Args: sequence_number (int): sequence number (a positive integer) denominator (int): denominator used to extract the relevant part of a path Returns: str: part of a path """ return '{:03d}'.format(int(sequence_number / denominator))[-3:] def unique_tiles_from_files(start, end, directory): """ Ectracts a unique and ordered list of z/x/y expired tiles (e.g. 0/0/0) from files, in a structured replication dir Args: start (int): index of the first replication file end (int): index of the last replication file directory (str): path to a directory that contains replication structured dirs with expired tiles lists Returns: list: unique and ordered list of tiles """ expired_tiles = [] i = start # replication directory structure 004/215/801 corresponds to sequence number 4,215,801 while i <= end: path_parts = [directory] path_parts += [get_path_part_from_sequence_number( i, denominator) for denominator in SEQUENCE_PATH_DENOMINATORS] path_parts[-1] += '-expire.list' expired_tiles_file_path = path.sep.join(path_parts) try: with open(expired_tiles_file_path, 'r') as expired_tiles_file: expired_tiles += expired_tiles_file.read().splitlines() except FileNotFoundError: log.warn( f'file {expired_tiles_file_path} not found for sequence number {i}') except: raise finally: i += 1 expired_tiles = list(set(expired_tiles)) expired_tiles.sort() return expired_tiles def update_currently_expired_tiles_file(currently_expired_tiles_file_path, expired_tiles): """ Updates the currently expired list of tiles file Args: currently_expired_tiles_file_path (str): path to the currently expired list of tiles file expired_tiles (list): list if of tiles to expire """ # write the expired tiles list to a file with open(currently_expired_tiles_file_path, 'w') as currently_expired_file: if expired_tiles: currently_expired_file.write(linesep.join(expired_tiles)) def update_rendered_state_file(rendered_state_file_path, sequence_number): """ Updates the rendered state file with an updated state (after tile expiration) Args: rendered_state_file_path (str): path to the state file sequence_number (int): current sequence number to update rendered state file with """ with open(rendered_state_file_path, 'r+') as rendered_file: rendered_file.write(f'lastRendered={sequence_number}') def expire_tiles(state_file_path, currently_expired_tiles_file_path, rendered_state_file_path): """ Call mod_tile's render_expired with tiles that need to be re-rendered Args: state_file_path (str): path to a state file that holds the current replication state defined by the sequence number currently_expired_tiles_file_path (str): path to currentlyExpired.list file that holds a list of tiles to be re-rendered rendered_state_file_path (str): path to a file that holds the current rendered state relative to sequence number """ # Infinite loop that sleeps between tiles expirations while True: try: with open(state_file_path, 'r') as state_file: end = extract_positivie_integer_value(state_file.read(), 'sequenceNumber') if not end: raise LookupError(f'"sequenceNumber=" is not present in file') with open(rendered_state_file_path, 'r') as rendered_file: start = extract_positivie_integer_value(rendered_file.read(), 'lastRendered') log.info(f'rendering loop state', extra={'lastRendered': start, 'sequenceNumber': end}) except FileNotFoundError as e: if e.filename == rendered_state_file_path: log.info('initializing rendering state file') start = 1 with open(rendered_state_file_path, 'w') as rendered_file: rendered_file.write('lastRendered=1') else: log.error(f'{e.strerror}: {e.filename}') except: raise else: if start <= end: expired_tiles = unique_tiles_from_files(start, end, EXPIRED_DIRECTORY) update_currently_expired_tiles_file(currently_expired_tiles_file_path, expired_tiles) if len(expired_tiles) > 0: render_expired(currently_expired_tiles_file_path) log.info('marked expired tiles', extra={'lastRendered': start, 'sequenceNumber': end}) update_rendered_state_file(rendered_state_file_path, end) finally: time.sleep(RENDER_EXPIRED_TILES_INTERVAL) def render_expired(currently_expired_tiles_file_path): """ Render expired tiles Args: currently_expired_tiles_file_path (str): path to a file with a list of expired tiles to be rendered """ command = fr'cat {currently_expired_tiles_file_path} | /src/mod_tile/render_expired --map=osm --min-zoom={TILE_EXPIRE_MIN_ZOOM} --touch-from={TILE_EXPIRE_MIN_ZOOM}' _ = run_command(command, process_log.debug, process_log.error, handle_command_graceful_exit, handle_command_successful_complete) def run_apache_service(): """ Start apache tile serving service """ command = 'service apache2 start' _ = run_command_async(command, process_log.info, process_log.error, handle_command_graceful_exit, handle_command_successful_complete) log.info('apache2 service started') def run_renderd_service(): """ Start renderd service """ command = 'renderd -f -c /usr/local/etc/renderd.conf' _ = run_command_async(command, process_log.info, process_log.error, handle_command_graceful_exit, handle_command_successful_complete) log.info('renderd service started') def configure_carto_project(): log.info('configuring the carto project') with open(CARTO_FILE, 'r') as file : carto_data = file.read() for placeholder, value in db_config.items(): carto_data = carto_data.replace(placeholder, value) with open(CARTO_FILE, 'w') as file: file.write(carto_data) command = 'carto {} > /src/openstreetmap-carto/mapnik.xml'.format(CARTO_FILE) run_command(command, process_log.info, process_log.error, handle_command_graceful_exit, handle_command_successful_complete) def main(): log.info('mod-tile container started') state_file_path = path.join(EXPIRED_DIRECTORY, 'state.txt') currently_expired_tiles_file_path = path.join(EXPIRED_DIRECTORY, 'currentlyExpired.list') rendered_state_file_path = path.join(EXPIRED_DIRECTORY, 'renderedState.txt') configure_carto_project() run_apache_service() run_renderd_service() expire_tiles(state_file_path, currently_expired_tiles_file_path, rendered_state_file_path) def handle_command_graceful_exit(exit_code): process_log.error(f'process failed with exit code: {exit_code}') sys.exit(exit_code) def handle_command_successful_complete(): process_log.info(f'process completed successfully') if __name__ == '__main__': # create a dir for the default log file location mkdir('/var/log/osm-seed') # pass service/process name as a parameter to JSONLogger to be as an identifier for this specific logger instance log = JSONLogger('main-debug', additional_fields={'service': 'mod-tile', 'description': 'main log'}) process_log = JSONLogger('main-debug', additional_fields={'service': 'mod-tile', 'description': 'process logs'}) main()
yossiz16/microcOSM
images/imposm/start.py
<filename>images/imposm/start.py<gh_stars>0 #!/usr/bin/env python3 import os import re import time import json import subprocess import sys from datetime import datetime import psycopg2 import requests from jsonlogger.logger import JSONLogger from osmeterium.run_command import run_command state_file = 'state.txt' pbf_file = 'first-osm-import.pbf' sql_helpers = 'postgis_helpers.sql' sql_index = 'postgis_index.sql' pg_user = os.environ['POSTGRES_USER'] pg_password = os.environ['POSTGRES_PASSWORD'] pg_host = os.environ['POSTGRES_HOST'] pg_db = os.environ['POSTGRES_DB'] pg_port = os.environ['POSTGRES_PORT'] cache_dir_path = '/mnt/data/cache' diff_dir_path = '/mnt/data/diff' expired_tiles_dir_path = os.environ['CONFIG_EXPIRED_TILES_DIR'] replication_url = os.environ['IMPOSM_REPLICATION_URL'] last_state_file = 'last.state.txt' db_init_table_name = 'goad' imposm_config = { 'cachedir': cache_dir_path, 'diffdir': diff_dir_path, 'expiretiles_dir': expired_tiles_dir_path, 'expiretiles_zoom': int(os.environ['CONFIG_EXPIRED_TILES_ZOOM']), 'connection': 'postgis://{0}:{1}@{2}/{3}'.format(pg_user, pg_password, pg_host, pg_db), 'mapping': 'imposm3.json', 'replication_url': replication_url, 'replication_interval': os.environ['CONFIG_REPLICATION_INTERVAL'] } log = JSONLogger('main-debug', additional_fields={'service': 'imposm'}) def get_pg_connection(): return psycopg2.connect(host=pg_host, port=pg_port, dbname=pg_db, user=pg_user, password=pg_password) def execute_sql_script(script_name): conn = get_pg_connection() log.info('loading script {0} to the db'.format(script_name)) cur = conn.cursor() cur.execute(open(script_name, "r").read()) conn.close() def get_api_db_creation_timestamp(): url = '{0}000/000/000.state.txt'.format(replication_url) log.info('fetching file from {0}'.format(url)) result = requests.get(url) if not result.ok: log.error('failed retrieving state file. status code {0}'.format( result.status_code)) sys.exit(1) raw_timestamp = re.search("timestamp=(.*)", result.text).group(1) return datetime.strptime(raw_timestamp, r'%Y-%m-%dT%H\:%M\:%SZ') def is_db_initialized(): log.info('checking if database is initialized') conn = get_pg_connection() cur = conn.cursor() cur.execute( 'SELECT count(*) FROM information_schema.tables WHERE table_name = \'{0}\''.format(db_init_table_name)) data = cur.fetchone()[0] conn.close() return data > 0 def mark_db_as_initialized(): log.info('marking database as initialized') conn = get_pg_connection() cur = conn.cursor() cur.execute( 'CREATE TABLE {0} (v BOOLEAN)'.format(db_init_table_name)) conn.commit() conn.close() def get_command_stdout_iter(process): for stdout_line in iter(process.stdout.readline, ''): yield stdout_line def on_command_fail(command_name, exit_code): 'command {0} has terminated with error code {1}'.format( command_name, exit_code) sys.exit(1) def is_last_state_exists(): return os.path.isfile(os.path.join(diff_dir_path, last_state_file)) def initialize_db(): # set the pbf file time to match the db creation time execute_sql_script(sql_helpers) log.info('initializing the db with empty pbf') creation_time = time.mktime(get_api_db_creation_timestamp().timetuple()) os.utime(pbf_file, (creation_time, creation_time)) init_command = 'imposm import -config config.json -read {0} -write -diff -diffdir {1} -cachedir {2}'.format( pbf_file, diff_dir_path, cache_dir_path) run_command(init_command, log.info, log.error, lambda exit_code: on_command_fail('imposm import', exit_code), lambda: None) if not is_last_state_exists(): log.error(f'{last_state_file} is missing, could not update data') sys.exit(1) deploy_command = 'imposm import -config config.json -deployproduction' run_command(deploy_command, log.info, log.error, lambda exit_code: on_command_fail('imposm import deploy', exit_code), lambda: None) mark_db_as_initialized() def update_data(): run_command('imposm run -config config.json', log.info, log.error, lambda exit_code: on_command_fail('imposm run', exit_code), lambda: None) def main(): for dir_path in [cache_dir_path, diff_dir_path]: if not os.path.exists(dir_path): os.mkdir(dir_path) if not os.path.exists(expired_tiles_dir_path): raise Exception( 'Folder {0} was not found, please check again'.format(expired_tiles_dir_path)) with open('config.json', 'w') as fp: json.dump(imposm_config, fp) if not is_db_initialized(): initialize_db() update_data() if __name__ == '__main__': main()
yossiz16/microcOSM
images/osm2pgsql/start.py
#!/usr/bin/env python3 import os import subprocess import sys import psycopg2 import re import time import requests from jsonlogger.logger import JSONLogger # postgres variables PGHOST = os.environ['POSTGRES_HOST'] PGPORT = os.environ['POSTGRES_PORT'] PGUSER = os.environ['POSTGRES_USER'] PGDATABASE = os.environ['POSTGRES_DB'] PGPASSWORD = os.environ['POSTGRES_PASSWORD'] REPLICATION_URL = os.environ['REPLICATION_URL'] EXPIRED_DIRECTORY = os.environ['EXPIRED_DIR'] UPDATE_INTERVAL = int(os.environ['OSM2PGSQL_UPDATE_INTERVAL']) PG_CONNECTION_STRING = f'host={PGHOST} port={PGPORT} dbname={PGDATABASE} user={PGUSER} password={<PASSWORD>}' READY_TABLE_NAME = 'goad' DOWNLOAD_DIR = '/tmp/cache' OSC_FILE_EXTENSION = '.osc.gz' os.environ['PGHOST'] = PGHOST os.environ['PGPORT'] = PGPORT os.environ['PGUSER'] = PGUSER os.environ['PGDATABASE'] = PGDATABASE os.environ['PGPASSWORD'] = <PASSWORD> divide_for_days = 1000000 divide_for_month = 1000 divide_for_years = 1000 tiler_db_state_file_path = os.path.join(EXPIRED_DIRECTORY, 'state.txt') log = JSONLogger( 'main-debug', additional_fields={'service': 'osm2pgsql', 'description': 'main log'}) process_log = JSONLogger('main-debug', config={'handlers': { 'file': {'filename': '/var/log/osm-seed/process.log'}}}, additional_fields={'service': 'osm2pgsql', 'description': 'process logs'}) def get_command_stdout_iter(process): for stdout_line in iter(process.stdout.readline, ''): yield stdout_line def run_osm2pgsql_command(*argv): process = subprocess.Popen(' '.join(('osm2pgsql',) + argv), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True) for stdout_line in get_command_stdout_iter(process): if stdout_line: process_log.info(stdout_line.strip()) process.stdout.close() return_code = process.wait() if (return_code != 0): log.error( 'osm2pgsql command failed with error code {0}'.format(return_code)) sys.exit(1) def db_init(): log.info('starting first osm import') run_osm2pgsql_command( '--create', '--slim', '-G', '--hstore', '--tag-transform-script', '/src/openstreetmap-carto.lua', '-C', '2500', '--number-processes', '2', '-S', '/src/openstreetmap-carto.style', '/src/first-osm-import.osm' ) log.info('first import is done') def parse_integer_to_directory_number(integer): return '{0:0=3d}'.format(integer) def is_file_or_directory(path): return os.path.exists(path) def get_file_from_replication_server(path): url = '{0}/{1}'.format(REPLICATION_URL, path) log.info(f'fetching file from {url}') result = requests.get(url) return (result.ok, result.text) def download(path: str, dest_folder: str): url = '{0}/{1}'.format(REPLICATION_URL, path) if not os.path.exists(dest_folder): os.makedirs(dest_folder) # create folder if it does not exist # be careful with file names filename = url.split('/')[-1].replace(' ', '_') file_path = os.path.join(dest_folder, filename) r = requests.get(url, stream=True) if r.ok: log.info(f'saving file to {os.path.abspath(file_path)}') with open(file_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024 * 8): if chunk: f.write(chunk) else: log.error( f'file download failed from {url} with error code {r.status_code}') return (r.status_code, file_path) def extract_integer_value(content, find, throw_not_found=True, none_found=-1): found = re.findall(f'{find}=.*', content) if len(found) == 0: if throw_not_found: raise LookupError(f'\'{find}=\' is not present in the state.txt') else: return none_found found = found[0].split('=')[1] try: found = int(found) except ValueError: raise ValueError( f'\'{find}=\' must be follow by a positive integer at state.txt') return found def is_db_initialized(): flag = True while (flag): conn = psycopg2.connect( PG_CONNECTION_STRING) cur = conn.cursor() cur.execute( f'SELECT count (*) from information_schema.tables where table_name=\'{READY_TABLE_NAME}\'') data = cur.fetchone()[0] flag = False return data > 0 def flag_db_as_initialized(): # flag = True # while (flag): log.info('marking database as initialized') conn = psycopg2.connect( PG_CONNECTION_STRING) cur = conn.cursor() cur.execute( f'CREATE TABLE {READY_TABLE_NAME} (v BOOLEAN)') conn.close() # flag = False def update_db_with_replication(api_db_sequence_number, tiler_db_sequence_number): for i in range(tiler_db_sequence_number + 1, api_db_sequence_number + 1): dir1 = parse_integer_to_directory_number(int(i / divide_for_days)) dir2 = parse_integer_to_directory_number(int(i / divide_for_month)) state = parse_integer_to_directory_number(int(i % divide_for_years)) # creating the folder to store the expired tiles list if it does not exist if not is_file_or_directory('/'.join([EXPIRED_DIRECTORY, dir1])): os.mkdir('{0}/{1}'.format(EXPIRED_DIRECTORY, dir1)) EXPIRED_PATH = '{0}/{1}/{2}'.format(EXPIRED_DIRECTORY, dir1, dir2) if not is_file_or_directory(EXPIRED_PATH): os.mkdir(EXPIRED_PATH) # downloading the osc file (status_code, osc) = download( '{0}/{1}/{2}'.format(dir1, dir2, state + OSC_FILE_EXTENSION), DOWNLOAD_DIR) # terminate on failed download or not saving properly if status_code >= 400 or not is_file_or_directory(osc): sys.exit(1) log.info( f'updating replications where api_db sequence={api_db_sequence_number} and tiler_db starting sequence={tiler_db_sequence_number} and current={i}') run_osm2pgsql_command( '--append', '--slim', '-G', '--hstore', '--tag-transform-script', '/src/openstreetmap-carto.lua', '-C', '2500', '--number-processes', '2', '-S', '/src/openstreetmap-carto.style', osc, '-e17', '-o', '{0}/{1}-expire.list'.format(EXPIRED_PATH, state) ) update_state_file(i) # cleanup of the state file that was applied os.remove(osc) def update_state_file(sequence_number): with open(tiler_db_state_file_path, 'r+') as expired_file: expired_content = expired_file.read() sequence_numberFound = re.search('sequenceNumber=.*', expired_content) if sequence_numberFound: expired_content = re.sub(r'(?<=sequenceNumber=)\d+', str(sequence_number), expired_content, 1) # update sequenceNumber value log.info( f'updating state file at {tiler_db_state_file_path} with sequenceNumber={sequence_number}') expired_file.truncate(0) expired_file.seek(0) expired_file.write(str(expired_content)) def get_api_db_sequence(): (is_ok, api_db_replication_state) = get_file_from_replication_server('state.txt') if (not is_ok): log.error( f'state file not found in remote server {REPLICATION_URL}, sleeping for {UPDATE_INTERVAL}') return -1 try: return extract_integer_value( api_db_replication_state, 'sequenceNumber') except: log.error( 'api_db_sequence_number must be a positive integer at state.txt') raise def get_tiler_db_sequence(): # create the state file as start from 0 as it was not found if (not is_file_or_directory(tiler_db_state_file_path)): log.info('creating osm2pgsql state file as one does not exist') with open(tiler_db_state_file_path, 'w+') as fp: fp.write( f'sequenceNumber=0\n') return 0 # retrive the sequence number from the file else: with open(tiler_db_state_file_path, 'r') as fp: return extract_integer_value( fp.read(), 'sequenceNumber') def update_data_loop(): log.info('starting replications update loop') while True: log.info(f'sleeping for {UPDATE_INTERVAL}') time.sleep(UPDATE_INTERVAL) api_db_sequence_number = get_api_db_sequence() # if true than it means the state wasnt found if (api_db_sequence_number == -1): continue tiler_db_sequence_number = get_tiler_db_sequence() log.info( f'api_db_sequence = {api_db_sequence_number}, tiler_db_sequence={tiler_db_sequence_number}') # check if an update is needed if (api_db_sequence_number != tiler_db_sequence_number): update_db_with_replication( api_db_sequence_number, tiler_db_sequence_number) def main(): log.info('osm2pgsql container started') # if pg_is_ready(): if not is_db_initialized(): db_init() flag_db_as_initialized() update_data_loop() if __name__ == '__main__': main()
yossiz16/microcOSM
images/earth-tiles-loader/start.py
<gh_stars>0 #!/usr/bin/env python3 import os import signal import sys from datetime import datetime from croniter import croniter import pause from jsonlogger.logger import JSONLogger from osmeterium.run_command import run_command pg_user = os.environ['POSTGRES_USER'] pg_password = os.environ['POSTGRES_PASSWORD'] pg_host = os.environ['POSTGRES_HOST'] pg_db = os.environ['POSTGRES_DB'] pg_port = os.environ.get('POSTGRES_PORT', default=5432) skip_load_on_startup = os.environ.get('SKIP_LOAD_ON_STARTUP', 'False') cron_expression = os.environ['LOAD_EXTERNAL_SCHEDULE_CRON'] config_file = os.environ.get('CONFIG_FILE_PATH', default='external-data.yaml') log = JSONLogger( 'main-debug', additional_fields={'service': 'earth-tiles-loader'}) def on_command_error(exit_code): log.error('get-external-data script failed with exit code {}'.format(exit_code)) os.kill(os.getpid(), signal.SIGINT) def load_data(): command = 'PGPASSWORD={0} get-external-data.py -H {1} -d {2} -p {3} -U {4} -c {5}'.format( pg_password, pg_host, pg_db, pg_port, pg_user, config_file) log.info('starting to load the data') run_command(command, log.info, log.error, on_command_error, lambda: None) log.info('loading completed') def main(): # check if script should load data on startup if not skip_load_on_startup.lower() == 'true': load_data() iter = croniter(expr_format=cron_expression, start_time=datetime.now()) while True: execute_time = iter.get_next(datetime) log.info('paused until {}'.format( execute_time.strftime("%d/%m/%Y %H:%M:%S"))) pause.until(execute_time) load_data() if __name__ == '__main__': main()
yossiz16/microcOSM
images/earth-tiles-loader/utils/ne-zip-files-extractor.py
# this script creates the correct yaml for the external data file sources part # it needs a flat directory structure in the zip like in natural earth import zipfile import requests import yaml import io import zipfile urls = ('https://naciscdn.org/naturalearth/110m/cultural/ne_110m_populated_places.zip', 'https://naciscdn.org/naturalearth/50m/cultural/ne_50m_populated_places.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_populated_places.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_0_label_points.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_1_label_points.zip', 'https://naciscdn.org/naturalearth/110m/cultural/ne_110m_admin_0_boundary_lines_land.zip', 'https://naciscdn.org/naturalearth/50m/cultural/ne_50m_admin_0_boundary_lines_land.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_0_boundary_lines_land.zip', 'https://naciscdn.org/naturalearth/50m/cultural/ne_50m_admin_0_boundary_lines_disputed_areas.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_0_boundary_lines_disputed_areas.zip', 'https://naciscdn.org/naturalearth/110m/cultural/ne_110m_admin_0_countries.zip', 'https://naciscdn.org/naturalearth/50m/cultural/ne_50m_admin_0_countries.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_0_countries.zip', 'https://naciscdn.org/naturalearth/110m/cultural/ne_110m_admin_1_states_provinces_lines.zip', 'https://naciscdn.org/naturalearth/50m/cultural/ne_50m_admin_1_states_provinces_lines.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_admin_1_states_provinces_lines.zip', 'https://naciscdn.org/naturalearth/110m/physical/ne_110m_land.zip', 'https://naciscdn.org/naturalearth/50m/physical/ne_50m_land.zip', 'https://naciscdn.org/naturalearth/10m/physical/ne_10m_land.zip', 'https://naciscdn.org/naturalearth/50m/cultural/ne_50m_admin_1_states_provinces_lakes.zip', 'https://naciscdn.org/naturalearth/10m/cultural/ne_10m_roads.zip') output = {} def create_data_entry(url): download = requests.get(url) filename = url.split('/')[-1].split('.')[0] zip = zipfile.ZipFile(io.BytesIO(download.content)) file_list = map(lambda x: x.filename, zip.filelist) filtered_file_list = filter( lambda x: 'README' not in x and 'VERSION' not in x, file_list) output[filename] = {'url': url, 'type': 'shp', 'archive': { 'format': 'zip', 'files': list(filtered_file_list)}, 'file': '{}.shp'.format(filename)} for url in urls: create_data_entry(url) with open('data.yml', 'w') as outfile: yaml.dump(output, outfile, default_flow_style=False)
jonahmakowski/PyWrskp
src/other/animal_guesser.py
import os import json try: pyWrkspLoc = os.environ["PYWRKSP"] except KeyError: pyWrkspLoc = os.environ["HOME"] + input('Since you do not have the PYWRSKP env var ' '\nPlease enter the pwd for the pyWrskp repo not including the ' '"home" section') class AnimalChoser: def __init__(self, pywrskp): self.name_1 = pywrskp + '/docs/txt-files/animal_chooser_options.txt' self.name_2 = pywrskp + '/docs/txt-files/animal_chooser_atturbites.txt' self.options = [] self.atturbites = [] self.load() self.correct_atturbites = [] do = input('would you like to add or play?') if do == 'play': print('The current options for this game are:') for item in self.options: print(item['name']) self.guess() else: self.add() def guess(self): for item in self.atturbites: yes_or_no = input('is this animal/does it have {} (y/n)?'.format(item['name'])) item['y/n'] = yes_or_no for item in self.atturbites: if item['y/n'] == 'y': self.correct_atturbites.append(item['name']) choosen = False for item in self.options: item['info'] = sorted(item['info']) self.correct_atturbites = sorted(self.correct_atturbites) for item in self.options: if item['info'] == self.correct_atturbites: print('your animal is {}'.format(item['name'])) choosen = True break if not choosen: print("This program can figure out what you choose, make sure it is on this list:") for item in self.options: print(item['name']) '''print('debug info:') print('self.correct_atturbites:') print(self.correct_atturbites) print('self.options:') print(self.options)''' def load(self): try: with open(self.name_1) as json_file: self.options = json.load(json_file) except FileNotFoundError: print('This file does not exist (num1)') exit(5) try: with open(self.name_2) as json_file: self.atturbites = json.load(json_file) except FileNotFoundError: print('This file does not exist (num2)') exit(5) def add(self): new_name = input('What is the name of this animal?') new = {"name": new_name, "info": []} new_attrbs = [] print('What are the atturbuites?') while True: attrb = input() if attrb == '': break new_attrbs.append(attrb) new["info"].append(attrb) for item in new_attrbs: for atra in self.atturbites: if item == atra: del item for item in new_attrbs: self.atturbites.append({'name': item, "y/n": ""}) self.options.append(new) with open(self.name_1, 'w') as outfile: json.dump(self.options, outfile) with open(self.name_2, 'w') as outfile: json.dump(self.atturbites, outfile) game = AnimalChoser(pyWrkspLoc)
jonahmakowski/PyWrskp
src/other/txt_editor.py
<reponame>jonahmakowski/PyWrskp<gh_stars>0 class TxtReader: def __init__(self): self.file_loc = input('Enter the path for this .txt file\nOr enter create for a new file') if self.file_loc == 'create': self.file_loc = input('What is the path for the new file you want to make') self.write('', self.file_loc) print('An empty file should be created at that loc.') self.mainloop() def mainloop(self): while True: do = input('What do you want to do?') if do == 'wipe & write' or do == 'w&w': self.wipe_and_write() break elif do == 'add' or do == 'a': self.add() break elif do == 'read' or do == 'r': self.show() break else: print('{} is not an option'.format(do)) print('Here are the options:') print('\t"wipe & write"') print('\t\t"w&w"') print('\t"add"') print('\t\t"a"') print('\t"read"') print('\t\t"r"') def show(self): write = self.read(self.file_loc) print('The current file is:') print(write) def add(self): write = self.read(self.file_loc) print('The current file is:') print(write) write_add = input('What do you wish to add? (use "\ n"\n') write_all = write + write_add self.write(write_all, self.file_loc) def wipe_and_write(self): write = input('What do you wish to write?\n') self.write(write, self.file_loc) def read(self, loc): with open(loc, 'r') as inFile: txt = inFile.read() return txt def write(self, item, loc): with open(loc, 'w') as outFile: outFile.write(item) txt_reader = TxtReader()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/class_2wrk.py
import pygame DIS_WIDTH = 1280 DIS_HEIGHT = 820 pygame.init() screen = pygame.display.set_mode([DIS_WIDTH, DIS_HEIGHT]) pygame.display.set_caption("Paint") buttonMinus = pygame.image.load('button_minus.png') buttonPlus = pygame.image.load('button_plus.png') keep_going = True mouse_down = False BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) GREY = (131, 131, 131) currentColour = RED radius = 5 colors = [RED, GREEN, BLUE] buttons = [buttonMinus, buttonPlus] recWidth = int(DIS_WIDTH * 0.1) recHeight = int(DIS_HEIGHT * 0.09) button_size = int(recHeight / 2) max_radius = int(recHeight / 2) location_x = ((DIS_WIDTH - (max_radius * 4))) def menu(): global location_x global button_size global colors topRectangle = pygame.Rect((0, 0), (DIS_WIDTH, recHeight)) pygame.draw.rect(screen, GREY, topRectangle) pygame.draw.circle(screen, currentColour, (DIS_WIDTH - radius, radius), radius) x = 0 for col in colors: rectangle = pygame.Rect((x, 0), (recWidth, recHeight)) pygame.draw.rect(screen, col, rectangle) x += recWidth y = 0 for button in buttons: plus_minus = pygame.transform.scale(button, (button_size, button_size)) plus_minus_rec = plus_minus.get_rect(topleft = (location_x, y)) screen.blit(plus_minus, plus_minus_rec) y += button_size pygame.display.update() def check_color(): global colors global recWidth global currentColour x = 0 spot = pygame.mouse.get_pos() for col in colors: rectangle = pygame.Rect((x, 0), (recWidth, recHeight)) x += recWidth if rectangle.collidepoint(spot): return 'color' for button in buttons: plus_minus = pygame.transform.scale(button, (button_size, button_size)) plus_minus_rec = plus_minus.get_rect(topleft = (location_x, y)) y += button_size if plus_minus_rec.collidepoint(spot): return 'radius' return False def check(): global colors global recWidth global currentColour global recHeight global radius x = 0 spot = pygame.mouse.get_pos() for col in colors: rectangle = pygame.Rect((x, 0), (recWidth, recHeight)) x += recWidth if rectangle.collidepoint(spot): currentColour = col increase = 5 while keep_going: for event in pygame.event.get(): if event.type == pygame.QUIT: keep_going = False elif event.type == pygame.MOUSEBUTTONDOWN: spot = pygame.mouse.get_pos() if minusRect.collidepoint(spot): if radius > increase: radius -= increase if plusRect.collidepoint(spot): if radius < max_radius: radius += increase if radius > max_radius: radius -= increase else: mouse_down = True elif event.type == pygame.MOUSEBUTTONUP: mouse_down = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: screen.fill(BLACK) if event.key == pygame.K_r: radius = 5 if event.key == pygame.K_q: if radius < max_radius: radius += increase if radius > max_radius: radius -= increase if event.key == pygame.K_a: if radius > increase: radius -= increase if event.key == pygame.K_z: screen.fill(currentColour) if mouse_down: # if the event is pressing the mouse if not check_color(): # if it's not within a button, place a circle at the spot the mouse was pressed pygame.draw.circle(screen, currentColour, spot, radius) else: menu() pygame.quit()
jonahmakowski/PyWrskp
src/other/shopping_list.py
<gh_stars>0 import json import os try: pyWrkspLoc = os.environ["PYWRKSP"] except KeyError: pyWrkspLoc = os.environ["HOME"] + input('Since you do not have the PYWRSKP env var ' '\nPlease enter the pwd for the pyWrskp repo not including the ' '"home" section') class ShoppingList: def __init__(self, py_wrskp): self.name = py_wrskp + '/docs/txt-files/shopping_list.txt' self.list = self.load() print('the current list is:') self.show() t = input('what would you like to do?') if t == 'add': self.add() print('The list is now:') self.show() elif t == 'rm': self.rm() print('The list is now:') self.show() self.save() def load(self): try: with open(self.name) as json_file: j = json.load(json_file) except FileNotFoundError: print('This file does not exist') exit(5) return j def add(self): item = input('What is the name of the object you want to add to your list?') self.list.append(item) def rm(self): item = input('What is the name of teh item you would like to remove, make sure this is right') if item == 'all': self.list =[] else: for i in range(len(self.list)): if self.list[i] == item: del self.list[i] break def show(self): for item in self.list: print(item) def save(self): with open(self.name, 'w') as outfile: json.dump(self.list, outfile) if __name__ == "__main__": shopping_list = ShoppingList(pyWrkspLoc)
jonahmakowski/PyWrskp
src/super_safe_note_sender/sender.py
import sys import json import random import os sys.path.append('../coder-decoder') from coder import CoderDecoder as Coder ''' Need to pass a message to your friends? Don't want anyone else to see it? Use this program! This program when you run the "create" option, will create a message.txt file, if your friend has the program, they can decode the message! ''' class Sender: def __init__(self): self.remote_coder = Coder(print_info=False) self.remote_coder_2 = Coder(print_info=False) self.remote_coder_3 = Coder(print_info=False) self.remote_coder_4 = Coder(print_info=False) self.remote_coder_5 = Coder(print_info=False) def create_note(self): print('What would you like the password to be?') password = input('The person who decodes this needs to know it') message = input('What is the message that you would like to send?') key = random.randint(0, len(self.remote_coder.abcs) - 1) key_for_the_key = random.randint(0, len(self.remote_coder.abcs) - 1) destroy = input('Would you like the file to be destoryed after reading?\n' 'Will be destroyed either way if password is inputed wrong\n' 'y/n\n') self.remote_coder.add_vars(message, key) message = self.remote_coder.code() self.remote_coder_2.add_vars(password, key) password = self.remote_coder_2.code() self.remote_coder_5.add_vars(destroy, key) destroy = self.remote_coder_5.code() self.remote_coder_3.add_vars(str(key), key_for_the_key) key = self.remote_coder_3.code() self.remote_coder_4.add_vars(str(key_for_the_key), 15) key_for_the_key = self.remote_coder_4.code() items = [] for i in range(5): item = '' for c in range(random.randint(6, 20)): new_item = '' while (new_item != '}' and new_item != '{') and (new_item != '[' and new_item != ']'): new_item = self.remote_coder.abcs[random.randint(0, len(self.remote_coder.abcs) - 1)] item += new_item items.append(item) save_dic = {'dshaidsh': items[0], 'asuydhausdhuashd': password, 'shadiufad': items[1], 'sdifhuegtsydftyas': message, 'g': items[2], 'asdyatsdftras': key, 'asd7r8ushdfuhja': items[3], 'd': destroy, 'fjgishuagsdiufji': items[4], 'gjfosjodjif': key_for_the_key} with open('message.txt', 'w') as outfile: json.dump(save_dic, outfile) def read_note(self): try: with open('message.txt') as json_file: dic = json.load(json_file) except FileNotFoundError: print('There is no file like this (make sure it is called message.txt)') exit(404) self.remote_coder_4.add_vars(dic['gjfosjodjif'], 15) key_for_the_key = int(self.remote_coder_4.decode()) self.remote_coder_3.add_vars(dic['asdyatsdftras'], key_for_the_key) key = int(self.remote_coder_3.decode()) password = input('What is the password?') self.remote_coder_2.add_vars(dic['asuydhausdhuashd'], key) password_check = self.remote_coder_2.decode() if password != password_check: print('password incorrect deleting file') os.remove("message.txt") exit(500) self.remote_coder.add_vars(dic['sdifhuegtsydftyas'], key) message = self.remote_coder.decode() self.remote_coder_5.add_vars(dic['d'], key) destroy = self.remote_coder_5.decode() print('The message in this file is:') print(message) if destroy == 'y': print('destroying file') os.remove('message.txt') else: print('The person who sent you this .txt file has decieded that it is not nessary to delete the file,') print('Though you may do so if you want') if __name__ == '__main__': sender = Sender() do = input('What do you wish to do?') if do == 'create': sender.create_note() elif do == 'read': sender.read_note()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/mm2.py
import pygame print('Based on Class_one1.py by Jonas, Apr 4, 2021; modified by <NAME>.') # define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) PURPLE = (251, 0, 255) YELLOW = (255, 247, 0) TEAL = (0, 255, 255) ORANGE = (255, 196, 0) LIME = (132, 255, 0) box_size = 50 # size (in pixels) of menu boxes h_menu = box_size # height of the menu bar (at top of the display) colors = [BLACK, WHITE, RED, BLUE, GREEN, PURPLE, YELLOW, TEAL, ORANGE, LIME] n_colors = len(colors) pen_sizes = [5, 10, 15, 20, 25] n_sizes = len(pen_sizes) x_pixels = 1375 y_pixels = 750 currentColour = BLUE # initial background color radius = 10 # initial radius of the circle def mk_menu(): # display menu boxes (colors and pen-sizes) global currentColour screen.fill(currentColour) x_cur = 0 for col in colors: # menu color boxes rectangle = pygame.Rect((x_cur, 0), (box_size, box_size)) pygame.draw.rect(screen, col, rectangle) x_cur += box_size for pen in pen_sizes: # menu pen-size boxes rectangle = pygame.Rect((x_cur, 0), (box_size, box_size)) pygame.draw.rect(screen, BLACK, rectangle) pygame.draw.circle(screen, WHITE, (x_cur + box_size/2, box_size/2), pen) x_cur += box_size rectangle = pygame.Rect((x_cur, 0), (x_pixels, box_size)) pygame.draw.rect(screen, WHITE, rectangle) pygame.display.update() def mk_change(x_pos): # change either color or pen_size global currentColour global radius x_org = x_pos colors_menu = n_colors * box_size if x_pos <= colors_menu: col_pos = int(x_pos / box_size) currentColour = colors[col_pos] # print('New color, pos = ' + str(col_pos)) return pens_menu = n_sizes * box_size x_pos -= colors_menu if x_pos <= pens_menu: pen_pos = int(x_pos / box_size) radius = pen_sizes[pen_pos] # print('New radius, pos = ' + str(pen_pos)) else: print('Ignore menu position: ' + str(x_org)) pygame.init() screen = pygame.display.set_mode([x_pixels, y_pixels]) pygame.display.set_caption( "Click the color-square to change the current color; the space-bar changes the background color") pygame.display.update() mk_menu() keep_going = True mouse_down = False while keep_going: for event in pygame.event.get(): if event.type == pygame.QUIT: # exit keep_going = False elif event.type == pygame.MOUSEBUTTONUP: # do nothing mouse_down = False elif event.type == pygame.MOUSEBUTTONDOWN: spot = pygame.mouse.get_pos() # get the current position of the mouse x = spot[0] y = spot[1] if y <= box_size: # in menu area mk_change(x) # change either color or pen-size else: mouse_down = True elif event.type == pygame.KEYDOWN: # keyboard events if event.key == pygame.K_SPACE: # only the space-bar handled screen.fill(currentColour) mk_menu() pygame.display.update() if mouse_down: spot = pygame.mouse.get_pos() # get the current position of the mouse # print('Mouse position: ' + str(spot[0]) + ', ' + str(spot[1])) if spot[1] > box_size: margin = spot[1] - box_size paint_radius = radius if margin < radius: paint_radius = margin pygame.draw.circle(screen, currentColour, spot, paint_radius) pygame.display.update() else: print('Painting in the menu-bar is suppressed.') pygame.quit()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/bday1.py
# compute number of months and days from today to my next bday import datetime from dateutil import relativedelta bday = datetime.date(2010, 5, 29) today = datetime.date.today() age = today - bday cur_yr = today.year next_bday = bday.replace(year=cur_yr) if next_bday < today: # already passed this year, consider bday next year next_bday = next_bday.replace(year=cur_yr + 1) diff = next_bday - today diff2 = relativedelta.relativedelta(next_bday, today) n_months = diff2.months n_days = diff2.days if n_months == 0 and n_days == 0: print('Your birthsday is TODAY.') else: print('Next birthday is in ' + (str(n_months)) + ' months and ' + (str(n_days)) + ' days.') pass
jonahmakowski/PyWrskp
src/other/team_maker.py
""" I know I have an older team maker, but I thought I would use what I have learned so far to make a brand new one! Here it is: """ import os from random import randint import json try: pyWrkspLoc = os.environ["PYWRKSP"] except KeyError: pyWrkspLoc = os.environ["HOME"] + input('Since you do not have the PYWRSKP env var ' '\nPlease enter the pwd for the pyWrskp repo not including the ' '"home" section') class TeamMaker: def __init__(self, loc, t=None, d=None, pr=True): self.name = loc + '/docs/txt-files/team_maker_save.txt' change_t = False if t is None: change_t = True while True: if change_t: t = self.ask_t() if t == '2 teams': self.two_teams() if pr: self.show() break elif t == '4 teams': self.four_teams() if pr: self.show() break elif t == 'partners': self.partners() if pr: self.show() break elif t == '2 teams + captions': self.two_teams() self.chose_caption() if pr: self.show() break elif t == '4 teams + captions': self.four_teams() self.chose_caption() if pr: self.show() break elif t == 'partners + captions': self.partners() self.chose_caption() if pr: self.show() break else: if change_t is False: print("As this option can't be changed, ending program") exit() print('This value is not allowed, please try again') print('The options are:') print('"2 teams"') print('"4 teams"') print('"partners"') print('or if you add "+ captions" to any of them you will get one caption per team') print('asking again\n\n') if d is None: d = self.ask_l() self.d = d self.teams = [] def ask_t(self): t = input('What type would you like?\n') return t def ask_l(self): d = [] load = input('would you like to load the list? (y/n)') if load == 'n': print("Enter a list of the people's names if nothing is entered, the list will stop, you must include " "more than one name") while True: l_add = input('') if l_add == '': if len(d) != 1: break elif l_add != '': d.append(l_add) save = input('would you like to save this list? (y/n)') if save == 'y': self.save_list(d) elif load == 'y': d = self.load() else: print('{} is an word/char that this code does not allow'.format(load)) exit(404) return d def two_teams(self): team_1 = [] team_2 = [] while len(self.d) > 1: person1 = randint(0, len(self.d) - 1) team_1.append(self.d[person1]) del self.d[person1] person2 = randint(0, len(self.d) - 1) team_2.append(self.d[person2]) del self.d[person2] if len(self.d) == 1: print('you have and uneven amount, adding {} to team 1'.format(self.d[0])) team_1.append(self.d[0]) self.teams.append(team_1) self.teams.append(team_2) def four_teams(self): team_1 = [] team_2 = [] team_3 = [] team_4 = [] while len(self.d) > 3: person1 = randint(0, len(self.d) - 1) team_1.append(self.d[person1]) del self.d[person1] person2 = randint(0, len(self.d) - 1) team_2.append(self.d[person2]) del self.d[person2] person3 = randint(0, len(self.d) - 1) team_3.append(self.d[person3]) del self.d[person3] person4 = randint(0, len(self.d) - 1) team_4.append(self.d[person4]) del self.d[person4] if len(self.d) == 1: team_1.append(self.d[0]) elif len(self.d) == 2: team_1.append(self.d[0]) team_2.append(self.d[1]) elif len(self.d) == 3: team_1.append(self.d[0]) team_2.append(self.d[1]) team_3.append(self.d[2]) self.teams.append(team_1) self.teams.append(team_2) self.teams.append(team_3) self.teams.append(team_4) def partners(self): while len(self.d) >= 2: person1 = randint(0, len(self.d) - 1) person_1_name = self.d[person1] del self.d[person1] person2 = randint(0, len(self.d) - 1) person_2_name = self.d[person2] del self.d[person2] self.teams.append([person_1_name, person_2_name]) if len(self.d) == 1: print('You have an uneven amount of people') print('I am making a group of three') self.teams[0].append(self.d[0]) def chose_caption(self): for item in self.teams: caption_num = randint(0, len(item) - 1) caption_name = item[caption_num] del item[caption_num] item.append(caption_name + ' is Caption of the team') def load(self): try: with open(self.name) as json_file: j = json.load(json_file) except FileNotFoundError: print('This file, where the save is does not exist, to use this program make a file at {}.' .format(self.name)) exit(5) return j def save_list(self, d): with open(self.name, 'w') as outfile: json.dump(d, outfile) def show(self): team_num = 1 for item_large in self.teams: print('Team {}'.format(team_num)) for item in item_large: print(item) print('\n') team_num += 1 if __name__ == "__main__": teams = TeamMaker(pyWrkspLoc)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/testing.py
import requests street = "1600+Pennsylvania+Avenue+NW" city = "Washington" state = "DC" zipcode = "20500" geocode = requests.get("https://geocoding.geo.census.gov/geocoder/locations/address?street={}&city={}&state={}&zip={}&benchmark=4&format=json".format(street, city, state, zipcode)) #print(geocode.text) coordinates = geocode.json()['result']['addressMatches'][0]['coordinates'] gridpoints = requests.get('https://api.weather.gov/points/{},{}'.format(coordinates['y'],coordinates['x'])) #print(gridpoints.text) forecast = requests.get(gridpoints.json()['properties']['forecastHourly'])
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/what_is_your_name.py
import sys import os try: pyWrkspLoc = os.environ["PYWRKSP"] except KeyError: pyWrkspLoc = os.environ["HOME"] + input('Since you do not have the PYWRSKP env var ' '\nPlease enter the pwd for the pyWrskp repo not including the ' '"home" section') class Name: def __init__(self, name, pyWrskp): self.name = name self.pyWrskp = pyWrskp self.fun_stuff() def hello_world(self): print('Hello World') print('Your name is {}!'.format(self.name)) def lola_is_the_best(self): for i in range(999): print('Lola is the best') def name(self): sys.path.append(self.pyWrskp + '/src/game') from game import Game g = Game def fun_stuff(self): option = input('What do you want to do {}?'.format(self.name)) if option == 'hello world': self.hello_world() elif option == 'lola is the best': self.lola_is_the_best() elif option == 'game': self.name() n = Name('Jonah')
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/smartness_test.py
a = [] print('WELCOME TO MY SMARTNESS TEST') def q(qu, ae): qe = input(qu + '\n') if qe == ae: return True if qe != ae: return False c = '' # question d = '' # question (3 * 3) def q_idea(): from random import randint as r num = r(2, 3) nums = [] if num == 2: num_1 = r(10, 100) num_2 = r(50, 150) nums.append(num_1) nums.append(num_2) if num == 3: num_1 = r(10, 100) num_2 = r(50, 150) num_3 = r(100, 200) nums.append(num_1) nums.append(num_2) nums.append(num_3) def question_def(opr): if len(nums) == 2: questionr = ('What is ' + str(nums[0]) + opr + str(nums[1]) + '?') if len(nums) == 3: questionr = ('What is ' + str(nums[0]) + opr + str(nums[1]) + opr + str(nums[2]) + '?') return questionr op = r(1, 4) if op == 1: question = question_def(' + ') elif op == 2: question = question_def(' - ') elif op == 3: question = question_def(' * ') elif op == 4: question = question_def(' / ') global c global d c = question if len(nums) == 2: if op == 1: d = nums[0] + nums[1] if op == 2: d = nums[0] - nums[1] if op == 3: d = nums[0] * nums[1] if op == 4: d = nums[0] / nums[1] elif len(nums) == 3: if op == 1: d = nums[0] + nums[1] + nums[2] if op == 2: d = nums[0] - nums[1] - nums[2] if op == 3: d = nums[0] * nums[1] * nums[2] if op == 4: d = nums[0] / nums[1] / nums[2] for i in range(9): q_idea() a.append(q(c, d)) i = 0 for item in a: if item: i += 1 rank = 'terrible.' if i >= 1: rank = 'bad.' if i >= 3: rank = 'ok.' if i >= 5: rank = 'pretty good.' if i >= 7: rank = 'good.' if i >= 8: rank = 'great!' if i >= 9: rank = 'Outstanding!!' print('you ranked ' + rank)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/class_7.py
import requests import matplotlib.pyplot as plt import dateutil.parser class Weather: def __init__(self, street, city, state, zipcode, loc_name, hour): self.street = street self.city = city self.state = state self.zipcode = zipcode self.loc_name = loc_name # print(self.zipcode) if hour == 'd': self.getForecastdaily() self.getTempsdaily() elif hour == 'h': self.getForecasthourly() self.getTempsHourly() def getForecasthourly(self): geocode = requests.get("https://geocoding.geo.census.gov/geocoder/locations/address?street={}&city={}&state={}&zip={}&benchmark=4&format=json".format(self.street, self.city, self.state, self.zipcode)) #print(geocode.text) coordinates = geocode.json()['result']['addressMatches'][0]['coordinates'] gridpoints = requests.get('https://api.weather.gov/points/{},{}'.format(coordinates['y'],coordinates['x'])) #print(gridpoints.text) self.forecast = requests.get(gridpoints.json()['properties']['forecastHourly']) # print(self.forecast.text) # uncomment to print raw forecast info def getTempsHourly(self): #print(self.forecast.text) time = str(self.forecast.json()['properties']['periods'][0]['startTime']) time = time[-5:] hour = int(time[:-3]) tick = 0 self.times, self.temp = [], [] for hr in self.forecast.json()['properties']['periods']: time = str(hour) + ':00' self.times.append(time) self.temp.append(hr['temperature']) hour += 1 if hour == 25: hour = 1 tick += 1 if tick == 24: break def getForecastdaily(self): geocode = requests.get("https://geocoding.geo.census.gov/geocoder/locations/address?street={}&city={}&state={}&zip={}&benchmark=4&format=json".format(self.street, self.city, self.state, self.zipcode)) #print(geocode.text) coordinates = geocode.json()['result']['addressMatches'][0]['coordinates'] gridpoints = requests.get('https://api.weather.gov/points/{},{}'.format(coordinates['y'],coordinates['x'])) self.forecast = requests.get(gridpoints.json()['properties']['forecast']) # print(self.forecast.text) # uncomment to print raw forecast info def getTempsdaily(self): self.timesDay, self.tempsDay, self.timesNight, self.tempsNight = [], [], [], [] for days in self.forecast.json()['properties']['periods']: if days['isDaytime']: self.timesDay.append(dateutil.parser.parse(days['startTime'])) self.tempsDay.append(days['temperature']) else: self.timesNight.append(dateutil.parser.parse(days['startTime'])) self.tempsNight.append(days['temperature']) def txt_display_forecast(self): for days in self.forecast.json()['properties']['periods']: print('{}:\n{}{}, {}\n\n'.format(days['name'], days['temperature'], days['temperatureUnit'], days['shortForecast'])) def plt_display_forecast(item, hour): if hour == 'd': for lis in item: plt.plot(lis.timesDay, lis.tempsDay, 'o-', label=lis.loc_name + ' day') plt.plot(lis.timesNight, lis.tempsNight,'o-', label=lis.loc_name + ' night') plt.title('temp for next seven days') else: for lis in item: plt.plot(lis.times, lis.temp, 'o-', label=lis.loc_name) plt.title('temp for 24 hours') plt.gcf().autofmt_xdate() plt.xlabel('days') plt.ylabel('temp (in F)') plt.grid() plt.legend() plt.show() # get the weather of the white house ny_near_street = '1+Scott+Ave' ny_near_city = 'Yougstown' ny_near_state = 'NY' ny_near_zipcode = "14174" ny_street = '20+W+34th+st' ny_city = 'New York' ny_state = 'NY' ny_zipcode = '10001' dc_street = "1600+Pennsylvania+Avenue+NW" dc_city = "Washington" dc_state = "DC" dc_zipcode = "20500" other_street = (input('What is the number of your loc ') + '+' + input('What is the road name ') + '+' + input('What is the dr, ave, rd, etc ')) other_city = input('What is the city name? ') i = 0 for ob in other_city: if ob == ' ': other_city = other_city[:i] + '+' + other_city[i+1:] i += 1 other_state = input('What is the name of the state ') while True: try: other_zipcode = int(input('What is the zipcode ')) break except: print('That is not a number') other_name = input('What is the name of this place? ') hour = input('Would you like hourly or daily? (h/d) ') NY_near = Weather(ny_near_street, ny_near_city, ny_near_state, ny_near_zipcode, 'NY Near', hour) DC = Weather(dc_street, dc_city, dc_state, dc_zipcode, 'DC', hour) NY = Weather(ny_street, ny_city, ny_state, ny_zipcode, 'NY', hour) try: other = Weather(other_street, other_city, other_state, other_zipcode, other_name, hour) locs = [NY, DC, NY_near, other] other_loc = True except: print('This address is invaild, countining with other address') locs = [NY, DC, NY_near] other_loc = False chart = input('would you like a chart? (y/n) ') if chart == 'y': while True: loc = input('What loc would you like to print? (all/DC/NY Near/NY, or if it worked, ' + other_name + ' if it worked) ') if loc == 'all': plt_display_forecast(locs, hour) break elif loc == 'DC': plt_display_forecast([DC], hour) break elif loc == 'NY': plt_display_forecast([NY], hour) break elif loc == 'NY Near': plt_display_forecast([NY_near], hour) break if loc == other_name: if other_loc == True: plt_display_forecast([other], hour) break else: print('sorry ' + other_name + ' is not working') else: while True: loc = input('What loc would you like to print? (all/DC/NY Near/NY, or if it worked, ' + other_name + ' if it worked) ') if loc == 'NY': NY.txt_display_forecast() break elif loc == 'DC': DC.txt_display_forecast() break elif loc == 'NY Near': NY_near.display_forecast() break if loc == other_name: if other_loc == True: plt_display_forecast([other], hour) break else: print('sorry ' + other_name + ' is not working')
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/search.py
import tkinter as tk class search(tk.Frame): def __init__(self, items, master=None): super().__init__(master) self.master = master self.items = items self.pack() self.cteate() def create(self): self.entry1 = tk.Entry(self.master, justify='right') self,entry1.place(x=0, y=100, width=1000, height=25)
jonahmakowski/PyWrskp
src/alarm/time_only.py
<reponame>jonahmakowski/PyWrskp import datetime def work(hour, mint, print_info=True): hour = int(hour) mint = int(mint) now = datetime.datetime.now() past_time = datetime.datetime(now.year, now.month, now.day, hour, mint) past_time = past_time.strftime("%X") while True: now = datetime.datetime.now() now = now.strftime("%X") if now == past_time: if print_info: print('DING-DONG') print('Time up!') return 'DING-Dong'
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/class_2mm.py
<reponame>jonahmakowski/PyWrskp # import datetime # print(datetime.date.today()) import pygame # definitions of the available colors BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) PURPLE = (255, 0, 234) GREY = (131, 131, 131) ORANGE = (255, 174, 0) # definitions of available buttons buttonMinus = pygame.image.load('button_minus.png') buttonPlus = pygame.image.load('button_plus.png') # definitions of lists of currently used pen-colors and buttons colors = [RED, GREEN, BLUE, BLACK, PURPLE, ORANGE] buttons = [buttonMinus, buttonPlus] # dimensions and sizes used eraser = BLACK DIS_WIDTH = 1280 DIS_HEIGHT = 820 recWidth = int(DIS_WIDTH * 0.1) recHeight = int(DIS_HEIGHT * 0.09) button_size = int(recHeight / 2) max_radius = int(recHeight / 2) min_radius = 5 button_x = int((DIS_WIDTH - (max_radius * 4))) radius_change = 5 # increase/decrease of radius through -/+ buttons ini_radius = 15 # initial/default radius # initialize currentColour = colors[0] radius = ini_radius pygame.init() screen = pygame.display.set_mode([DIS_WIDTH, DIS_HEIGHT]) pygame.display.set_caption("Paint") def menu(): # display rectangles with pen-colors and buttons to change the radius menu_bar = pygame.Rect((0, 0), (DIS_WIDTH, recHeight)) pygame.draw.rect(screen, GREY, menu_bar) x = 0 # current x position y = 0 # current y position for col in colors: # draw rectangles for changing the pen color rectangle = pygame.Rect((x, y), (recWidth, recHeight)) pygame.draw.rect(screen, col, rectangle) x += recWidth for button in buttons: # draw button for decreasing/increasing the pen size plus_minus = pygame.transform.scale(button, (button_size, button_size)) plus_minus_rec = plus_minus.get_rect(topleft=(button_x, y)) screen.blit(plus_minus, plus_minus_rec) y += button_size pygame.draw.circle(screen, currentColour, (DIS_WIDTH - int(1.5 * max_radius), int(recHeight/2)), radius) pygame.display.update() def change_pen(): # returns True if the pen (color or size) was changed, otherwise returns False global recWidth global currentColour global button_x global radius x = 0 y = 0 for col in colors: rectangle = pygame.Rect((x, 0), (recWidth, recHeight)) x += recWidth if rectangle.collidepoint(spot): currentColour = col menu() # need to be repainted for the changed pen color return True is_first = True for button in buttons: plus_minus = pygame.transform.scale(button, (button_size, button_size)) plus_minus_rec = plus_minus.get_rect(topleft=(button_x, y)) if plus_minus_rec.collidepoint(spot): if is_first: # decrease the radius for the first/top button radius -= radius_change if radius < min_radius: radius = min_radius else: # increase the radius for the second/bottom button radius += radius_change if radius > max_radius: radius = max_radius menu() # need to be repainted for the changed pen size return True y += button_size is_first = False return False # processing mouse events menu() keep_going = True mouse_down = False while keep_going: for event in pygame.event.get(): if event.type == pygame.QUIT: keep_going = False break if event.type == pygame.MOUSEBUTTONDOWN: spot = pygame.mouse.get_pos() if change_pen(): mouse_down = False else: mouse_down = True elif event.type == pygame.MOUSEBUTTONUP: mouse_down = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: screen.fill(BLACK) eraser = BLACK elif event.key == pygame.K_z: # change the canvas background to the current color screen.fill(currentColour) eraser = currentColour elif event.key == pygame.K_r: # reset the radius to the initial value radius = ini_radius elif event.key == pygame.K_i: # increase the radius size (same as through the + button) radius += radius_change if radius > max_radius: radius = max_radius elif event.key == pygame.K_d: # decrease the radius size (same as through the - button) radius -= radius_change if radius < min_radius: radius = min_radius menu() # repaint menu (for possibly changed pen-size or color) if mouse_down: # mouse not pointing to menu spot = pygame.mouse.get_pos() if spot[1] > recHeight: # mouse in the painting area margin = spot[1] - recHeight paint_radius = radius if margin < radius: # paint only below the menu bar paint_radius = margin else: paint_radius = radius if eraser != currentColour: pygame.draw.circle(screen, currentColour, spot, paint_radius) elif eraser == currentColour: pygame.draw.circle(screen, currentColour, spot, paint_radius * 2) pygame.display.update() pygame.quit()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/class_4.py
import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.createWidgets() def createWidgets(self): self.txtEdit = tk.Text(self) self.btnFrame = tk.Frame(self) self.btnOpen = tk.Button(self.btnFrame, text='Open', command=self.openFile) self.btnSave = tk.Button(self.btnFrame, text='Save as', command = self.saveFile) self.txtEdit.grid(row=0, column=1, sticky='nsew') self.btnFrame.grid(row = 0, column=0, sticky='ns') self.btnOpen.grid(row=0, column=0, sticky= 'ew') self.btnSave.grid(row=1, column=0, sticky= 'ew') def openFile(self): fp = askopenfilename(filetypes=[('Text Files', '*.txt'), ('Python Files', '*.py'), ('All Files', '*.*')]) if not fp: return self.txtEdit.delete(1.0, tk.END) with open(fp, 'r') as inFile: txt = inFile.read() self.txtEdit.insert(tk.END, txt) def saveFile(self): fp = asksaveasfilename(filetypes=[('Text Files', '*.txt'), ('Python Files', '*.py'), ('All Files', '*.*')]) if not fp: return with open(fp, 'w') as outFile: txt = self.txtEdit.get(1.0, tk.END) outFile.write(txt) root = tk.Tk() root.title('Text Editer') root.rowconfigure(0, minsize =800, weight = 1) root.columnconfigure(1, minsize =600, weight=1) app = Application(master=root) app.mainloop()
jonahmakowski/PyWrskp
src/custom_slack_bot/bot.py
import slack import os from pathlib import Path from dotenv import load_dotenv env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) client = slack.WebClient(token=os.environ['SLACK_TOKEN']) user = input('What is your name?') print('What would you like to send?') mess = '' while True: message = input() if message == ' ': break message += '\n' mess += message final_message = ('{}\n\nSent by: @{}'.format(mess, user)) client.chat_postMessage(channel='#general', text=final_message)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/class_3_example_classes.py
<filename>src/other/Other_from_2020-2021/classes/class_3_example_classes.py class Student: role = "learn" def __init__(self, name, grade): self.name = name self.grade = grade class Teacher: role = "teach" def __init__(self, name, subject): self.name = name self.subject = subject class School: roster = [] def __init__(self, school_name): self.school_name = school_name def add_members(self): name = input('What is their name ') is_student = input('Are they a student? (y/n)') if is_student == 'y': grade = input('What grade are they in? ') new_member = Student(name, grade) else: subject = input('What do they teach? ') new_member = Teacher(name, subject) self.roster.append(new_member) if input('Add another member? (y/n) ') == 'y': self.add_members() def show_roster(self): for member in self.roster: if isinstance(member, Teacher): print('{} is a teacher, they teach {}'.format(member.name, member.subject)) elif isinstance(member, Student): print('{} is a student, they are in grade {}'.format(member.name, member.grade)) class School_board: schools = [] def __init__(self, loc, board_name): self.loc = loc self.board_name = board_name def add_schools(self, school_v, other_schools): school_name = input('Is ' + school_v.school_name + ' the school you want to add? (y/n)') if school_name == 'y': school_name = school_v.school_name elif school_name == 'n': name = input('What school would you like?') for i in range (len(other_schools)): if name == other_schools[i]: school_name = other_schools[i] break self.schools.append(school_name) new = input('Would you like to add a new school? (y/n)') if new == 'y': self.add_schools(school_v, other_schools) def show_schools(self): for i in self.schools: print(i) brookdale = School('brookdale') pine_grove = School('pine_grove') schools = [brookdale, pine_grove] halton = School_board('Halton', 'Halton school board (HDSB)') brookdale.add_members() pine_grove.add_members() halton.add_schools(brookdale, schools)
jonahmakowski/PyWrskp
src/notes/notes.py
<gh_stars>0 import json class Notes: def __init__(self, name='data3.jonahtext'): self.notes = [] self.name = name def add_note(self, note): self.notes.append(note) def print_notes(self): try: with open(self.name) as json_file: self.notes += json.load(json_file) except: pass if self.notes != []: for item in self.notes: print('{}'.format(item)) if self.notes == []: print("you don't have any notes saved!") def save_notes(self): with open(self.name, 'w') as outfile: json.dump(self.notes, outfile) def clear(self): self.notes = [] self.save_notes() if __name__ == "__main__": n = Notes() n.print_notes() add = input('would you like to add any note? (y/n/c)') if add == 'y': info = input('what is your note?') n.add_note(info) n.save_notes() print('your note, "{}" has been added to your saved notes!'.format(info)) elif add == 'c': n.clear()
jonahmakowski/PyWrskp
src/classroom_tools/classroom_tools_extras.py
from random import randint as r import time def math_game(coins): opration = r(1, 4) num_1 = r(0, 9999999) num_2 = r(0, 9999999) if opration == 1: opration = '+' question = '{} {} {}'.format(num_1, opration, num_2) a = str(num_1 + num_2) elif opration == 2: opration = '-' question = '{} {} {}'.format(num_1, opration, num_2) a = str(num_1 - num_2) elif opration == 3: opration = '*' question = '{} {} {}'.format(num_1, opration, num_2) a = str(num_1 * num_2) elif opration == 4: opration = '/' question = '{} {} {}'.format(num_1, opration, num_2) a = str(num_1 / num_2) else: print('error') question = 'error' # this is to solve an error found by pycharm a = 'error' # this is to solve an error found by pycharm exit(404) g = input('What is ' + question + '?') if g == a: print('Good job you got it correct! you earned 10 coins') coins += 10 print('You now have {} coins'.format(coins)) else: print('You got it incorrect, you lost 5 coins') coins -= 5 print('You now have {} coins'.format(coins)) if g == '': print('if you are playing basic mode this coins will be returned') return g, coins def basic_math_game(): print('WELCOME TO') print("JONAH'S MATH GAME!") print('entering nothing will end the game!') coins = 0 while True: g, coins = math_game(coins) if g == '': coins += 5 return print('GAME OVER') print('You have {} coins right now'.format(coins)) def challange_math_game(people): scores = {} while len(people) > 0: current_player = people[0] print('Your turn {}'.format(current_player)) time.sleep(1) coins = 0 for i in range(4): g, coins = math_game(coins) scores[current_player] = coins del people[0] print('Final scores:') for person in scores: print(str(person) + ': ' + str(scores[person]))
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/fun_math_game.py
<filename>src/other/Other_from_2020-2021/home/fun_math_game.py num = 1 money = 0 streak = 0 add = 1 while True: q = (str(num) + ' + ' + str(num)) question = input('What is ' + q + '?\n') an = str(num + num) if question == an: print('good job\nyou earned $' + str(num)) money += num streak += 1 print('you have a streak of ' + str(streak)) if int(streak / 5) >= 1: add = int(streak / 5) elif int(streak / 5) < 1: add = 1 elif question != an: print('you got it incorrect the correct A is ' + an) print('you lost $' + str(int(num / 2))) print('you lost a streak of ' + str(streak)) money -= int(num/2) streak = 0 if streak >= 20: num += 10 if streak >= 30: num += 10 if streak >= 40: num += 10 if streak >= 50: num += 10 if money <= -1000: break if num >= 1: break print('you have $' + str(money) + '!') num += add if money <= -1000: print('you have lost b/c you have $' + money + ' so you have gone bankrupt') elif num >= 1: print('you have won as you just solved ' + q)
jonahmakowski/PyWrskp
src/catalog/fuction.py
<gh_stars>0 import webbrowser def online_search(): author = input('What is the author of the book?') author = list(author) for i in range(len(author)): if author[i] == ' ': author[i] = '+' author2 = '' for char in author: author2 += char title = input('What is the title of the book?') title = list(title) for i in range(len(title)): if title[i] == ' ': title[i] = '+' title2 = '' for char in title: title2 += char #print('Click here:') #print('https://www.google.com/search?q={}%2C+{}'.format(author2, title2) webbrowser.open('https://www.google.com/search?q={}%2C+{}'.format(author2, title2)) def wait(): input('Press enter to continue')
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/turtle_hi.py
<filename>src/other/Other_from_2020-2021/home/turtle_hi.py<gh_stars>0 import turtle t = turtle.Turtle() t.penup t.goto(140, 10) t.pendown() def hi(): t.left(90) t.forward(100) t.backward(50) t.right(90) t.forward(50) t.left(90) t.forward(50) t.backward(100) t.right(90) t.penup() t.forward(50) t.left(90) t.pendown() t.forward(75) t.penup() t.forward(10) t.pendown() t.forward(1) t.penup() t.right(90) t.forward(100) t.pendown() hi() hi() hi()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/shape maker.py
import turtle t = turtle.Turtle() t.right(90) t.penup() t.forward(100) t.left(90) t.pendown() t.speed(1) sides = int(input('How many sides would you like?\n')) length_sides = int(input('How long would you like the sides to be?\n')) for i in range(sides): t.left(360 / sides) t.forward(length_sides)
jonahmakowski/PyWrskp
src/sudoku/Player.py
<reponame>jonahmakowski/PyWrskp # Player found from https://www.geeksforgeeks.org/building-and-visualizing-sudoku-game-using-pygame/ # import pygame library import pygame # initialise the pygame font pygame.font.init() # Total window screen = pygame.display.set_mode((500, 600)) # Title and Icon pygame.display.set_caption("SUDOKU SOLVER") x = 0 y = 0 dif = 500 / 9 val = 0 # Default Sudoku Board. from creator import sudoku grid =[ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7] ] # Load test fonts for future use font1 = pygame.font.SysFont("comicsans", 40) font2 = pygame.font.SysFont("comicsans", 20) def get_cord(pos): global x x = pos[0]//dif global y y = pos[1]//dif # Highlight the cell selected def draw_box(): for i in range(2): pygame.draw.line(screen, (255, 0, 0), (x * dif-3, (y + i)*dif), (x * dif + dif + 3, (y + i)*dif), 7) pygame.draw.line(screen, (255, 0, 0), ( (x + i)* dif, y * dif ), ((x + i) * dif, y * dif + dif), 7) # Function to draw required lines for making Sudoku grid def draw(): # Draw the lines for i in range (9): for j in range (9): if grid[i][j]!= 0: # Fill blue color in already numbered grid pygame.draw.rect(screen, (0, 153, 153), (i * dif, j * dif, dif + 1, dif + 1)) # Fill grid with default numbers specified text1 = font1.render(str(grid[i][j]), 1, (0, 0, 0)) screen.blit(text1, (i * dif + 15, j * dif + 15)) # Draw lines horizontally and verticallyto form grid for i in range(10): if i % 3 == 0 : thick = 7 else: thick = 1 pygame.draw.line(screen, (0, 0, 0), (0, i * dif), (500, i * dif), thick) pygame.draw.line(screen, (0, 0, 0), (i * dif, 0), (i * dif, 500), thick) # Fill value entered in cell def draw_val(val): text1 = font1.render(str(val), 1, (0, 0, 0)) screen.blit(text1, (x * dif + 15, y * dif + 15)) # Raise error when wrong value entered def raise_error1(): text1 = font1.render("WRONG !!!", 1, (0, 0, 0)) screen.blit(text1, (20, 570)) def raise_error2(): text1 = font1.render("Wrong !!! Not a valid Key", 1, (0, 0, 0)) screen.blit(text1, (20, 570)) # Check if the value entered in board is valid def valid(m, i, j, val): for it in range(9): if m[i][it]== val: return False if m[it][j]== val: return False it = i//3 jt = j//3 for i in range(it * 3, it * 3 + 3): for j in range (jt * 3, jt * 3 + 3): if m[i][j]== val: return False return True # Solves the sudoku board using Backtracking Algorithm def solve(grid, i, j): while grid[i][j]!= 0: if i<8: i+= 1 elif i == 8 and j<8: i = 0 j+= 1 elif i == 8 and j == 8: return True pygame.event.pump() for it in range(1, 10): if valid(grid, i, j, it)== True: grid[i][j]= it global x, y x = i y = j # white color background\ screen.fill((255, 255, 255)) draw() draw_box() pygame.display.update() pygame.time.delay(20) if solve(grid, i, j)== 1: return True else: grid[i][j]= 0 # white color background\ screen.fill((255, 255, 255)) draw() draw_box() pygame.display.update() pygame.time.delay(50) return False # Display instruction for the game def instruction(): text1 = font2.render("PRESS D TO RESET TO DEFAULT / R TO EMPTY", 1, (0, 0, 0)) text2 = font2.render("ENTER VALUES AND PRESS ENTER TO VISUALIZE", 1, (0, 0, 0)) screen.blit(text1, (20, 520)) screen.blit(text2, (20, 540)) # Display options when solved def result(): text1 = font1.render("FINISHED PRESS R or D", 1, (0, 0, 0)) screen.blit(text1, (20, 570)) run = True flag1 = 0 flag2 = 0 rs = 0 error = 0 # The loop thats keep the window running while run: # White color background screen.fill((255, 255, 255)) # Loop through the events stored in event.get() for event in pygame.event.get(): # Quit the game window if event.type == pygame.QUIT: run = False # Get the mouse position to insert number if event.type == pygame.MOUSEBUTTONDOWN: flag1 = 1 pos = pygame.mouse.get_pos() get_cord(pos) # Get the number to be inserted if key pressed if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x-= 1 flag1 = 1 if event.key == pygame.K_RIGHT: x+= 1 flag1 = 1 if event.key == pygame.K_UP: y-= 1 flag1 = 1 if event.key == pygame.K_DOWN: y+= 1 flag1 = 1 if event.key == pygame.K_1: val = 1 if event.key == pygame.K_2: val = 2 if event.key == pygame.K_3: val = 3 if event.key == pygame.K_4: val = 4 if event.key == pygame.K_5: val = 5 if event.key == pygame.K_6: val = 6 if event.key == pygame.K_7: val = 7 if event.key == pygame.K_8: val = 8 if event.key == pygame.K_9: val = 9 if event.key == pygame.K_RETURN: flag2 = 1 # If R pressed clear the sudoku board if event.key == pygame.K_r: rs = 0 error = 0 flag2 = 0 grid =[ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0] ] # If D is pressed reset the board to default if event.key == pygame.K_d: rs = 0 error = 0 flag2 = 0 grid =[ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7] ] if flag2 == 1: if solve(grid, 0, 0)== False: error = 1 else: rs = 1 flag2 = 0 if val != 0: draw_val(val) # print(x) # print(y) if valid(grid, int(x), int(y), val)== True: grid[int(x)][int(y)]= val flag1 = 0 else: grid[int(x)][int(y)]= 0 raise_error2() val = 0 if error == 1: raise_error1() if rs == 1: result() draw() if flag1 == 1: draw_box() instruction() # Update window pygame.display.update() # Quit pygame window pygame.quit()
jonahmakowski/PyWrskp
src/other/is_it_the_word.py
class IsItAWord: def __init__(self, word): self.word = word self.word_list = list(word) self.rever = '' self.reverse() def reverse(self): for i in range(len(self.word_list) - 1, -1, -1): self.rever += self.word_list[i] # print(self.rever) # print(i) def check(self): if self.rever == self.word: print('If you reverse the word {} you will get the same word'.format(self.word)) else: print('If you reverse the word {} you get {}'.format(self.word, self.rever)) print('So it does not work') def check_blind(self): if self.rever == self.word: return 'If you reverse the word {} you will get the same word'.format(self.word) else: return 'If you reverse the word {} you get {}'.format(self.word, self.rever) if __name__ == "__main__": is_it_a_word = IsItAWord(input('What word would you like to check?')) is_it_a_word.check()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/class_onea.py
<gh_stars>0 import pygame print('version 0') pygame.init() screen = pygame.display.set_mode([1375,750]) pygame.display.set_caption("Paint (press space bar to erase all)") keep_going = True mouse_down = False BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) PURPLE = (251, 0, 255) YELLOW = (255, 247, 0) TEAL = (0, 255, 255) ORANGE = (255, 196, 0) LIME = (132, 255, 0) currentColour = (0, 0, 0) radius = 10 redRectangle = pygame.Rect((0, 0), (50, 50)) greenRectangle = pygame.Rect((50, 0), (50, 50)) blueRectangle = pygame.Rect((100, 0), (50, 50)) blackRectangle = pygame.Rect((150, 0), (50, 50)) purpleRectangle = pygame.Rect((200, 0), (50, 50)) yellowRectangle = pygame.Rect((250, 0), (50, 50)) tealRectangle = pygame.Rect((300, 0), (50, 50)) orangeRectangle = pygame.Rect((350, 0), (50, 50)) limeRectangle = pygame.Rect((400, 0), (50, 50)) whiteRectangle = pygame.Rect((450, 0), (50, 50)) dotRectangle5 = pygame.Rect((500, 0), (50,50)) dotRectangle10 = pygame.Rect((550, 0), (50,50)) dotRectangle15 = pygame.Rect((600, 0), (50,50)) dotRectangle20 = pygame.Rect((650, 0), (50,50)) dotRectangle25 = pygame.Rect((700, 0), (50,50)) while keep_going: for event in pygame.event.get(): if event.type == pygame.QUIT: keep_going = False elif event.type == pygame.MOUSEBUTTONDOWN: mouse_down = True elif event.type == pygame.MOUSEBUTTONUP: mouse_down = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: screen.fill(currentColour) pygame.display.update() if mouse_down: # if the event is pressing the mouse # get the current position of the mouse spot = pygame.mouse.get_pos() x = spot[0] y = spot[1] if x < 50 and y <= 50: # if the current position is within the red square, change the colour to red currentColour = RED elif (x < 100 and x >= 50) and y <= 50: # if the current position is within the green square, change the colour to green currentColour = GREEN elif (x < 150 and x >= 100) and y <= 50: # if the current position is within the blue square, change the colour to blue currentColour = BLUE elif (x < 200 and x >= 150) and y <= 50: # if the current position is within the black square, change the colour to black currentColour = BLACK elif (x < 250 and x >= 200) and y <= 50: # if the current position is within the purple square, change the colour to purple currentColour = PURPLE elif (x < 300 and x >= 250) and y <= 50: # if the current position is within the yellow square, change the colour to yellow currentColour = YELLOW elif (x < 350 and x >= 300) and y <= 50: # if the current position is within the teal square, change the colour to teal currentColour = TEAL elif (x < 400 and x >= 350) and y <= 50: # if the current position is within the orange square, change the colour to orange currentColour = ORANGE elif (x < 450 and x >= 400) and y <= 50: # if the current position is within the orange square, change the colour to orange currentColour = LIME elif (x < 500 and x >= 450) and y <= 50: # if the current position is within the orange square, change the colour to orange currentColour = WHITE elif (x < 550 and x >= 500) and y <= 50: radius = 5 elif (x < 600 and x >= 550) and y <= 50: radius = 10 elif (x < 650 and x >= 600) and y <= 50: radius = 15 elif (x < 700 and x >= 650) and y <= 50: radius = 20 elif (x < 750 and x >= 700) and y <= 50: radius = 25 else: # if it's not within a button, place a circle at the spot the mouse was pressed pygame.draw.circle(screen, currentColour, spot, radius) pygame.display.update() pygame.draw.rect(screen, RED, redRectangle) pygame.draw.rect(screen, GREEN, greenRectangle) pygame.draw.rect(screen, BLUE, blueRectangle) pygame.draw.rect(screen, BLACK, blackRectangle) pygame.draw.rect(screen, PURPLE, purpleRectangle) pygame.draw.rect(screen, YELLOW, yellowRectangle) pygame.draw.rect(screen, TEAL, tealRectangle) pygame.draw.rect(screen, ORANGE, orangeRectangle) pygame.draw.rect(screen, LIME, limeRectangle) pygame.draw.rect(screen, WHITE, whiteRectangle) pygame.display.update() pygame.draw.rect(screen, BLACK, dotRectangle5) pygame.draw.rect(screen, BLACK, dotRectangle10) pygame.draw.rect(screen, BLACK, dotRectangle15) pygame.draw.rect(screen, BLACK, dotRectangle20) pygame.draw.rect(screen, BLACK, dotRectangle25) pygame.draw.circle(screen, WHITE, (525, 25), 5) pygame.draw.circle(screen, WHITE, (575, 25), 10) pygame.draw.circle(screen, WHITE, (625, 25), 15) pygame.draw.circle(screen, WHITE, (675, 25), 20) pygame.draw.circle(screen, WHITE, (725, 25), 25) pygame.display.update() pygame.quit()
jonahmakowski/PyWrskp
src/JupyterLab/Helper_files/game_code.py
<filename>src/JupyterLab/Helper_files/game_code.py import time import random def monster_fight(monster_name, monster_health, monster_damage_range, player_username, player_health, player_items): print('A {} is fighting you, {}!'.format(monster_name, player_username)) print('It has {} health!'.format(monster_health)) print('It can do from {} to {} damage!'.format(monster_damage_range[0], monster_damage_range[1])) time.sleep(3) while player_health >= 1 and monster_health >= 1: current_attack_damage = 0 print() print() print() print() print('What attack would you like to use?') print('Here are your options:') for item in player_items: print('Name: {}, Damage: {}'.format(item['name'], item['damage'])) current_correct = False current_attack_name = input('choose one\n') for item in player_items: if item['name'] == current_attack_name: current_attack_damage = int(item['damage']) current_correct = True if current_correct: print('You did {} damage!'.format(current_attack_damage)) time.sleep(0.5) monster_health -= current_attack_damage print('The monster now has {} health!'.format(monster_health)) if monster_health < 1: break monster_damage = random.randint(monster_damage_range[0], monster_damage_range[1]) print('the monster does {} damage!'.format(monster_damage)) time.sleep(1) player_health -= monster_damage print('you now have {} health!'.format(player_health)) time.sleep(1) if player_health <= 0: print('You Died!') exit(0) elif monster_health <= 0: print('Good Job!') print('you beat the {}!'.format(monster_name)) return player_health def learn_spell(spell): print('you are learn how to cast the {} spell'.format(spell)) for i in range(5): time.sleep(0.5) print() print('Woosh') time.sleep(0.5) print() print('BANG') time.sleep(0.5) print() print('CRASH') print('Good Job!') time.sleep(0.5) print('You have learned the spell!') def learn_all(dic, objects): if dic['type'] == 's': del dic['type'] learn_spell(dic['name']) objects.append(dic) return items elif dic['type'] == 'w': del dic['type'] objects.append(dic) return items else: print('ERROR') exit() def make_monster(letters): creation_health = random.randint(10, 500) creation_name = '' for i in range(random.randint(1, 50)): creation_name += letters[random.randint(0, len(letters) - 1)] creation_attack_range = [0, random.randint(1, 200)] return creation_name, creation_health, creation_attack_range abcs = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '.', ',', '[', ']', '{', '}', ':', ';', "'", '"', '?'] ''' this is the format for the dic below: {'name': '', 'damage': '', 'type': ''} ''' unlearned = [{'name': 'Sword', 'damage': '10', 'type': 'w'}, {'name': 'Flame Tongue', 'damage': '20', 'type': 's'}, {'name': 'Spear', 'damage': '25', 'type': 'w'}, {'name': 'Flame Dance', 'damage': '40', 'type': 's'}, {'name': 'Scythe', 'damage': '60', 'type': 'w'}, {'name': 'Lightning Strike', 'damage': '120', 'type': 's'}, {'name': 'Javelin', 'damage': '80', 'type': 'w'}, {'name': 'Fire dance', 'damage': '200', 'type': 's'}] health = 100 items = [] print('Welcome To My Game!') time.sleep(1) username = input('Stranger: What is your username, brave adventurer?\n') time.sleep(1) print() print() print('Stranger: Welcome to Alglia {}!'.format(username)) time.sleep(1) why = input('Stranger: What brings you here?\nthe challange?\n') if why != 'the challenge' and why != 'yes': print('{} is not allowed'.format(why)) print('code is terminated') exit(4913901809481390841) print('Stranger: I knew it!') print() print('Stranger: I will tell you what is happening, a group of monstors has come and have been attacking the village for months now, the poorer people are running out of food, we need help, fast') print('Stranger: I think you might just be the help we need!') print('Stranger: My name is Bob') print('Bob: Come, you can sleep in my house tonight!') time.sleep(2) print() print('Bob: WAKE UP!!!') time.sleep(0.5) print('Bob: We need your help, there is a dhfai attacking us!') print('Bob: Here is a sword...') time.sleep(0.5) print() print('YOU GOT A SWORD!') learn_all(unlearned[0], items) del unlearned[0] print('It Does 10 Damage!') time.sleep(0.5) health = monster_fight('dhfai', 50, [10, 25], username, health, items) time.sleep(0.5) print('Bob: Thanks for helping us!') print('Bob: Let me heal you') time.sleep(2) if username == 'WhiteSwine': health = 10000 else: health = 500 print('Bob: There you are, your health is now {}!'.format(health)) print('Bob: Good job out there!') print('Bob: I think it is time you go out on your own!') time.sleep(1) print('Bob: but first, you need something better than a Sword!') time.sleep(2) print('Here is my old wand, it will let you cast spells!') print('I will teach you how to cast the first, and most basic spell, here') learn_all(unlearned[0], items) print('YOU GOT THE SPELL FLAME TONGUE!') del unlearned[0] print('It Does 20 Damage!') while len(unlearned) > 0: info_name, info_health, info_damage_range = make_monster(abcs) monster_fight(info_name, info_health, info_damage_range, username, health, items) print() learn_all(unlearned[0], items) print('You learned how to use the {}'.format(unlearned[0]['name'])) print() print('Good Job!') print('You Beat the Game!')
jonahmakowski/PyWrskp
src/coder-decoder/coder.py
<reponame>jonahmakowski/PyWrskp class CoderDecoder: def __init__(self, print_info=True): self.abcs = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '.', ',', '[', ']', '{', '}', ':', ';', "'", '"', '?'] self.finished = '' self.print_info = print_info self.key = '' self.message = '' def add_vars(self, message, key): self.message = message self.key = key def code(self): message = list(self.message) new_message = [] new_message_str = '' for i in range(len(message)): for l in range(len(self.abcs)): if self.abcs[l] == message[i]: try: new_message.append(self.abcs[l + self.key]) except: if (l + self.key) >= len(self.abcs): loc = (l + self.key) - len(self.abcs) new_message.append(self.abcs[loc]) for item in new_message: new_message_str += item if self.print_info: print('your coded message is {}'.format(new_message_str)) print('give your friend this info:') print('message: {}\ncode: {}'.format(new_message_str, self.key)) return new_message_str def decode(self): message = list(self.message) new_message = [] new_message_str = '' for i in range(len(message)): for l in range(len(self.abcs)): if self.abcs[l] == message[i]: try: new_message.append(self.abcs[l - self.key]) except: pass for item in new_message: new_message_str += item if self.print_info: print('your decoded message is {}'.format(new_message_str)) return new_message_str
jonahmakowski/PyWrskp
src/other/counter.py
<gh_stars>0 count_type = input('What count type would you like to use?\n') if count_type == 'with spaces': string = input('Paste what you want to count\n') string = list(string) print('Here is the length of your text:') print(len(string)) else: print('you have choosen not including spaces') string = input('Paste what you want to count\n') string = list(string) count = 0 length = len(string) for i in range(len(string)): item = string[count] if item == ' ': del string[count] # print(string) # uncommenting this will make the current list print else: count += 1 print('Here is the length of your text:') print(len(string)) print() print('your text without spaces is:') stri = '' for item in string: stri += item print(stri)
jonahmakowski/PyWrskp
src/sudoku/creator.py
''' THIS DOES NOT WORK ''' from solve_mm1 import Board def sudoku(size): import time start_time=time.time() import sys import random as rn mydict = {} n = 0 # print ('--started calculating--') while len(mydict) < 9: n += 1 x = range(1, size+1) testlist = rn.sample(x, len(x)) isgood = True for dictid,savedlist in mydict.items(): if isgood == False: break for v in savedlist: if testlist[savedlist.index(v)] == v: isgood = False break if isgood == True: isgoodafterduplicatecheck = True mod = len(mydict) % 3 dsavedlists = {} dtestlists = {} dcombindedlists = {} for a in range(1,mod + 1): savedlist = mydict[len(mydict) - a] for v1 in savedlist: modsavedlists = (savedlist.index(v1) / 3) % 3 dsavedlists[len(dsavedlists)] = [modsavedlists,v1] for t1 in testlist: modtestlists = (testlist.index(t1) / 3) % 3 dtestlists[len(dtestlists)] = [modtestlists,t1] for k,v2 in dsavedlists.items(): dcombindedlists[len(dcombindedlists)] = v2 dcombindedlists[len(dcombindedlists)] = dtestlists[k] vsave = 0 lst1 = [] for k, vx in dcombindedlists.items(): vnew = vx[0] if not vnew == vsave: lst1 = [] lst1.append(vx[1]) else: if vx[1] in lst1: isgoodafterduplicatecheck = False break else: lst1.append(vx[1]) vsave = vnew if isgoodafterduplicatecheck == True: mydict[len(mydict)] = testlist # print ('success found', len(mydict), 'row') # print ('--finished calculating--') total_time = time.time()-start_time return mydict return_dict = sudoku(9) # print ('') # print ('--printing output--') for n,v in return_dict.items(): print (n,v) # print ('process took',total_tries,'tries in', round(amt_of_time,2), 'secs') # print ('-------------------')
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/preschool_drawing.py
from random import randint as random import turtle from time import sleep screen = turtle.Screen() DIS_WIDTH = 1280 DIS_HEIGHT = 750 x_max = DIS_WIDTH y_max = DIS_HEIGHT screen.setup(DIS_WIDTH, DIS_HEIGHT) turtles = {} colors = ['black','blue','yellow','green','purple','orange','gold'] for i in range(len(colors)): t = turtle.Turtle() turtles['turtle' + str(i)] = t turtles['turtle' + str(i)].color(colors[i]) turtles['turtle' + str(i)].speed(0) d = 0 while True: for i in range(10): for i in range(len(turtles)): turtles['turtle' + str(i)].forward(random(10, 15)) turtles['turtle' + str(i)].left(random(1, 90)) sleep(1 / len(turtles)) for i in range(10): for i in range(len(turtles)): turtles['turtle' + str(i)].forward(random(10, 15)) turtles['turtle' + str(i)].right(random(1, 90)) sleep(1 / len(turtles))
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/teams_with_captions.py
_4_5 = {'teacher':'Mr.Payne', 'students':['Ayaan', 'Nathaniel', 'Ethan', 'Kennedy', 'Shay', 'Dimitriana','Laith','Tamanna', 'Anna', 'Kaitlyn', 'Nathan', 'Jonah', 'Raleigh', 'Arijon', 'Jairus', 'Lauren', 'Abhijay', 'Liam', 'Lydia', 'Arionna', 'Calvin', 'Maxwell', 'Nyla']} from random import randint team_1 = [] team_2 = [] x = _4_5['students'] while len(x) >= 2: i = randint(0, len(x)-1) team_1.append(x[i]) del x[i] i = randint(0, len(x)-1) team_2.append(x[i]) del x[i] if len(x) == 1: team_1.append(x[0]) caption = team_1[i] del team_1[i] i = randint(0, len(team_1)-1) team_1 = {'team_caption':caption, 'members':team_1} team_1_members = team_1['members'] i = randint(0, len(team_2)-1) caption = team_2[i] del team_2[i] team_2 = {'team_caption':caption, 'members':team_2} team_2_members = team_2['members'] print('teacher: ' + _4_5['teacher']) print('\nteam 1:') print('team caption: ' + team_1['team_caption']) for person in team_1_members: print(person) print('\nteam 2:') print('team caption: ' + team_2['team_caption']) for person in team_2_members: print(person)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/google_photos_icon.py
import turtle from time import sleep t = turtle.Turtle() colors = ['yellow', 'green', 'blue', 'red'] curve = 3 t.speed(0) color = 0 heading = 90 for i in range(len(colors)): t.setheading(heading) t.fillcolor(colors[color]) t.begin_fill() t.goto(0, 0) t.color(colors[i]) for c in range(50): t.left(curve) t.forward(5) t.goto(0, 0) t.end_fill() color += 1 t.right(1) if heading == 270: heading = 0 else: heading += 90 t.penup() t.goto(1000, 1000) sleep(10)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/class_8.py
import requests from bs4 import BeautifulSoup url = "https://www.tiobe.com/tiobe-index/" r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") heading = soup.find(id="top20") langs = heading.findAll('td') topLangs = {} for n in range(0, len(langs), 6): topLangs.update({ langs[n].string: { "name": langs[n+3].string, "percent": langs[n+4].string, "change": langs[n+5].string } }) for place in topLangs: print("{:5}{:22}{:10}{}".format(place, topLangs[place]["name"], topLangs[place]["percent"], topLangs[place]["change"]))
jonahmakowski/PyWrskp
src/other/funnything.py
import turtle import time t = turtle.Turtle() i = 1 while True: t.write(i) i += 1 time.sleep(0.1) t.clear()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/login.py
import tkinter as tk from time import sleep from random import randint import os class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.active = False self.pas = '<PASSWORD>' self.create_widgets() self.code = '' def create_widgets(self): self.btnFrame = tk.Frame(self) self.btns = [tk.Button(self.btnFrame, text='1', command=self.one), tk.Button(self.btnFrame, text='2', command=self.two), tk.Button(self.btnFrame, text='3', command=self.three), tk.Button(self.btnFrame, text='4', command=self.four), tk.Button(self.btnFrame, text='send', command=self.send), tk.Button(self.btnFrame, text='del', command=self.d)] self.btnFrame.grid(row=0, column=0, sticky='ns') r, c = 0, 0 for item in self.btns: item.grid(row=r, column=c, sticky='ew') r += 1 def one(self): if not self.active: print('Enter the code') self.active = True else: print('1') self.code += '1' def two(self): if self.active: print('2') self.code += '2' else: print('Error Wrong Button') def three(self): if self.active: print('3') self.code += '3' else: print('Error Wrong Button') def four(self): if self.active: print('4') self.code += '4' else: print('Error Wrong Button') def d(self): if self.active: self.code = self.code[:len(self.code)-1] print(self.code) print('del') else: print('Error Wrong Button') def send(self): if self.code == self.pas: self.master.destroy() else: print('FAIL, SYSTEM SHUTTING DOWN') exit() root = tk.Tk() root.title('Login') root.rowconfigure(0, minsize=800, weight=1) root.columnconfigure(1, minsize=600, weight=1) app = Application(master=root) app.mainloop() class System(tk.Frame): def __init__(self, usr, master=None): super().__init__(master) self.master = master self.pack() self.usr = usr self.create_buttons_btns() self.runtime = 0 def create_buttons_btns(self): self.btnFrame = tk.Frame(self) self.btns = [ {'loc': [10, 10], 'item': tk.Button(self.btnFrame, text='log out', command=self.master.destroy)}, {'loc': [0, 0], 'item': tk.Button(self.btnFrame, text='Info', command=self.info)}] self.create_buttons() def create_buttons(self): self.btnFrame.grid(row=0, column=0, sticky='ns') for item in self.btns: r = item['loc'][0] c = item['loc'][1] item['item'].grid(row=r, column=c, sticky='ew') def info(self): print('\n\n\n\n\n\n\n') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~ Hello ~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') sleep(5) print('\n\n\n\n\n\n\n') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~ This system is owned and run by <NAME> ~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') sleep(4) print('\n\n\n\n\n\n\n') print('as you know the passcode is {}'.format(app.pas)) if app.active and app.pas == app.code: os.system('clear') print('system active') print('setting up system') sleep(randint(1, 10)) print('~~~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~ Hi ~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~~~') sleep(5) print('\n\n\n') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~ WELCOME TO SYSTEM ~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') sleep(5) print('\n\n\n') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~ What is your name ~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') name = input() if (name == 'Jonah' or name == 'Noah') or (name == '<NAME>' or name == '<NAME>'): sleep(2.5) print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') print('~~~~~~~~ SYSTEM 100% ACTIVE ~~~~~~~~') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') # system print('Hi {} welcome to the system!'.format(name)) root2 = tk.Tk() root2.title('System') root2.rowconfigure(0, minsize=800, weight=1) root2.columnconfigure(1, minsize=600, weight=1) system = System(name, master=root2) system.mainloop() else: exit()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/noah_and_me_turtle.py
<filename>src/other/Other_from_2020-2021/home/noah_and_me_turtle.py import turtle import extra_turtle_stuff def run(): t = turtle.Turtle() t.speed(0) sides = 6 length_sides = 50 t.fillcolor('green') t.begin_fill() extra_turtle_stuff.draw_hex(sides, length_sides, t) t.left(120) extra_turtle_stuff.draw_hex(sides, length_sides, t) t.left(120) extra_turtle_stuff.draw_hex(sides, length_sides, t) t.left(120) t.penup() t.forward(50) t.left(60) t.pendown() extra_turtle_stuff.draw_hex(sides, length_sides, t) t.end_fill t.right(120) t.forward(length_sides) t.right(60) t.forward(length_sides) t.left(120) extra_turtle_stuff.turn(100, 0.65, 'left', t) t.right(2) t.forward(length_sides - 5) t.left(360 / sides) t.forward(length_sides) extra_turtle_stuff.turn(100, 0.65, 'left', t) t.right(sides + 2) t.forward(length_sides) extra_turtle_stuff.turn(90, 0.85, 'left', t) t.right(sides * 3) t.forward(length_sides - 10) t.left(360 / sides) t.forward(length_sides) extra_turtle_stuff.turn(100, 0.7, 'left', t) t.penup() t.goto((0 + (length_sides * 3 - 15)), 30) t.right(1) t.pendown() t.forward(length_sides) extra_turtle_stuff.turn(90, 2, 'right', t) t.forward(length_sides + (length_sides * 0.2)) t.penup() t.goto((0 + (length_sides * 2 - 15)), 75) t.right(90) t.pendown() t.forward(length_sides) extra_turtle_stuff.turn(3, 30, 'left', t) t.forward(length_sides / 2) extra_turtle_stuff.turn(3, 30, 'left', t) t.forward(length_sides - 10) t.penup() t.goto((0 + (length_sides * -1.5)), 75) run()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/class_4_pt_1.py
<gh_stars>0 import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename class Application(tk.Frame): def __init__(self, name, save_loc, master=None): super().__init__(master) self.master = master self.pack() self.createwidgets() self.fp = save_loc + name def createwidgets(self): self.txtEdit = tk.Text(self) self.btnFrame = tk.Frame(self) self.btnOpen = tk.Button(self.btnFrame, text='Open', command=self.openfile) self.btnSaveas = tk.Button(self.btnFrame, text='Save as', command=self.savefile) self.btnquit = tk.Button(self.btnFrame, text='Close', command=self.master.destroy) self.btnsave = tk.Button(self.btnFrame, text='save', command=self.save) self.txtEdit.grid(row=0, column=1, sticky='nsew') self.btnFrame.grid(row=0, column=0, sticky='ns') self.btnOpen.grid(row=0, column=0, sticky='ew') self.btnSaveas.grid(row=1, column=0, sticky='ew') self.btnsave.grid(row=2, column=0, sticky='ew') self.btnquit.grid(row=4, column=0, sticky='ew') def openfile(self): testing = askopenfilename(filetypes=[('all files that work with this code', ['*.py', '*.txt', '*.docx']), ('Text Files', '*.txt'), ('Python Files', '*.py'), ('All Files', '*.*')]) if not testing: return else: self.fp = testing self.txtEdit.delete(1.0, tk.END) with open(self.fp, 'r') as inFile: txt = inFile.read() self.txtEdit.insert(tk.END, txt) def savefile(self): testing = asksaveasfilename(filetypes=[('all files that work with this code', ['*.py', '*.txt', '*.docx']), ('Text Files', '*.txt'), ('Python Files', '*.py'), ('All Files', '*.*')]) if not testing: return else: self.fp = testing with open(self.fp, 'w') as outFile: txt = self.txtEdit.get(1.0, tk.END) outFile.write(txt) def save(self): with open(self.fp, "w") as f: try: txt = self.txtEdit.get(1.0, tk.END) f.write(txt) except: print('FYI, your file did not save') def enter(self, info): self.txtEdit.insert(tk.END, info)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/class_6.py
<reponame>jonahmakowski/PyWrskp<gh_stars>0 import requests # get the weather of the white house street = '1600+Pennsylvania+Avenue+NW' city = 'Washington' state = 'DC' zipcode = "20500" geocode = requests.get("https://geocoding.geo.census.gov/geocoder/locations/address?street={}&city={}&state={}&zip={}&benchmark=4&format=json".format(street, city, state, zipcode)) coordinates = geocode.json()['result']['addressMatches'][0]['coordinates'] gridpoints = requests.get('https://api.weather.gov/points/{},{}'.format(coordinates['y'], coordinates['x'])) forecast = requests.get(gridpoints.json()['properties']['forecast']) # print(forecast.text) # uncomment to print raw forecast info for days in forecast.json()['properties']['periods']: print('{}:\n{}{}, {} \n \n {} \n \n \n'.format(days['name'], days['temperature'], days['temperatureUnit'], days['shortForecast'], days['detailedForecast']))
jonahmakowski/PyWrskp
src/other/package_testing.py
import pyWrskp t = pyWrskp.RandomNumber(10, 25)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/j_game1.py
<reponame>jonahmakowski/PyWrskp import pygame keep_going = True mouse_down = False RED = (225, 0, 0) radius = int(input('What would you like your pen size to be for this project?\n')) current_color = (0,0,0) pygame.init() screen = pygame.display.set_mode([1290, 650]) pygame.display.set_caption('Click and drag to draw dots.') WHITE = (225, 225, 225) screen.fill(WHITE) RED = (225, 0, 0) red = pygame.Rect((0,0), (50,50)) GREEN = (0, 225, 0) green = pygame.Rect((50, 0), (50,50)) BLUE = (0, 0, 225) blue = pygame.Rect((100, 0), (50,50)) BLACK = (0, 0, 0) black = pygame.Rect((150, 0), (50,50)) YELLOW = (225, 225, 3) yellow = pygame.Rect((200, 0), (50,50)) white = pygame.Rect((250, 0), (50,50)) line = pygame.Rect((300, 0), (3, 50)) white_2 = pygame.Rect((303, 0), (50,50)) screen.fill(WHITE) pygame.draw.rect(screen, RED, red) pygame.draw.rect(screen, GREEN, green) pygame.draw.rect(screen, BLUE, blue) pygame.draw.rect(screen, BLACK, black) pygame.draw.rect(screen, YELLOW, yellow) pygame.draw.rect(screen, WHITE, white) pygame.draw.rect(screen, BLACK, line) pygame.draw.rect(screen, WHITE, white_2) while keep_going: for event in pygame.event.get(): if event.type == pygame.QUIT: keep_going = False if event.type == pygame.MOUSEBUTTONDOWN: mouse_down = True if event.type == pygame.MOUSEBUTTONUP: mouse_down = False if mouse_down: spot = pygame.mouse.get_pos() x = spot[0] y = spot[1] if x < 50 and y <= 50: current_color = RED if (x >= 50 and x <= 100) and y <= 50: current_color = GREEN if (x >= 100 and x <= 150) and y <= 50: current_color = BLUE if (x >= 150 and x <= 200) and y <= 50: current_color = BLACK if (x >= 200 and x <= 250) and y <= 50: current_color = YELLOW if (x >= 250 and x <= 300) and y <= 50: current_color = WHITE screen.fill(WHITE) pygame.draw.rect(screen, RED, red) pygame.draw.rect(screen, GREEN, green) pygame.draw.rect(screen, BLUE, blue) pygame.draw.rect(screen, BLACK, black) pygame.draw.rect(screen, YELLOW, yellow) pygame.draw.rect(screen, WHITE, white) pygame.draw.rect(screen, BLACK, line) pygame.draw.rect(screen, WHITE, white_2) if (x >= 303 and x <= 353) and y <= 50: current_color = WHITE else: pygame.draw.circle(screen, current_color, spot, radius) pygame.display.update() pygame.quit()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/bday1jm1.py
<gh_stars>0 import time from datetime import date import turtle today = date.today() today == date.fromtimestamp(time.time()) month = int(input('what is the month of your birthday?\nJanuary is 1, February is 2, March is 3, April is 4, May is 5, June is 6, July is 7, August is 8, September is 9, October is 10, November is 11, and December is 12\n')) my_birthday = date(today.year, month, int(input('what is the day of your birthday?\n'))) time_to_birthday = abs(my_birthday - today) days = turtle.Turtle() setup = turtle.Turtle() setup.penup() setup.goto(-100, -20) months = turtle.Turtle() months.penup() months.goto(0, 20) days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] while True: today = date.today() today == date.fromtimestamp(time.time()) days_in = days_in_month[today.month] if my_birthday < today: my_birthday = my_birthday.replace(year=today.year + 1) time_to_birthday = abs(my_birthday - today) time_to_birthday_2 = time_to_birthday.days / days_in time_to_birthday_2 = int(time_to_birthday_2) if time_to_birthday_2 * days_in != time_to_birthday: time_to_birthday_2 = (str(time_to_birthday_2) + ' months and ' + str(int(time_to_birthday.days) - (time_to_birthday_2 * days_in)) + ' days') months.write(time_to_birthday_2) days.write(str(time_to_birthday.days) + ' days') continue_q = ('are you done?') setup.write('please type in y/n for the following question (you must do this in the shell) ' + continue_q) continue_ = input(continue_q + ' (y/n) ') if continue_ == 'y': break months.clear() days.clear() print('SHUTTING DOWN') time.sleep(3)
jonahmakowski/PyWrskp
src/math-game/game.py
import game_extras from random import randint as r class Game: def __init__(self): while True: try: self.max = int(input('What would you like the max of the nums\n')) break except: print('ERROR: this is not a number, try again') while True: try: self.min = int(input('What would you like the min of the nums\n')) break except: print('ERROR: this is not a number, try again') self.neg = input('Would you like negitive numbers and decimal numbers? (y/n)\n') self.money = 0 self.wrong = 0 self.correct = 0 while self.wrong <= 20: option = r(1, 4) if option == 1: self.add() elif option == 2: self.sub() elif option == 3: self.multi() elif option == 4: self.div self.over() def add(self): num1, num2, a = game_extras.add(self.max, self.min) while True: try: ask = int(input('What is {} + {}?\n'.format(num1, num2))) break except: print('ERROR: this is not a number, try again') print(num1, num2, a, ask) if ask == a: self.correct += 1 self.money += 1 print('You have {} correct'.format(self.correct)) print('You have {} money'.format(self.money)) elif ask != a: self.wrong += 1 self.money -= 10 print('you lost 10 money, you now have {} money'.format(self.money)) print('you got {} wrong so far'.format(self.wrong)) def sub(self): num1, num2, a = game_extras.sub(self.max, self.min, self.neg) while True: try: ask = int(input('What is {} - {}?\n'.format(num1, num2))) break except: print('ERROR: this is not a number, try again') print(num1, num2, a, ask) if ask == a: self.correct += 1 self.money += 7.5 print('You have {} correct'.format(self.correct)) print('You have {} money'.format(self.money)) elif ask != a: self.wrong += 1 self.money -= 7.5 print('you lost 7.5 money, you now have {} money'.format(self.money)) print('you got {} wrong so far'.format(self.wrong)) def multi(self): num1, num2, a = game_extras.multi(self.max, self.min) while True: try: ask = int(input('What is {} * {}?\n'.format(num1, num2))) break except: print('ERROR: this is not a number, try again') print(num1, num2, a, ask) if ask == a: self.correct += 1 self.money += 5 print('You have {} correct'.format(self.correct)) print('You have {} money'.format(self.money)) elif ask != a: self.wrong += 1 self.money -= 5 print('you lost 5 money, you now have {} money'.format(self.money)) print('you got {} wrong so far'.format(self.wrong)) def div(self): num1, num2, a = game_extras.div(self.max, self.min, self.neg) while True: try: ask = int(input('What is {} / {}?\n'.format(num1, num2))) break except: print('ERROR: this is not a number, try again') print(num1, num2, a, ask) if ask == a: self.correct += 1 self.money += 2.5 print('You have {} correct'.format(self.correct)) print('You have {} money'.format(self.money)) elif ask != a: self.wrong += 1 self.money -= 2.5 print('you lost 2.5 money, you now have {} money'.format(self.money)) print('you got {} wrong so far'.format(self.wrong)) def over(self): print('GAME OVER') print('Wrong:\t{}'.format(self.wrong)) print('Correct:\t{}'.format(self.correct)) print('Money:\t{}'.format(self.money)) game = Game()
jonahmakowski/PyWrskp
src/coder-decoder/coder_run.py
<filename>src/coder-decoder/coder_run.py from coder import CoderDecoder code = CoderDecoder() message = input('What is your message?\n') while True: key = int(input('what is the key? (from 1 to {})\n'.format(len(code.abcs)))) if key >= 1 and key < len(code.abcs): break else: print('inccorrect number') code.add_vars(message, key) code_decode = input('Would you like to code or decode?') if code_decode == 'code': code.code() elif code_decode == 'decode': code.decode()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/users.py
<reponame>jonahmakowski/PyWrskp<gh_stars>0 from datetime import date class Human: def __init__(self, fname, lname, age, tec_age=False, _ = None): self.shut_off = False self.pin = 1982 self.today = date.today() if tec_age == True: if _ == '+': tec_age = age + 1 if _ == '-': tec_age = age - 1 else: tec_age = age self.info = {'name':{'first name':fname,'last name':lname}, 'age':{'str':str(age),'int':int(age),'tec_age':{'str':str(tec_age),'int':int(tec_age)}}, 'login':False} def figure(n_fname, n_lname, year): if (self.info['name']['first name'] == n_fname and self.info['name']['last name'] == n_lname) and ( self.today.year - year) == self.info['age']['tec_age']['int']: return True else: return False self.Noah = figure('Noah', 'Makowski', 2013) if self.Noah: self.info['Password'] = '<PASSWORD>' self.Jonah = figure('Jonah', 'Makowski', 2010) if self.Jonah: self.info['Password'] = '<PASSWORD>' self.admin_usr = False self.var = {'info':self.info, 'today':self.today, 'Noah':self.Noah, 'Jonah':self.Jonah, 'admin usr':self.admin_usr, 'pin':self.pin, 'shut off':self.shut_off} self.home() def login(self): while True: if self.Noah == False and self.Jonah == False: return 'Guest' else: password = input('What is the password ' + self.info['name']['first name'] + '?\n') if password == self.info['Password']: if self.Jonah: self.admin_login() self.info['login'] = True return True elif password != self.info['Password']: self.kick_out() def admin_login(self): code_name = input('What is your codename ' + self.info['name']['first name'] + ' ') code_name_title = input('What is your codename title? ') if code_name == 'Joe' and code_name_title == ", Lola's spy": pin = input("what is Jonah's pin? ") if pin == str(self.pin): self.admin_usr = True else: self.kick_out() def kick_out(self): print('INCORRECT!') print('YOU ARE BEING KICKED OUT') print('LOADING') p = '-' from time import sleep length = 20 dec = 0 i = 0 while True: print('') print(p + ' ({}%)'.format(str(dec))) sleep(1) dec = (i / length) * 100 p = p + '-' i += 1 if dec == 105: self.shut_off = True self.sleep() def sleep(self): if self.shut_off: print('Sleep has been activated') while True: pass else: print('you are being rederict back') return def home(self): d = self.login() if self.admin_usr: print('Welcome admin!') print('Now redirecting you to the admin page:') self.admin() if not self.shut_off: print('Welcome ' + self.info['name']['first name'] + '!') while True: pass def admin(self): if self.admin_usr == False or self.info['login'] == False: self.home() print('Welcome to admin {}!'.format(self.info['name']['first name'])) print("Today's ({}) report".format(self.today.strftime("%d %B, %Y"))) report = input("Today's report is that Lola is being very cute, and that she is the best dog ever\n") if report == 'y': self.pin = 1892 pin = input("what is Jonah's pin? ") if pin == str(self.pin): self.admin_usr = True if d == 'Guest' or self.admin_usr == False: self.home() else: print('opening real report:') f_name = input('what is your (first) name?\n') l_name = input('What is your last name?\nif you enter nothing, it will enter a guest\n') if l_name == '': l_name = 'Guest' while True: try: age = int(input('how old are you?\n')) break except: print('That is not a number') while True: try: tec_age = int(input('what is your tec age?\nyour tec age is say you were born in 2009, and today it is the year 2021, then your tec age would be 12\n')) break except: print('That is not a number') if tec_age == age: item = False elif tec_age != age: item = True if tec_age > age: _ = '+' elif tec_age < age: _ = '-' try: usr = Human(f_name, l_name, age, tec_age=item, _=_) except: usr = Human(f_name, l_name, age, tec_age=item)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/date_time_testing.py
import datetime from dateutil import relativedelta bday = datetime.date(2010, int(input('What month were you born in (numbers please)\n')), int(input('What day of the month were you born in (numbers please)\n'))) today = datetime.date.today() age = today - bday cur_yr = today.year next_bday = bday.replace(year=cur_yr) if next_bday < today: # already passed this year, consider bday next year next_bday = next_bday.replace(year=cur_yr + 1) diff = next_bday - today diff2 = relativedelta.relativedelta(next_bday, today) n_months = diff2.months n_days = diff2.days if n_months == 0 and n_days == 0: print('Your birthsday is TODAY.') else: # print('Next birthday is in ' + (str(n_months)) + ' months and ' + (str(n_days)) + ' days.') import turtle import time t = turtle.Turtle() while True: diff2 = relativedelta.relativedelta(next_bday, today) n_months = diff2.months n_days = diff2.days t.write('your next birthday is in ' + (str(n_months)) + ' months and ' + (str(n_days)) + ' days.') time.sleep(86400) # wait one t.clear() pass
jonahmakowski/PyWrskp
src/other/human_classes.py
<filename>src/other/human_classes.py from datetime import datetime from random import randint class Human: def __init__(self, gender, first_name, last_name, birth_year): self.gender = gender self.first_name = first_name self.last_name = last_name self.birth_year = birth_year current_year = datetime.now().year self.age = current_year - birth_year def talk(self, text): print('{} {}: {}'.format(self.first_name, self.last_name, text)) def good_thing(self): options = ['Lola is the best', 'I had PE at school today', 'I played Roblox with my friends today', 'We went sledding', 'I had fun with my students today', 'We went to Bronte today'] rad = randint(0, len(options) - 1) txt = 'Good thing: {}'.format(options[rad]) self.talk(txt) def bad_thing(self): options = ['We went to Bronte today', 'I had to wake up at 6:00 am today for swimming'] rad = randint(0, len(options) - 1) txt = 'Bad thing: {}'.format(options[rad]) self.talk(txt) Jonah = Human('male', 'Jonah', 'Makowski', 2010) Noah = Human('male', 'Noah', 'Makowski', 2013) Papa = Human('male', 'Maciej', 'Makowski', 1980) Mama = Human('female', 'Karolina', 'Werner', 1979) class Family: def __init__(self, members=[]): self.members = members def add(self, person): self.members.append(person) def good_thing_bad_thing(self): for i in range(len(self.members)): self.members[i].good_thing() print('\n') self.members[i].bad_thing() print('\n\n') our_family = Family(members=[Jonah, Noah, Papa, Mama]) class House: def __init__(self, family, address_num, address_road, address_extenstion, address_city, address_province, address_country): self.family = family self.address_str = '{} {} {}, {}, {}, {}'.format(address_num, address_road, address_extenstion, address_city, address_province, address_country) self.address_dic = {'num': address_num, 'road': address_road, 'road type': address_extenstion, 'city': address_city, 'province': address_province, 'country': address_country} def day_or_night(self): now_hour = int(datetime.now().hour) if now_hour >= 20: print('night') else: print('day') oakville = House(our_family, 449, 'Valley', 'Dr', 'Oakville', 'Ontario', 'Canada') oakville.day_or_night()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/print_all_combos.py
def printCombination(arr, n, r): data = [0]*r; combinationUtil(arr, data, 0, n - 1, 0, r); def combinationUtil(arr, data, start, end, index, r): # Current combination is ready # to be printed, print it if (index == r): for j in range(r): print(data[j], end = " "); print(); return; i = start; while(i <= end and end - i + 1 >= r - index): data[index] = arr[i]; combinationUtil(arr, data, i + 1, end, index + 1, r); i += 1; arr = []; while True: add = input('what would you like to add?') if add == '': break arr.append(add) r = int(input('size of possiblities')); n = len(arr); printCombination(arr, n, r);
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/examples_to_show_to_jacob.py
<reponame>jonahmakowski/PyWrskp import json # this is a library # This char "#" makes the rest of the line a comment and the computer ignores it """This is a other way to right comments as this can be many lines""" print() # prints the item in the bracket var1 = input('? str') # takes input from the question put in the bracket in this case '? str' (this saves as a string) var2 = int(input('? int')) '''takes input from the question put in the bracket in this case '? int' (this saves as a int), the int() part takes the input and turns it into an int, if it is a word, like "Hello", it will return an error, if it is a float like 0.5 it will also return an error''' var3 = float(input('? float')) '''takes input from the question put in the bracket in this case '? float' (this saves as a float), the float() part takes the input and turns it into a float, if it is a word, like "Hello", it will return an error, if it is a int like 1 it will make the int, 1 into 1.0''' var4 = str(1 + 2) # this will add 1 + 2 and save it as a string, so this would look like "3" in string form var5 = 0 # makes a var that is = to the integer 0 var6 = 'Hello World' # makes a var that is = to the string "Hello world" var7 = 0.5 # makes a var that is = to the float 0.5 var8 = True # this is a boolean value, True or False (it has to start with a capitol in python) var9 = {'first name': 'Jonah', 'middle name': 'Werner', 'last name': 'Makowski', 'age': 11, 'grade': 6, 'firends': ['Jacob', 'Phinn', 'Liam', 'Rafa', '<NAME>', 'Hannah']} '''This is a dictonary, what it is is like a list with a key that is instead of a number what is in the string the item the key is = to is anything, a list, a string, a int, a list, a dictonary, or a float.''' var10 = [var1, var2, var3, var4, var5, var6, var7, var8] # This makes a var = to a list of all of the other vars for i in range(3): # means do 3 times "i" is a counter print('hi') for item in var10: # means for every item in var10 (a list), do this, item is the current item that is going through print(item) while True: # this is a while statment and True can be reaplaced with other objects var5 += 1 # adds and equals 1 if var5 == len(var10): # many things here, if statments are just as they sound, len() counts the number of objects in a list print('the number of objects in var9 are {}'.format(var5)) # .format replaces {} with the object in the brakets break # this cuts out of a loop with open('hello.txt', 'w') as outfile: # how to save a file to the file named "hello.txt" json.dump('Testing message', outfile) # this will save "Testing message" to a txt file with open('hello.txt') as json_file: print(json.load(json_file)) # this will print the info in a file def fuction(): # this is a fuction in the () you can put in info so that it can get info print('fuction testing') # you have to start the fuction name with a lowercase letter fuction() # this is how to call up a fuction class Testing: # this is how to make a class def __init__(self, info): # this is needed in any class it is what happens when the class is first called on info is a paremater self.info = info # this saves info as a file that you can use anyware in the class def print_info(self): # this is a fuction that prints self.info print(self.info) testing = Testing('Hello') # this is how to call a class testing.print_info() # this is how to call a class fuction
jonahmakowski/PyWrskp
src/password_maker/Creater.py
from random import randint import os if __name__ == '__main__': try: pyWrkspLoc = os.environ["PYWRKSP"] except KeyError: pyWrkspLoc = os.environ["HOME"] + input('Since you do not have the PYWRSKP env var ' '\nPlease enter the pwd for the pyWrskp repo not including the ' '"home" section') def create(letter, num, sc, super_c, length, save, print_info, pyWrskp): chars = [] letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] scs = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '~', '`', '{', '}', '[', ']', ';', ':', '"', "'", '<', '>', '?', ',', '.', '/', '|'] super_s_c = ['←', '↑', '→', '↓', '·', '•', '●', '–', '‽', '‖', '«', '»', '‘', '„', '✅', '❤️', '⌘', '', '⌥', '⌫', '∞', '™', '¼', '½', '¾', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'æ', 'Ħ', 'ij', 'Œ', 'œ', '☚', '☛', '★', '☆', '♠', '♣', '♥', '♦', '♪', '♫', '♀'] make = True if letter == 'y': chars += letters if num == 'y': chars += nums if sc == 'y': chars += scs if super_c == 'y': chars += super_s_c if (letter == 'n' and num == 'n') and (sc == 'n' and super_c == 'n'): make = False password = '' if make: for i in range(length): loc = randint(0, len(chars) - 1) password += chars[loc] elif not make: password = '<PASSWORD> in all the questions, so there are no options' if print_info: print(password) if save == 'y': website = input('what website will this password be used by?') from password_saver import add_password, save_passwords add_password(password, website) save_passwords(pyWrskp) if print_info: print('your password, {} has been added to your saved passwords!'.format(password)) return password if __name__ == "__main__": create(input('Would you like letters? (ex. A, b, c)'), input('Would you like numbers? (ex. 1, 2, 3)'), input('Would you like special chars? (ex. @, %, -)'), input('Would you like super special chars (ex. ←, ↑, →), ' '\nsome websites may not allow this, if it does not work turn this off'), int(input('how long would you like your password to be?')), input('Would you like to save your password to passwords.txt? (y/n)'), True, pyWrkspLoc)
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/class_2a.py
import pygame DIS_WIDTH = 1280 DIS_HEIGHT = 820 pygame.init() screen = pygame.display.set_mode([DIS_WIDTH, DIS_HEIGHT]) pygame.display.set_caption("Paint") keep_going = True mouse_down = False BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) GREY = (131, 131, 131) currentColour = RED radius = 15 recWidth = int(DIS_WIDTH * 0.1) recHeight = int(DIS_HEIGHT * 0.09) redRectangle = pygame.Rect((0, 0), (recWidth, recHeight)) greenRectangle = pygame.Rect((recWidth, 0), (recWidth, recHeight)) blueRectangle = pygame.Rect(((recWidth * 2), 0), (recWidth, recHeight)) button_size = int(recHeight / 2) topRectangle = pygame.Rect((0, 0), (DIS_WIDTH, recHeight + button_size)) buttonMinus = pygame.image.load('button_minus.png') buttonPlus = pygame.image.load('button_plus.png') buttonMinus = pygame.transform.scale(buttonMinus, (button_size, button_size)) buttonPlus = pygame.transform.scale(buttonPlus, ((button_size), button_size)) minusRect = buttonMinus.get_rect(topleft = (0, recHeight)) plusRect = buttonPlus.get_rect(topleft = (recHeight, recHeight)) while keep_going: for event in pygame.event.get(): if event.type == pygame.QUIT: keep_going = False elif event.type == pygame.MOUSEBUTTONDOWN: spot = pygame.mouse.get_pos() if minusRect.collidepoint(spot): if radius > 5: radius -= 5 if plusRect.collidepoint(spot): if radius < 50: radius += 5 else: mouse_down = True elif event.type == pygame.MOUSEBUTTONUP: mouse_down = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: screen.fill(BLACK) if event.key == pygame.K_r: radius = 15 if event.key == pygame.K_q: if radius < 45: radius += 5 if event.key == pygame.K_a: if radius > 5: radius -= 5 if mouse_down: # if the event is pressing the mouse # get the current position of the mouse spot = pygame.mouse.get_pos() if redRectangle.collidepoint(spot): currentColour = RED elif greenRectangle.collidepoint(spot): currentColour = GREEN elif blueRectangle.collidepoint(spot): currentColour = BLUE else: # if it's not within a button, place a circle at the spot the mouse was pressed pygame.draw.circle(screen, currentColour, spot, radius) pygame.draw.rect(screen, GREY, topRectangle) pygame.draw.circle(screen, currentColour, (DIS_WIDTH - radius, radius), radius) pygame.draw.rect(screen, RED, redRectangle) pygame.draw.rect(screen, GREEN, greenRectangle) pygame.draw.rect(screen, BLUE, blueRectangle) screen.blit(buttonMinus, minusRect) screen.blit(buttonPlus, plusRect) pygame.display.update() pygame.quit()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/testing.py
<gh_stars>0 import os shutdown = input("Do you wish to shutdown your computer ? (yes / no): ") if shutdown == 'no': exit() else: os.system("shutdown")
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/mm1.py
<reponame>jonahmakowski/PyWrskp # don't use file-name: turtle.py import turtle from random import randint import time t = turtle.Turtle() t.penup() t.goto (-140,140) t.speed(0) t.pendown() screen = turtle.Screen() # screen.setup(500,500) # draw race-lines for i in range (8): t.forward(318) t.backward(318) t.right(90) t.penup() t.forward(40) t.left(90) t.pendown() # draw the tick finish-line t.penup() t.left(90) t.forward(40) t.right(90) t.forward(315) t.left(90) t.pendown() t.forward(280) for l in range(10): t.right(90) t.forward(1) t.right(90) t.forward(280) t.backward(280) t.left(180) t.penup() t.goto(-150,200) t.color('white') # colors of racers, implicitly define the number of racers colors = ['Red', 'Blue', 'Lime', 'Violet', 'Orange', 'Gray', 'Black'] n_racers = len(colors) racers = [] x_start = -160 y_start = 120 y_current = 120 y_delta = 40 # create racers and position each of them at its start position (the corresponding line-beginning) for col in colors: racer = turtle.Turtle() racer.shape('turtle') racer.color(col) racer.speed(0) racer.penup() racer.goto(x_start, y_current) racers.append(racer) y_current -= y_delta # show start-preparation signal-markers and 'Go' maker = turtle.Turtle() maker.penup() # maker.goto(-160,160) maker.goto(x_start, y_start + y_delta) maker.speed(0) for i in range(4): maker.write(i) maker.forward(20) time.sleep(0.5) maker.write('Go') maker.color('white') time.sleep(0.5) # race: n_steps, at each step a random speed for each racer n_steps = 110 for turn in range(n_steps): for racer in racers: racer.speed(randint(1,10)) racer.forward(randint(1,5)) results = {} # dictionary of results for i in range(n_racers): # store the results in the dictionary results[colors[i]] = int(racers[i].xcor()) # print(results) # uncomment to see the dictionary items # sort the results and print from collections import Counter # use the Counter from the collections to sort the race results c = Counter(results) results_sort = c.most_common() # most_common() sorts the dictionary items in ascending order # print(results_sort) # uncomment to see the unformatted sorted results place = 1 print('Results of the race sorted by the distance:') for item in results_sort: print('Place ' + str(place) + ': ' + item[0] + ', distance = '+ str(item[1])) place += 1 print('Hit the return/enter key to finish.') input()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/bday2.py
# compute number of months and days from today to my next bday # import sys needed if sys.exit() used import datetime from dateutil import relativedelta # handle and process the bday data class NextBday: def __init__(self, b_month, b_day, b_yr=0, cheat_today=False): self.use_dateutl = True # set to False, if dateutil not available try: assert not (b_month < 1 or b_month > 12) except AssertionError: print('Month number must be in [1, 12]. Provided value of ' + str(b_month) + ' is illegal.') # sys.exit('wrong month') raise try: # Note: this is incomplete check (one can e.g., specify Apr 31 or Feb 30) assert not(b_day < 1 or b_day > 31) except AssertionError: print('Day number must be in [1, 31]. Provided value of ' + str(b_day) + ' is illegal.') # sys.exit('wrong day') raise self.b_month = b_month self.b_day = b_day self.b_yr = b_yr # optional bday-year; if defined then the age is calculated if cheat_today: # for testing: set below a date to be used as today's date cheated = datetime.date(2021, 5, 29) self.today = cheated else: self.today = datetime.date.today() self.cur_yr = self.today.year if b_yr: self.bday_defined = True self.birth = datetime.date(b_yr, b_month, b_day) else: self.bday_defined = False self.birth = datetime.date(self.cur_yr, b_month, b_day) self.next_bday = self.birth.replace(year=self.cur_yr) if self.next_bday < self.today: # already passed this year, consider bday next year self.next_bday = self.next_bday.replace(year=self.cur_yr + 1) def bday_info(self): print('Today is: ' + str(self.today)) if self.bday_defined: print('On ' + str(self.next_bday) + ' you will be ' + str(self.next_bday.year - self.birth.year) + ' years old.') else: print('Your next birthday will be on: ' + str(self.next_bday)) def bday_in(self): # calculate and print number of months and days until next birthday if not self.use_dateutl: self.bday_in2() # do the calculation without using dateutil return away = relativedelta.relativedelta(self.next_bday, self.today) n_months = away.months n_days = away.days if n_months == 0 and n_days == 0: print('Your birthsday is TODAY.') else: print('You have to wait ' + (str(n_months)) + ' months and ' + (str(n_days)) + ' days for your bday party.') # calculate and print number of months and days until next birthday without using datautil # place-holder for the code to be written by Jonas def bday_in2(self): print('bday_in2() not implemented yet') print('Number of months and days until ' + str(self.next_bday) + ' not available.') # testing the NextBday class bday = NextBday(3, 29, 1946) # ctor with full bday (month, day, yr) bday.bday_info() bday.bday_in() # print('\nNext test:') bday = NextBday(5, 29) # ctor without the birth-year bday.bday_info() bday.bday_in() # print('\nNext test:') bday = NextBday(5, 29, 2010, True) # ctor for testing (uses the Today value specified in the ctor) bday.bday_info() bday.bday_in() pass
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/class_6_homework.py
<gh_stars>0 import requests # get the weather of the white house street = '1600+Pennsylvania+Avenue+NW' city = 'Washington' state = 'DC' zipcode = "20500" geocode = requests.get("https://geocoding.geo.census.gov/geocoder/locations/address?street={}&city={}&state={}&zip={}&benchmark=4&format=json".format(street, city, state, zipcode)) coordinates = geocode.json()['result']['addressMatches'][0]['coordinates'] gridpoints = requests.get('https://api.weather.gov/points/{},{}'.format(coordinates['y'], coordinates['x'])) forecast = requests.get(gridpoints.json()['properties']['forecastHourly']) # print(forecast.text) # uncomment to print raw forecast info pl = input('Would you like a chart? (y/n) ') if pl == 'y': pl = True else: pl = False time = str(forecast.json()['properties']['periods'][0]['startTime']) time = time[-5:] hour = int(time[:-3]) tick = 0 if not pl: for hr in forecast.json()['properties']['periods']: time = str(hour) + ':00' print('{} {}, {} \n{} \n\n'.format(time, hr['temperature'], hr['temperatureUnit'], hr['shortForecast'])) hour += 1 if hour == 25: hour = 1 tick += 1 if tick == 24: break if pl: import matplotlib.pyplot as plt times, temp = [], [] for hr in forecast.json()['properties']['periods']: time = str(hour) + ':00' times.append(time) temp.append(hr['temperature']) hour += 1 if hour == 25: hour = 1 tick += 1 if tick == 24: break fig = plt.figure() fig.set_figheight(10) fig.set_figwidth(15) plt.plot(times, temp, 'o-') plt.gcf().autofmt_xdate() plt.grid() plt.show()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/exec_coding.py
<gh_stars>0 def run_code(code): exec(code) code = '' print('what is your code (enter = new line):') while True: cod = input() if cod == '': break code += cod + '\n' run_code(code)
jonahmakowski/PyWrskp
src/other/turtle_stuff.py
import turtle import time import random class Turtle: def __init__(self): self.t = turtle.Turtle() self.t.speed(0) self.border = 500 def grid(self): self.t.pd() def draw(t, length): t.pd() t.forward(length) t.left(90) t.pu() t.forward(25) t.left(90) t.forward(length) t.right(180) self.t.penup() self.t.goto(-500, 420) self.t.right(90) for i in range(35): draw(self.t, 800) self.t.right(90) for i in range(33): draw(self.t, 900) time.sleep(5) def shape(self): self.t.pd() sides = int(input('How many sides?')) length = int(input('How long?')) corner = 360 / sides self.t.pu() self.t.goto(0, 0) self.t.pd() for i in range(sides): self.t.forward(length) self.t.right(corner) time.sleep(5) def scribble(self): self.t.pd() self.t.shape('turtle') self.t.speed(5) blue = turtle.Turtle() green = turtle.Turtle() yellow = turtle.Turtle() pink = turtle.Turtle() purple = turtle.Turtle() black = turtle.Turtle() brown = turtle.Turtle() gray = turtle.Turtle() red = turtle.Turtle() blue.color('blue') green.color('green') yellow.color('yellow') pink.color('pink') purple.color('purple') black.color('black') brown.color('brown') gray.color('gray') red.color('red') blue.pu() green.pu() yellow.pu() pink.pu() purple.pu() brown.pu() gray.pu() red.pu() blue.goto(0, 0) green.goto(-self.border, self.border) yellow.goto(-self.border, -self.border) pink.goto(self.border, self.border) purple.goto(self.border, -self.border) brown.goto(0, 0) gray.goto(-self.border, self.border) red.goto(-self.border, -self.border) blue.pd() green.pd() yellow.pd() pink.pd() purple.pd() brown.pd() gray.pd() red.pd() turtles = [blue, green, yellow, pink, purple, yellow, black, brown, gray, red] colors = ['blue', 'green', 'yellow', 'black', 'purple', 'pink', 'brown', 'gray', 'red'] while True: for item in turtles: item.shape('circle') item.speed(0) item.goto(random.randint(-self.border, self.border), random.randint(-self.border, self.border)) x = item.xcor() y = item.ycor() self.t.color(colors[random.randint(0, len(colors) - 1)]) self.t.goto(x, y) tit = Turtle() while True: do = input('What do you wish to do?\n') if do == 'grid': tit.grid() elif do == 'shape': tit.shape() elif do == 'scribble': tit.scribble() else: print('That is not an option try again')
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/classes/class_4_pt_2.py
<filename>src/other/Other_from_2020-2021/classes/class_4_pt_2.py import class_4_pt_1 import tkinter as tk df_save_loc = '/home/jonah/Thonny files/TXT_files/' # change to folder name where you want auto saves as def df_name = 'testing' # you can change def save name root = tk.Tk() root.title('Text Editer') root.rowconfigure(0, minsize=800, weight=1) root.columnconfigure(1, minsize=600, weight=1) app = class_4_pt_1.Application(df_name, df_save_loc, master=root) app.mainloop()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/class2020/class_one1.py
import pygame print('version 1') pygame.init() screen = pygame.display.set_mode([1375, 750]) pygame.display.set_caption( "Click the color-square to change the current color; the space-bar changes the background color") keep_going = True mouse_down = False # defines colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) PURPLE = (251, 0, 255) YELLOW = (255, 247, 0) TEAL = (0, 255, 255) ORANGE = (255, 196, 0) LIME = (132, 255, 0) currentColour = BLUE screen.fill(currentColour) pygame.display.update() radius = 10 # defines rectangles redRectangle = pygame.Rect((0, 0), (50, 50)) greenRectangle = pygame.Rect((50, 0), (50, 50)) blueRectangle = pygame.Rect((100, 0), (50, 50)) blackRectangle = pygame.Rect((150, 0), (50, 50)) purpleRectangle = pygame.Rect((200, 0), (50, 50)) yellowRectangle = pygame.Rect((250, 0), (50, 50)) tealRectangle = pygame.Rect((300, 0), (50, 50)) orangeRectangle = pygame.Rect((350, 0), (50, 50)) limeRectangle = pygame.Rect((400, 0), (50, 50)) whiteRectangle = pygame.Rect((450, 0), (50, 50)) dotRectangle5 = pygame.Rect((500, 0), (50, 50)) dotRectangle10 = pygame.Rect((550, 0), (50, 50)) dotRectangle15 = pygame.Rect((600, 0), (50, 50)) dotRectangle20 = pygame.Rect((650, 0), (50, 50)) dotRectangle25 = pygame.Rect((700, 0), (50, 50)) while keep_going: for event in pygame.event.get(): if event.type == pygame.QUIT: keep_going = False elif event.type == pygame.MOUSEBUTTONDOWN: mouse_down = True elif event.type == pygame.MOUSEBUTTONUP: mouse_down = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: screen.fill(currentColour) pygame.display.update() if mouse_down: # if the event is pressing the mouse # get the current position of the mouse spot = pygame.mouse.get_pos() x = spot[0] y = spot[1] if y > 50 or x >= 750: pygame.draw.circle(screen, currentColour, spot, radius) pygame.display.update() elif x < 50: # if the current position is within the red square, change the colour to red currentColour = RED elif x < 100: # if the current position is within the green square, change the colour to green currentColour = GREEN elif x < 150: # if the current position is within the blue square, change the colour to blue currentColour = BLUE elif x < 200: # if the current position is within the black square, change the colour to black currentColour = BLACK elif x < 250: # if the current position is within the purple square, change the colour to purple currentColour = PURPLE elif x < 300: # if the current position is within the yellow square, change the colour to yellow currentColour = YELLOW elif x < 350: # if the current position is within the teal square, change the colour to teal currentColour = TEAL elif x < 400: # if the current position is within the orange square, change the colour to orange currentColour = ORANGE elif x < 450: # if the current position is within the lime square, change the colour to lime currentColour = LIME elif x < 500: # if the current position is within the white square, change the colour to white currentColour = WHITE elif x < 550: # if touching the small circle change pensize to 5 radius = 5 elif x < 600: # if touching the small circle change pensize to 10 radius = 10 elif x < 650: # if touching the small circle change pensize to 15 radius = 15 elif x < 700: # if touching the small circle change pensize to 20 radius = 20 elif x < 750: # if touching the small circle change pensize to 25 radius = 25 # draws rectangles pygame.draw.rect(screen, RED, redRectangle) pygame.draw.rect(screen, GREEN, greenRectangle) pygame.draw.rect(screen, BLUE, blueRectangle) pygame.draw.rect(screen, BLACK, blackRectangle) pygame.draw.rect(screen, PURPLE, purpleRectangle) pygame.draw.rect(screen, YELLOW, yellowRectangle) pygame.draw.rect(screen, TEAL, tealRectangle) pygame.draw.rect(screen, ORANGE, orangeRectangle) pygame.draw.rect(screen, LIME, limeRectangle) pygame.draw.rect(screen, WHITE, whiteRectangle) # pygame.display.update()a # not needed pygame.draw.rect(screen, BLACK, dotRectangle5) pygame.draw.rect(screen, BLACK, dotRectangle10) pygame.draw.rect(screen, BLACK, dotRectangle15) pygame.draw.rect(screen, BLACK, dotRectangle20) pygame.draw.rect(screen, BLACK, dotRectangle25) # draws circles pygame.draw.circle(screen, WHITE, (525, 25), 5) pygame.draw.circle(screen, WHITE, (575, 25), 10) pygame.draw.circle(screen, WHITE, (625, 25), 15) pygame.draw.circle(screen, WHITE, (675, 25), 20) pygame.draw.circle(screen, WHITE, (725, 25), 25) pygame.display.update() pygame.quit()
jonahmakowski/PyWrskp
src/logs/logs.py
<gh_stars>0 import os import json import datetime class Log: def __init__(self, save_loc=None): self.log = [] save_loc = os.getcwd() + '/save_loc.txt' self.save_locs = self.load(save_loc) self.loc = os.environ["HOME"] new_or_old = input('Do you need a new txt file?') if new_or_old == 'new': self.name = self.loc + input('Where do you want the logs to be stored?') self.save_locs.append(self.name) else: print('your options are:') if len(self.save_locs) > 0: for i in range(len(self.save_locs)): print('Option number: {}, loc: {}'.format(i, self.save_locs[i])) else: print('There are no options') print('Ending program') exit(404) save_num = int(input('What is the save number?')) self.name = self.save_locs[save_num] try: self.log = self.load(self.name) print('loading info') except FileNotFoundError: print('Creating new txt file') self.save(save_loc, self.save_locs) self.mainloop() def load(self, loc): with open(loc) as json_file: item = json.load(json_file) return item def save(self, loc, item): with open(loc, 'w') as outfile: json.dump(item, outfile) def mainloop(self): while True: do = input('What do you want to do?') if do == 'add': self.add() break elif do == 'read': self.read() break elif do == 'clear': self.clear() break else: print('This is not an option') print('Try again') def add(self): log_info = input('What do you want to add to the log?\n') time = datetime.datetime.now() time = time.strftime("%d/%m/%y %H:%M") time = datetime.datetime.strptime(time, "%d/%m/%y %H:%M") time = "{:d}:{:02d}".format(time.hour, time.minute) date = {'day': datetime.datetime.now().day, 'month': datetime.datetime.now().month, 'year': datetime.datetime.now().year} current_log = {'time': time, 'date': date, 'info': log_info} self.log.append(current_log) self.save(self.name, self.log) post_date = '{}-{}-{}'.format(current_log['date']['month'], current_log['date']['day'], current_log['date']['year']) print('your message, {} and the time and date, {}, {}, have been saved!'.format(log_info, post_date, time)) def read(self): self.log = self.load(self.name) print('Date\ttime\tInfo') unreadable = 0 for item in self.log: try: post_date = '{}-{}-{}'.format(item['date']['month'], item['date']['day'], item['date']['year']) print('{}\t{}\t{}'.format(post_date, item['time'], item['info'])) except KeyError: unreadable += 1 # print('No information can be taken from this log entry, this might be from an older version') if unreadable > 0: print('\n\n') print('There are {} log entries that were either from an older version, or were entered directly into ' 'the txt file'.format(unreadable)) def clear(self): self.log = [] self.save(self.name, self.log) log = Log()
jonahmakowski/PyWrskp
src/other/Other_from_2020-2021/home/math game.py
<reponame>jonahmakowski/PyWrskp money = 0 streak = 0 number_correct = 0 correct = 0 #import os while True: try: ma = int(input('what would you like the largest number possible to be?\n')) except: pass if ma < 10: print('The largest possible number must be 10 or greater') else: break def question(num1, num2, typ): if typ == '*': q = 'What is {} * {}?\n'.format(num1, num2) a = num1 * num2 elif typ == '/': if num2 > num1: num2, num1 = num1, num2 q = 'What is {} / {}?\n'.format(num1, num2) a = num1 / num2 elif typ == '+': q = 'What is {} + {}?\n'.format(num1, num2) a = num1 + num2 elif typ == '-': if num2 > num1: num2, num1 = num1, num2 q = 'What is {} - {}?\n'.format(num1, num2) a = num1 - num2 while True: an = input(q) try: an = float(an) break except: pass if an == a: return True elif an == False: return False else: print('The correct A is {}'.format(a)) return False def money_adding(addby, removeby, question, money): global streak global number_correct global correct if question == True: money += addby streak += 1 number_correct += 1 correct += 1 else: money -= removeby streak = 0 correct -= 1 print('You have ${}!'.format(money)) print('You have a streak of {}'.format(streak)) print('You have gotten {} correct'.format(number_correct)) return money from random import randint as rand addby = 10 removeby = 5 while True: #os.system("clear") TERM = True num = rand(1,4) num1 = rand(1,ma) num2 = rand(1,ma) if num == 1: q = question(num1, num2, '*') money = money_adding(addby, removeby, q, money) elif num == 2: q = question(num1, num2, '/') money = money_adding(addby, removeby, q, money) elif num == 3: q = question(num1, num2, '+') money = money_adding(addby, removeby, q, money) elif num == 4: q = question(num1, num2, '-') money = money_adding(addby, removeby, q, money) if correct == -10: print('you have gotten 10 wrong in a row, would you like to stop? (y/n)') stop = input('') if stop == 'y': break else: correct = 0 print('You have ${}!'.format(money)) print('You have a streak of {}'.format(streak)) print('You have gotten {} correct'.format(number_correct)) print('Thank you for playing!')
jonahmakowski/PyWrskp
src/alarm/alarm-time&date.py
<reponame>jonahmakowski/PyWrskp import datetime hour = int(input('What is the hour number? - form 1 to 24')) mint = int(input('What is the min number? - from 0 to 59')) day = int(input('What is the day? - from 1 to 31')) month = int(input('What is the mounth? - from 1 to 12')) year = int(input('What is the year?')) now = datetime.datetime.now() past_time = datetime.datetime(year, month, day, hour, mint, 0) now_list = str(now) now_list = list(now_list) now_list = now_list[:-7] now_list2 = '' for char in now_list: now_list2 += char now_list = now_list2 while True: now = datetime.datetime.now() now_list = str(now) now_list = list(now_list) now_list = now_list[:-7] now_list2 = '' for char in now_list: now_list2 += char now_list = now_list2 if now == past_time: print('DING-DONG') print('Time up!') break # print('Now ' + str(now)) # print('Then ' + str(past_time))
jonahmakowski/PyWrskp
src/other/info_saver.py
<reponame>jonahmakowski/PyWrskp import json class InfoSaver: def __init__(self): self.loc = '../../docs/txt-files/info_saver.txt' self.save_info = self.load(self.loc) self.mainloop() def mainloop(self): user_type = input('are you a new or old user? (n/o)') if user_type == 'n': username = input('What is the username you wish to set?') try: testing = self.save_info[username] print('This username is being used') exit(404) except KeyError: print('Username granted') password = input('What do you wish the password to be?') self.save_info[username] = {'password': password, 'info': []} self.save(self.loc, self.save_info) print('Info Saved') else: username = input('What is the Username?') password = input('<PASSWORD>') do = input('What do you wish to do?') try: testing = self.save_info[username] if testing['password'] == password: print('Good job, moving on') else: print('Password is wrong') exit(404) except KeyError: print('This username does not exist') exit(404) if do == 'add': info = input('What do you wish to add?') self.save_info[username]['info'].append(info) self.save(self.loc, self.save_info) print('your info {} is saved'.format(info)) elif do == 'print': self.save_info = self.load(self.loc) for item in self.save_info[username]['info']: print(item) def load(self, loc): with open(loc) as json_file: item = json.load(json_file) return item def save(self, loc, item): with open(loc, 'w') as outfile: json.dump(item, outfile) info = InfoSaver()